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.

Use_Json_Mode.cs 2.1 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Use_Json_Mode.cs
  3. using System.Text.Json;
  4. using System.Text.Json.Serialization;
  5. using AutoGen.Core;
  6. using AutoGen.OpenAI;
  7. using AutoGen.OpenAI.Extension;
  8. using Azure.AI.OpenAI;
  9. using FluentAssertions;
  10. namespace AutoGen.BasicSample;
  11. public class Use_Json_Mode
  12. {
  13. public static async Task RunAsync()
  14. {
  15. #region create_agent
  16. var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
  17. var model = "gpt-3.5-turbo";
  18. var openAIClient = new OpenAIClient(apiKey);
  19. var openAIClientAgent = new OpenAIChatAgent(
  20. openAIClient: openAIClient,
  21. name: "assistant",
  22. modelName: model,
  23. systemMessage: "You are a helpful assistant designed to output JSON.",
  24. seed: 0, // explicitly set a seed to enable deterministic output
  25. responseFormat: ChatCompletionsResponseFormat.JsonObject) // set response format to JSON object to enable JSON mode
  26. .RegisterMessageConnector()
  27. .RegisterPrintMessage();
  28. #endregion create_agent
  29. #region chat_with_agent
  30. var reply = await openAIClientAgent.SendAsync("My name is John, I am 25 years old, and I live in Seattle.");
  31. var person = JsonSerializer.Deserialize<Person>(reply.GetContent());
  32. Console.WriteLine($"Name: {person.Name}");
  33. Console.WriteLine($"Age: {person.Age}");
  34. if (!string.IsNullOrEmpty(person.Address))
  35. {
  36. Console.WriteLine($"Address: {person.Address}");
  37. }
  38. Console.WriteLine("Done.");
  39. #endregion chat_with_agent
  40. person.Name.Should().Be("John");
  41. person.Age.Should().Be(25);
  42. person.Address.Should().BeNullOrEmpty();
  43. }
  44. }
  45. #region person_class
  46. public class Person
  47. {
  48. [JsonPropertyName("name")]
  49. public string Name { get; set; }
  50. [JsonPropertyName("age")]
  51. public int Age { get; set; }
  52. [JsonPropertyName("address")]
  53. public string Address { get; set; }
  54. }
  55. #endregion person_class