Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[.Net] fix #2859 #2974

Merged
merged 4 commits into from
Jun 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions dotnet/AutoGen.sln
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini", "src\AutoG
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini.Tests", "test\AutoGen.Gemini.Tests\AutoGen.Gemini.Tests.csproj", "{8EA16BAB-465A-4C07-ABC4-1070D40067E9}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.Gemini.Sample", "sample\AutoGen.Gemini.Sample\AutoGen.Gemini.Sample.csproj", "{19679B75-CE3A-4DF0-A3F0-CA369D2760A4}"
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.AotCompatibility.Tests", "test\AutoGen.AotCompatibility.Tests\AutoGen.AotCompatibility.Tests.csproj", "{6B82F26D-5040-4453-B21B-C8D1F913CE4C}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini.Sample", "sample\AutoGen.Gemini.Sample\AutoGen.Gemini.Sample.csproj", "{19679B75-CE3A-4DF0-A3F0-CA369D2760A4}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.AotCompatibility.Tests", "test\AutoGen.AotCompatibility.Tests\AutoGen.AotCompatibility.Tests.csproj", "{6B82F26D-5040-4453-B21B-C8D1F913CE4C}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>True</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS8981;CS8600;CS8602;CS8604;CS8618;CS0219;SKEXP0054;SKEXP0050;SKEXP0110</NoWarn>
<IncludeResourceFolder>true</IncludeResourceFolder>
</PropertyGroup>

<ItemGroup>
Expand All @@ -15,10 +16,4 @@
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionVersion)" />
<PackageReference Include="Microsoft.SemanticKernel.Plugins.Web" Version="$(SemanticKernelExperimentalVersion)" />
</ItemGroup>

