Skip to content

Commit 0027699

Browse files
LittleLittleCloudvictordibia
authored andcommitted
[.Net] fix #2859 (#2974)
* add getting start sample project * update * update * revert change
1 parent 668146e commit 0027699

11 files changed

+575
-15
lines changed

dotnet/AutoGen.sln

+3-2
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini", "src\AutoG
5757
EndProject
5858
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini.Tests", "test\AutoGen.Gemini.Tests\AutoGen.Gemini.Tests.csproj", "{8EA16BAB-465A-4C07-ABC4-1070D40067E9}"
5959
EndProject
60-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.Gemini.Sample", "sample\AutoGen.Gemini.Sample\AutoGen.Gemini.Sample.csproj", "{19679B75-CE3A-4DF0-A3F0-CA369D2760A4}"
61-
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AutoGen.AotCompatibility.Tests", "test\AutoGen.AotCompatibility.Tests\AutoGen.AotCompatibility.Tests.csproj", "{6B82F26D-5040-4453-B21B-C8D1F913CE4C}"
60+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.Gemini.Sample", "sample\AutoGen.Gemini.Sample\AutoGen.Gemini.Sample.csproj", "{19679B75-CE3A-4DF0-A3F0-CA369D2760A4}"
61+
EndProject
62+
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AutoGen.AotCompatibility.Tests", "test\AutoGen.AotCompatibility.Tests\AutoGen.AotCompatibility.Tests.csproj", "{6B82F26D-5040-4453-B21B-C8D1F913CE4C}"
6263
EndProject
6364
Global
6465
GlobalSection(SolutionConfigurationPlatforms) = preSolution

dotnet/sample/AutoGen.BasicSamples/AutoGen.BasicSample.csproj

+1-6
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<ImplicitUsings>enable</ImplicitUsings>
77
<GenerateDocumentationFile>True</GenerateDocumentationFile>
88
<NoWarn>$(NoWarn);CS8981;CS8600;CS8602;CS8604;CS8618;CS0219;SKEXP0054;SKEXP0050;SKEXP0110</NoWarn>
9+
<IncludeResourceFolder>true</IncludeResourceFolder>
910
</PropertyGroup>
1011

1112
<ItemGroup>
@@ -15,10 +16,4 @@
1516
<PackageReference Include="FluentAssertions" Version="$(FluentAssertionVersion)" />
1617
<PackageReference Include="Microsoft.SemanticKernel.Plugins.Web" Version="$(SemanticKernelExperimentalVersion)" />
1718
</ItemGroup>
18-
19-
<ItemGroup>
20-
<None Update="ImageResources\square.png">
21-
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
22-
</None>
23-
</ItemGroup>
2419
</Project>

dotnet/sample/AutoGen.BasicSamples/Example05_Dalle_And_GPT4V.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ public static async Task RunAsync()
6161
var gpt4vConfig = autogen.GetOpenAIConfigList(openAIKey, new[] { "gpt-4-vision-preview" });
6262
var openAIClient = new OpenAIClient(openAIKey);
6363
var instance = new Example05_Dalle_And_GPT4V(openAIClient);
64-
var imagePath = Path.Combine(Environment.CurrentDirectory, "image.jpg");
64+
var imagePath = Path.Combine("resource", "images", "background.png");
6565
if (File.Exists(imagePath))
6666
{
6767
File.Delete(imagePath);

dotnet/sample/AutoGen.BasicSamples/Example15_GPT4V_BinaryDataImageMessage.cs

+4-3
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ namespace AutoGen.BasicSample;
1414
/// </summary>
1515
public static class Example15_GPT4V_BinaryDataImageMessage
1616
{
17-
private static readonly string ImageResourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ImageResources");
17+
private static readonly string ImageResourcePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "resource", "images");
1818

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

3333
var visionAgent = new GPTAgent(
3434
name: "gpt",
3535
systemMessage: "You are a helpful AI assistant",
3636
config: openAiConfig,
37-
temperature: 0);
37+
temperature: 0)
38+
.RegisterPrintMessage();
3839

