2024-09-30 16:32:48 -07:00
|
|
|
// Copyright (c) Microsoft Corporation. All rights reserved.
|
2024-07-15 12:33:10 -07:00
|
|
|
// Use_Json_Mode.cs
|
2024-06-30 11:43:22 -07:00
|
|
|
|
|
|
|
using System.Text.Json;
|
|
|
|
using System.Text.Json.Serialization;
|
|
|
|
using AutoGen.Core;
|
2024-08-27 14:37:47 -07:00
|
|
|
using AutoGen.OpenAI.Extension;
|
2024-06-30 11:43:22 -07:00
|
|
|
using FluentAssertions;
|
2024-08-27 14:37:47 -07:00
|
|
|
using OpenAI;
|
|
|
|
using OpenAI.Chat;
|
2024-06-30 11:43:22 -07:00
|
|
|
|
2024-08-30 08:36:20 -07:00
|
|
|
namespace AutoGen.OpenAI.Sample;
|
2024-06-30 11:43:22 -07:00
|
|
|
|
|
|
|
public class Use_Json_Mode
|
|
|
|
{
|
|
|
|
public static async Task RunAsync()
|
|
|
|
{
|
|
|
|
#region create_agent
|
|
|
|
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
|
2024-08-27 14:37:47 -07:00
|
|
|
var model = "gpt-4o-mini";
|
2024-06-30 11:43:22 -07:00
|
|
|
|
|
|
|
var openAIClient = new OpenAIClient(apiKey);
|
|
|
|
var openAIClientAgent = new OpenAIChatAgent(
|
2024-08-27 14:37:47 -07:00
|
|
|
chatClient: openAIClient.GetChatClient(model),
|
2024-06-30 11:43:22 -07:00
|
|
|
name: "assistant",
|
|
|
|
systemMessage: "You are a helpful assistant designed to output JSON.",
|
|
|
|
seed: 0, // explicitly set a seed to enable deterministic output
|
2024-10-15 07:23:33 -07:00
|
|
|
responseFormat: ChatResponseFormat.CreateJsonObjectFormat()) // set response format to JSON object to enable JSON mode
|
2024-06-30 11:43:22 -07:00
|
|
|
.RegisterMessageConnector()
|
|
|
|
.RegisterPrintMessage();
|
|
|
|
#endregion create_agent
|
|
|
|
|
|
|
|
#region chat_with_agent
|
|
|
|
var reply = await openAIClientAgent.SendAsync("My name is John, I am 25 years old, and I live in Seattle.");
|
|
|
|
|
|
|
|
var person = JsonSerializer.Deserialize<Person>(reply.GetContent());
|
|
|
|
Console.WriteLine($"Name: {person.Name}");
|
|
|
|
Console.WriteLine($"Age: {person.Age}");
|
|
|
|
|
|
|
|
if (!string.IsNullOrEmpty(person.Address))
|
|
|
|
{
|
|
|
|
Console.WriteLine($"Address: {person.Address}");
|
|
|
|
}
|
|
|
|
|
|
|
|
Console.WriteLine("Done.");
|
|
|
|
#endregion chat_with_agent
|
|
|
|
|
|
|
|
person.Name.Should().Be("John");
|
|
|
|
person.Age.Should().Be(25);
|
|
|
|
person.Address.Should().BeNullOrEmpty();
|
|
|
|
}
|
|
|
|
|
2024-08-30 08:36:20 -07:00
|
|
|
#region person_class
|
|
|
|
public class Person
|
|
|
|
{
|
|
|
|
[JsonPropertyName("name")]
|
|
|
|
public string Name { get; set; }
|
|
|
|
|
|
|
|
[JsonPropertyName("age")]
|
|
|
|
public int Age { get; set; }
|
2024-06-30 11:43:22 -07:00
|
|
|
|
2024-08-30 08:36:20 -07:00
|
|
|
[JsonPropertyName("address")]
|
|
|
|
public string Address { get; set; }
|
|
|
|
}
|
|
|
|
#endregion person_class
|
2024-06-30 11:43:22 -07:00
|
|
|
}
|
2024-08-30 08:36:20 -07:00
|
|
|
|