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 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using LLama.Common;
  2. using LLama.Grammar;
  3. using LLama.Native;
  4. namespace LLama.Examples.NewVersion
  5. {
  6. public class GrammarJsonResponse
  7. {
  8. public static void Run()
  9. {
  10. var grammarBytes = File.ReadAllText("Assets/json.gbnf").Trim();
  11. var parsedGrammar = new GrammarParser();
  12. Console.Write("Please input your model path: ");
  13. var modelPath = Console.ReadLine();
  14. var parameters = new ModelParams(modelPath)
  15. {
  16. ContextSize = 1024,
  17. Seed = 1337,
  18. GpuLayerCount = 5
  19. };
  20. using var model = LLamaWeights.LoadFromFile(parameters);
  21. var ex = new StatelessExecutor(model, parameters);
  22. ParseState state = parsedGrammar.Parse(grammarBytes);
  23. using var grammar = SafeLLamaGrammarHandle.Create(state.Rules, 0);
  24. Console.ForegroundColor = ConsoleColor.Yellow;
  25. 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\"");
  26. Console.ForegroundColor = ConsoleColor.White;
  27. var inferenceParams = new InferenceParams()
  28. {
  29. Temperature = 0.6f,
  30. AntiPrompts = new List<string> { "Question:", "#", "Question: ", ".\n" },
  31. MaxTokens = 50,
  32. Grammar = grammar
  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. foreach (var text in ex.Infer(prompt, inferenceParams))
  43. {
  44. Console.Write(text);
  45. }
  46. }
  47. }
  48. }
  49. }