3940
List<IMessage> messages =
4041
[new TextMessage(Role.User, "What is this image?", from: "user")];
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Agent_Middleware.cs
3+
4+
#region Using
5+
using AutoGen.Core;
6+
using AutoGen.OpenAI;
7+
using AutoGen.OpenAI.Extension;
8+
using Azure.AI.OpenAI;
9+
#endregion Using
10+
using FluentAssertions;
11+
12+
namespace AutoGen.BasicSample;
13+
14+
public class Agent_Middleware
15+
{
16+
public static async Task RunTokenCountAsync()
17+
{
18+
#region Create_Agent
19+
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Please set the environment variable OPENAI_API_KEY");
20+
var model = "gpt-3.5-turbo";
21+
var openaiClient = new OpenAIClient(apiKey);
22+
var openaiMessageConnector = new OpenAIChatRequestMessageConnector();
23+
var totalTokenCount = 0;
24+
var agent = new OpenAIChatAgent(
25+
openAIClient: openaiClient,
26+
name: "agent",
27+
modelName: model,
28+
systemMessage: "You are a helpful AI assistant")
29+
.RegisterMiddleware(async (messages, option, innerAgent, ct) =>
30+
{
31+
var reply = await innerAgent.GenerateReplyAsync(messages, option, ct);
32+
if (reply is MessageEnvelope<ChatCompletions> chatCompletions)
33+
{
34+
var tokenCount = chatCompletions.Content.Usage.TotalTokens;
35+
totalTokenCount += tokenCount;
36+
}
37+
return reply;
38+
})
39+
.RegisterMiddleware(openaiMessageConnector);
40+
#endregion Create_Agent
41+
42+
#region Chat_With_Agent
43+
var reply = await agent.SendAsync("Tell me a joke");
44+
Console.WriteLine($"Total token count: {totalTokenCount}");
45+
#endregion Chat_With_Agent
46+
47+
#region verify_reply
48+
reply.Should().BeOfType<TextMessage>();
49+
totalTokenCount.Should().BeGreaterThan(0);
50+
#endregion verify_reply
51+
}
52+
53+
public static async Task RunRagTaskAsync()
54+
{
55+
#region Create_Agent
56+
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new InvalidOperationException("Please set the environment variable OPENAI_API_KEY");
57+
var model = "gpt-3.5-turbo";
58+
var openaiClient = new OpenAIClient(apiKey);
59+
var openaiMessageConnector = new OpenAIChatRequestMessageConnector();
60+
var agent = new OpenAIChatAgent(
61+
openAIClient: openaiClient,
62+
name: "agent",
63+
modelName: model,
64+
systemMessage: "You are a helpful AI assistant")
65+
.RegisterMessageConnector()
66+
.RegisterMiddleware(async (messages, option, innerAgent, ct) =>
67+
{
68+
var today = DateTime.UtcNow;
69+
var todayMessage = new TextMessage(Role.System, $"Today is {today:yyyy-MM-dd}");
70+
messages = messages.Concat(new[] { todayMessage });
71+
return await innerAgent.GenerateReplyAsync(messages, option, ct);
72+
})
73+
.RegisterPrintMessage();
74+
#endregion Create_Agent
75+
76+
#region Chat_With_Agent
77+
var reply = await agent.SendAsync("what's the date today");
78+
#endregion Chat_With_Agent
79+
}
80+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Chat_With_Agent.cs
3+
4+
#region Using
5+
using AutoGen.Core;
6+
using AutoGen.OpenAI;
7+
using AutoGen.OpenAI.Extension;
8+
using Azure.AI.OpenAI;
9+
#endregion Using
10+
11+
using FluentAssertions;
12+
13+
namespace AutoGen.BasicSample;
14+
15+
public class Chat_With_Agent
16+
{
17+
public static async Task RunAsync()
18+
{
19+
#region Create_Agent
20+
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
21+
var model = "gpt-3.5-turbo";
22+
var openaiClient = new OpenAIClient(apiKey);
23+
var agent = new OpenAIChatAgent(
24+
openAIClient: openaiClient,
25+
name: "agent",
26+
modelName: model,
27+
systemMessage: "You are a helpful AI assistant")
28+
.RegisterMessageConnector(); // convert OpenAI message to AutoGen message
29+
#endregion Create_Agent
30+
31+
#region Chat_With_Agent
32+
var reply = await agent.SendAsync("Tell me a joke");
33+
reply.Should().BeOfType<TextMessage>();
34+
if (reply is TextMessage textMessage)
35+
{
36+
Console.WriteLine(textMessage.Content);
37+
}
38+
#endregion Chat_With_Agent
39+
40+
#region Chat_With_History
41+
reply = await agent.SendAsync("summarize the conversation", chatHistory: [reply]);
42+
#endregion Chat_With_History
43+
44+
#region Streaming_Chat
45+
var question = new TextMessage(Role.User, "Tell me a long joke");
46+
await foreach (var streamingReply in agent.GenerateStreamingReplyAsync([question]))
47+
{
48+
if (streamingReply is TextMessageUpdate textMessageUpdate)
49+
{
50+
Console.WriteLine(textMessageUpdate.Content);
51+
}
52+
}
53+
#endregion Streaming_Chat
54+
55+
#region verify_reply
56+
reply.Should().BeOfType<TextMessage>();
57+
#endregion verify_reply
58+
}
59+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
// Copyright (c) Microsoft Corporation. All rights reserved.
2+
// Dynamic_GroupChat.cs
3+
4+
using AutoGen.Core;
5+
using AutoGen.OpenAI;
6+
using AutoGen.OpenAI.Extension;
7+
using AutoGen.SemanticKernel;
8+
using AutoGen.SemanticKernel.Extension;
9+
using Azure.AI.OpenAI;
10+
using Microsoft.SemanticKernel;
11+
12+
namespace AutoGen.BasicSample;
13+
14+
public class Dynamic_Group_Chat
15+
{
16+
public static async Task RunAsync()
17+
{
18+
var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
19+
var model = "gpt-3.5-turbo";
20+
21+
#region Create_Coder
22+
var openaiClient = new OpenAIClient(apiKey);
23+
var coder = new OpenAIChatAgent(
24+
openAIClient: openaiClient,
25+
name: "coder",
26+
modelName: model,
27+
systemMessage: "You are a C# coder, when writing csharp code, please put the code between ```csharp and ```")
28+
.RegisterMessageConnector() // convert OpenAI message to AutoGen message
29+
.RegisterPrintMessage(); // print the message content
30+
#endregion Create_Coder
31+
32+
#region Create_Commenter
33+
var kernel = Kernel
34+
.CreateBuilder()
35+
.AddOpenAIChatCompletion(modelId: model, apiKey: apiKey)
36+
.Build();
37+
var commenter = new SemanticKernelAgent(
38+
kernel: kernel,
39+
name: "commenter",
40+
systemMessage: "You write inline comments for the code snippet and add unit tests if necessary")
41+
.RegisterMessageConnector() // register message connector so it support AutoGen built-in message types like TextMessage.
42+
.RegisterPrintMessage(); // pretty print the message to the console
43+
#endregion Create_Commenter
44+
45+
#region Create_UserProxy
46+
var userProxy = new DefaultReplyAgent("user", defaultReply: "END")
47+
.RegisterPrintMessage(); // print the message content
48+
#endregion Create_UserProxy
49+
50+
#region Create_Group
51+
var admin = new OpenAIChatAgent(
52+
openAIClient: openaiClient,
53+
name: "admin",
54+
modelName: model)
55+
.RegisterMessageConnector(); // convert OpenAI message to AutoGen message
56+
57+
var group = new GroupChat(
58+
members: [coder, commenter, userProxy],
59+
admin: admin);
60+
#endregion Create_Group
61+
62+
#region Chat_With_Group
63+
var workflowInstruction = new TextMessage(
64+
Role.User,
65+
"""
66+
Here is the workflow of this group chat:
67+
User{Ask a question} -> Coder{Write code}
68+
Coder{Write code} -> Commenter{Add comments to the code}
69+
Commenter{Add comments to the code} -> User{END}
70+
""");
71+
72+
var question = new TextMessage(Role.User, "How to calculate the 100th Fibonacci number?");
73+
var chatHistory = new List<IMessage> { workflowInstruction, question };
74+
while (true)
75+
{
76+
var replies = await group.CallAsync(chatHistory, maxRound: 1);
77+
var lastReply = replies.Last();
78+
chatHistory.Add(lastReply);
79+
80+
if (lastReply.From == userProxy.Name)
81+
{
82+
break;
83+
}
84+
}
85+
#endregion Chat_With_Group
86+
87+
#region Summarize_Chat_History
88+
var summary = await coder.SendAsync("summarize the conversation", chatHistory: chatHistory);
89+
#endregion Summarize_Chat_History
90+
}
91+
}

0 commit comments

Comments
 (0)