<ItemGroup>
<None Update="ImageResources\square.png">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public static async Task RunAsync()
var gpt4vConfig = autogen.GetOpenAIConfigList(openAIKey, new[] { "gpt-4-vision-preview" });
var openAIClient = new OpenAIClient(openAIKey);
var instance = new Example05_Dalle_And_GPT4V(openAIClient);
var imagePath = Path.Combine(Environment.CurrentDirectory, "image.jpg");
var imagePath = Path.Combine("resource", "images", "background.png");
if (File.Exists(imagePath))
{
File.Delete(imagePath);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ namespace AutoGen.BasicSample;
/// </summary>
public static class Example15_GPT4V_BinaryDataImageMessage
{
private static readonly string ImageResourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ImageResources");
private static readonly string ImageResourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resource", "images");

private static Dictionary<string, string> _mediaTypeMappings = new()
{
Expand All @@ -28,13 +28,14 @@ public static class Example15_GPT4V_BinaryDataImageMessage
public static async Task RunAsync()
{
var openAIKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
var openAiConfig = new OpenAIConfig(openAIKey, "gpt-4-vision-preview");
var openAiConfig = new OpenAIConfig(openAIKey, "gpt-4o");

var visionAgent = new GPTAgent(
name: "gpt",
systemMessage: "You are a helpful AI assistant",
config: openAiConfig,
temperature: 0);
temperature: 0)
.RegisterPrintMessage();

List<IMessage> messages =
[new TextMessage(Role.User, "What is this image?", from: "user")];
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Agent_Middleware.cs

#region Using
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
using Azure.AI.OpenAI;
#endregion Using
using FluentAssertions;

namespace AutoGen.BasicSample;

public class Agent_Middleware
{
public static async Task RunTokenCountAsync()
{
#region Create_Agent
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Please set the environment variable OPENAI_API_KEY");
var model = "gpt-3.5-turbo";
var openaiClient = new OpenAIClient(apiKey);
var openaiMessageConnector = new OpenAIChatRequestMessageConnector();
var totalTokenCount = 0;
var agent = new OpenAIChatAgent(
openAIClient: openaiClient,
name: "agent",
modelName: model,
systemMessage: "You are a helpful AI assistant")
.RegisterMiddleware(async (messages, option, innerAgent, ct) =>
{
var reply = await innerAgent.GenerateReplyAsync(messages, option, ct);
if (reply is MessageEnvelope<ChatCompletions> chatCompletions)
{
var tokenCount = chatCompletions.Content.Usage.TotalTokens;
totalTokenCount += tokenCount;
}
return reply;
})
.RegisterMiddleware(openaiMessageConnector);
#endregion Create_Agent

#region Chat_With_Agent
var reply = await agent.SendAsync("Tell me a joke");
Console.WriteLine($"Total token count: {totalTokenCount}");
#endregion Chat_With_Agent

#region verify_reply
reply.Should().BeOfType<TextMessage>();
totalTokenCount.Should().BeGreaterThan(0);
#endregion verify_reply
}

public static async Task RunRagTaskAsync()
{
#region Create_Agent
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Please set the environment variable OPENAI_API_KEY");
var model = "gpt-3.5-turbo";
var openaiClient = new OpenAIClient(apiKey);
var openaiMessageConnector = new OpenAIChatRequestMessageConnector();
var agent = new OpenAIChatAgent(
openAIClient: openaiClient,
name: "agent",
modelName: model,
systemMessage: "You are a helpful AI assistant")
.RegisterMessageConnector()
.RegisterMiddleware(async (messages, option, innerAgent, ct) =>
{
var today = DateTime.UtcNow;
var todayMessage = new TextMessage(Role.System, $"Today is {today:yyyy-MM-dd}");
messages = messages.Concat(new[] { todayMessage });
return await innerAgent.GenerateReplyAsync(messages, option, ct);
})
.RegisterPrintMessage();
#endregion Create_Agent

#region Chat_With_Agent
var reply = await agent.SendAsync("what's the date today");
#endregion Chat_With_Agent
}
}
59 changes: 59 additions & 0 deletions dotnet/sample/AutoGen.BasicSamples/GettingStart/Chat_With_Agent.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Chat_With_Agent.cs

#region Using
using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
using Azure.AI.OpenAI;
#endregion Using

using FluentAssertions;

namespace AutoGen.BasicSample;

public class Chat_With_Agent
{
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.");
var model = "gpt-3.5-turbo";
var openaiClient = new OpenAIClient(apiKey);
var agent = new OpenAIChatAgent(
openAIClient: openaiClient,
name: "agent",
modelName: model,
systemMessage: "You are a helpful AI assistant")
.RegisterMessageConnector(); // convert OpenAI message to AutoGen message
#endregion Create_Agent

#region Chat_With_Agent
var reply = await agent.SendAsync("Tell me a joke");
reply.Should().BeOfType<TextMessage>();
if (reply is TextMessage textMessage)
{
Console.WriteLine(textMessage.Content);
}
#endregion Chat_With_Agent

#region Chat_With_History
reply = await agent.SendAsync("summarize the conversation", chatHistory: [reply]);
#endregion Chat_With_History

#region Streaming_Chat
var question = new TextMessage(Role.User, "Tell me a long joke");
await foreach (var streamingReply in agent.GenerateStreamingReplyAsync([question]))
{
if (streamingReply is TextMessageUpdate textMessageUpdate)
{
Console.WriteLine(textMessageUpdate.Content);
}
}
#endregion Streaming_Chat

#region verify_reply
reply.Should().BeOfType<TextMessage>();
#endregion verify_reply
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Dynamic_GroupChat.cs

using AutoGen.Core;
using AutoGen.OpenAI;
using AutoGen.OpenAI.Extension;
using AutoGen.SemanticKernel;
using AutoGen.SemanticKernel.Extension;
using Azure.AI.OpenAI;
using Microsoft.SemanticKernel;

namespace AutoGen.BasicSample;

public class Dynamic_Group_Chat
{
public static async Task RunAsync()
{
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
var model = "gpt-3.5-turbo";

#region Create_Coder
var openaiClient = new OpenAIClient(apiKey);
var coder = new OpenAIChatAgent(
openAIClient: openaiClient,
name: "coder",
modelName: model,
systemMessage: "You are a C# coder, when writing csharp code, please put the code between ```csharp and ```")
.RegisterMessageConnector() // convert OpenAI message to AutoGen message
.RegisterPrintMessage(); // print the message content
#endregion Create_Coder

#region Create_Commenter
var kernel = Kernel
.CreateBuilder()
.AddOpenAIChatCompletion(modelId: model, apiKey: apiKey)
.Build();
var commenter = new SemanticKernelAgent(
kernel: kernel,
name: "commenter",
systemMessage: "You write inline comments for the code snippet and add unit tests if necessary")
.RegisterMessageConnector() // register message connector so it support AutoGen built-in message types like TextMessage.
.RegisterPrintMessage(); // pretty print the message to the console
#endregion Create_Commenter

#region Create_UserProxy
var userProxy = new DefaultReplyAgent("user", defaultReply: "END")
.RegisterPrintMessage(); // print the message content
#endregion Create_UserProxy

#region Create_Group
var admin = new OpenAIChatAgent(
openAIClient: openaiClient,
name: "admin",
modelName: model)
.RegisterMessageConnector(); // convert OpenAI message to AutoGen message

var group = new GroupChat(
members: [coder, commenter, userProxy],
admin: admin);
#endregion Create_Group

#region Chat_With_Group
var workflowInstruction = new TextMessage(
Role.User,
"""
Here is the workflow of this group chat:
User{Ask a question} -> Coder{Write code}
Coder{Write code} -> Commenter{Add comments to the code}
Commenter{Add comments to the code} -> User{END}
""");

var question = new TextMessage(Role.User, "How to calculate the 100th Fibonacci number?");
var chatHistory = new List<IMessage> { workflowInstruction, question };
while (true)
{
var replies = await group.CallAsync(chatHistory, maxRound: 1);
var lastReply = replies.Last();
chatHistory.Add(lastReply);

if (lastReply.From == userProxy.Name)
{
break;
}
}
#endregion Chat_With_Group

#region Summarize_Chat_History
var summary = await coder.SendAsync("summarize the conversation", chatHistory: chatHistory);
#endregion Summarize_Chat_History
}
}
Loading
Loading