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.2 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.Extension;
  7. using FluentAssertions;
  8. using OpenAI;
  9. using OpenAI.Chat;
  10. namespace AutoGen.OpenAI.Sample;
  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-4o-mini";
  18. var openAIClient = new OpenAIClient(apiKey);
  19. var openAIClientAgent = new OpenAIChatAgent(
  20. chatClient: openAIClient.GetChatClient(model),
  21. name: "assistant",
  22. systemMessage: "You are a helpful assistant designed to output JSON.",
  23. seed: 0, // explicitly set a seed to enable deterministic output
  24. responseFormat: ChatResponseFormat.CreateJsonObjectFormat()) // set response format to JSON object to enable JSON mode
  25. .RegisterMessageConnector()
  26. .RegisterPrintMessage();
  27. #endregion create_agent
  28. #region chat_with_agent
  29. var reply = await openAIClientAgent.SendAsync("My name is John, I am 25 years old, and I live in Seattle.");
  30. var person = JsonSerializer.Deserialize<Person>(reply.GetContent());
  31. Console.WriteLine($"Name: {person.Name}");
  32. Console.WriteLine($"Age: {person.Age}");
  33. if (!string.IsNullOrEmpty(person.Address))
  34. {
  35. Console.WriteLine($"Address: {person.Address}");
  36. }
  37. Console.WriteLine("Done.");
  38. #endregion chat_with_agent
  39. person.Name.Should().Be("John");
  40. person.Age.Should().Be(25);
  41. person.Address.Should().BeNullOrEmpty();
  42. }
  43. #region person_class
  44. public class Person
  45. {
  46. [JsonPropertyName("name")]
  47. public string Name { get; set; }
  48. [JsonPropertyName("age")]
  49. public int Age { get; set; }
  50. [JsonPropertyName("address")]
  51. public string Address { get; set; }
  52. }
  53. #endregion person_class
  54. }