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.md 2.0 kB

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