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.

GrammarJsonResponse.cs 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using LLama.Common;
  2. using LLama.Grammars;
  3. namespace LLama.Examples.Examples
  4. {
  5. public class GrammarJsonResponse
  6. {
  7. public static async Task Run()
  8. {
  9. string modelPath = UserSettings.GetModelPath();
  10. var gbnf = File.ReadAllText("Assets/json.gbnf").Trim();
  11. var grammar = Grammar.Parse(gbnf, "root");
  12. var parameters = new ModelParams(modelPath)
  13. {
  14. ContextSize = 1024,
  15. Seed = 1337,
  16. GpuLayerCount = 5
  17. };
  18. using var model = LLamaWeights.LoadFromFile(parameters);
  19. var ex = new StatelessExecutor(model, parameters);
  20. Console.ForegroundColor = ConsoleColor.Yellow;
  21. Console.WriteLine("The executor has been enabled. In this example, the LLM will follow your instructions and always respond in a JSON format. For example, you can input \"Tell me the attributes of a good dish\"");
  22. Console.ForegroundColor = ConsoleColor.White;
  23. using var grammarInstance = grammar.CreateInstance();
  24. var inferenceParams = new InferenceParams()
  25. {
  26. Temperature = 0.6f,
  27. AntiPrompts = new List<string> { "Question:", "#", "Question: ", ".\n" },
  28. MaxTokens = 50,
  29. Grammar = grammarInstance
  30. };
  31. while (true)
  32. {
  33. Console.Write("\nQuestion: ");
  34. Console.ForegroundColor = ConsoleColor.Green;
  35. var prompt = Console.ReadLine();
  36. Console.ForegroundColor = ConsoleColor.White;
  37. Console.Write("Answer: ");
  38. prompt = $"Question: {prompt?.Trim()} Answer: ";
  39. await foreach (var text in ex.InferAsync(prompt, inferenceParams))
  40. {
  41. Console.Write(text);
  42. }
  43. }
  44. }
  45. }
  46. }