# Set your Azure OpenAI credentialsexport AZURE_OPENAI_API_KEY="your-azure-key"export AZURE_OPENAI_ENDPOINT="https://your-resource.openai.azure.com/"export AZURE_OPENAI_DEPLOY_NAME="your-deployment-name"
2
Create Azure OpenAI agent
using System.ClientModel;using AutoGen.OpenAI.Extension;using Azure.AI.OpenAI;var apiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY");var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT");var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOY_NAME");// Create Azure OpenAI clientvar azureClient = new AzureOpenAIClient( new Uri(endpoint), new ApiKeyCredential(apiKey));var agent = new OpenAIChatAgent( chatClient: azureClient.GetChatClient(deploymentName), name: "assistant", systemMessage: "You are a helpful assistant", seed: 0) .RegisterMessageConnector() .RegisterPrintMessage();var response = await agent.SendAsync( "Can you write a piece of C# code to calculate 100th Fibonacci?");
Stream responses token-by-token for real-time output:
using AutoGen.Core;var agent = new OpenAIChatAgent( chatClient: openAIClient.GetChatClient("gpt-4"), name: "assistant") .RegisterMessageConnector();var messages = new[]{ new TextMessage(Role.User, "Write a long story about a robot")};await foreach (var message in agent.GenerateStreamingReplyAsync(messages)){ if (message.GetContent() is string content) { Console.Write(content); }}
using System.Text.Json;using System.Text.Json.Serialization;using OpenAI.Chat;// Define your schemapublic class Person{ [JsonPropertyName("name")] public string Name { get; set; } [JsonPropertyName("age")] public int Age { get; set; } [JsonPropertyName("email")] public string Email { get; set; }}var jsonSchema = JsonSerializer.Serialize(new{ type = "object", properties = new { name = new { type = "string" }, age = new { type = "integer" }, email = new { type = "string" } }, required = new[] { "name", "age", "email" }, additionalProperties = false});var agent = new OpenAIChatAgent( chatClient: openAIClient.GetChatClient("gpt-4"), name: "assistant", systemMessage: "Extract person information as JSON", responseFormat: ChatResponseFormat.CreateJsonSchemaFormat( "person", BinaryData.FromString(jsonSchema))) .RegisterMessageConnector();var response = await agent.SendAsync( "John Doe is 30 years old. His email is [email protected]");var person = JsonSerializer.Deserialize<Person>(response.GetContent());Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");
using AutoGen.Core;using AutoGen.OpenAI;using AutoGen.OpenAI.Extension;using Microsoft.Extensions.AI;public partial class WeatherFunctions{ /// <summary> /// Get current weather /// </summary> /// <param name="location">city name</param> [Function] public async Task<string> GetWeather(string location) { return $"Weather in {location}: Sunny, 72°F"; }}var tools = new WeatherFunctions();var gpt4 = openAIClient.GetChatClient("gpt-4");var functionCallMiddleware = new FunctionCallMiddleware( functions: [tools.GetWeatherFunctionContract], functionMap: new Dictionary<string, Func<string, Task<string>>> { { nameof(tools.GetWeather), tools.GetWeatherWrapper } });var agent = new OpenAIChatAgent( chatClient: gpt4, name: "assistant") .RegisterMessageConnector() .RegisterStreamingMiddleware(functionCallMiddleware) .RegisterPrintMessage();var response = await agent.SendAsync("What's the weather in Seattle?");Console.WriteLine(response.GetContent());// Output: The weather in Seattle is sunny with a temperature of 72°F.
using OpenAI;// Point to Ollama's OpenAI-compatible endpointvar ollamaClient = new OpenAIClient( new ApiKeyCredential("not-used"), new OpenAIClientOptions { Endpoint = new Uri("http://localhost:11434/v1") });var agent = new OpenAIChatAgent( chatClient: ollamaClient.GetChatClient("llama2"), name: "assistant") .RegisterMessageConnector();var response = await agent.SendAsync("Hello!");