You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

ChatChineseGB2312.cs 2.9 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using LLama.Common;
  7. namespace LLama.Examples.Examples
  8. {
  9. public class ChatChineseGB2312
  10. {
  11. private static string ConvertFromEncodingToAnother(string input, Encoding original, Encoding target)
  12. {
  13. byte[] bytes = original.GetBytes(input);
  14. var convertedBytes = Encoding.Convert(original, target, bytes);
  15. return target.GetString(convertedBytes);
  16. }
  17. public static async Task Run()
  18. {
  19. Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); // Register gb2312 encoding
  20. Console.Write("Please input your model path: ");
  21. var modelPath = Console.ReadLine();
  22. var prompt = File.ReadAllText("Assets/chat-with-kunkun-chinese.txt", encoding: Encoding.GetEncoding("gb2312")).Trim();
  23. prompt = ConvertFromEncodingToAnother(prompt, Encoding.GetEncoding("gb2312"), Encoding.UTF8);
  24. var parameters = new ModelParams(modelPath)
  25. {
  26. ContextSize = 1024,
  27. Seed = 1337,
  28. GpuLayerCount = 20,
  29. Encoding = Encoding.UTF8
  30. };
  31. using var model = LLamaWeights.LoadFromFile(parameters);
  32. using var context = model.CreateContext(parameters);
  33. var executor = new InteractiveExecutor(context);
  34. var session = new ChatSession(executor).WithHistoryTransform(new LLamaTransforms.DefaultHistoryTransform("用户"));
  35. Console.ForegroundColor = ConsoleColor.Yellow;
  36. Console.WriteLine("This example shows how to use Chinese with gb2312 encoding, which is common in windows. It's recommended" +
  37. " to use https://huggingface.co/hfl/chinese-alpaca-2-7b-gguf/blob/main/ggml-model-q5_0.gguf, which has been verified by LLamaSharp developers.");
  38. Console.ForegroundColor = ConsoleColor.White;
  39. // show the prompt
  40. Console.Write(prompt);
  41. while (true)
  42. {
  43. await foreach (var text in session.ChatAsync(prompt, new InferenceParams()
  44. {
  45. Temperature = 0.3f,
  46. TopK = 5,
  47. TopP = 0.85f,
  48. AntiPrompts = new List<string> { "用户:" },
  49. MaxTokens = 2048,
  50. RepeatPenalty = 1.05f
  51. }))
  52. {
  53. //Console.Write(text);
  54. Console.Write(ConvertFromEncodingToAnother(text, Encoding.UTF8, Encoding.GetEncoding("gb2312")));
  55. }
  56. Console.ForegroundColor = ConsoleColor.Green;
  57. prompt = Console.ReadLine();
  58. Console.ForegroundColor = ConsoleColor.White;
  59. }
  60. }
  61. }
  62. }