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.

GrammerJsonResponse.md 1.8 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Grammer json response
  2. ```cs
  3. using LLama.Common;
  4. using LLama.Grammars;
  5. public class GrammarJsonResponse
  6. {
  7. public static async Task Run()
  8. {
  9. var gbnf = (await File.ReadAllTextAsync("Assets/json.gbnf")).Trim();
  10. var grammar = Grammar.Parse(gbnf, "root");
  11. Console.Write("Please input your model path: ");
  12. var modelPath = Console.ReadLine();
  13. var parameters = new ModelParams(modelPath)
  14. {
  15. ContextSize = 1024,
  16. Seed = 1337,
  17. GpuLayerCount = 5
  18. };
  19. using var model = LLamaWeights.LoadFromFile(parameters);
  20. var ex = new StatelessExecutor(model, parameters);
  21. Console.ForegroundColor = ConsoleColor.Yellow;
  22. 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\"");
  23. Console.ForegroundColor = ConsoleColor.White;
  24. using var grammarInstance = grammar.CreateInstance();
  25. var inferenceParams = new InferenceParams()
  26. {
  27. Temperature = 0.6f,
  28. AntiPrompts = new List<string> { "Question:", "#", "Question: ", ".\n" },
  29. MaxTokens = 50,
  30. Grammar = grammarInstance
  31. };
  32. while (true)
  33. {
  34. Console.Write("\nQuestion: ");
  35. Console.ForegroundColor = ConsoleColor.Green;
  36. var prompt = Console.ReadLine();
  37. Console.ForegroundColor = ConsoleColor.White;
  38. Console.Write("Answer: ");
  39. prompt = $"Question: {prompt?.Trim()} Answer: ";
  40. await foreach (var text in ex.InferAsync(prompt, inferenceParams))
  41. {
  42. Console.Write(text);
  43. }
  44. }
  45. }
  46. }
  47. ```