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.

MiddlewareAgentCodeSnippet.cs 6.8 kB

Bring Dotnet AutoGen (#924) * update readme * update * update * update * update * update * update * add sample project * revert notebook change back * update * update interactive version * add nuget package * refactor Message * update example * add azure nightly build pipeline * Set up CI with Azure Pipelines [skip ci] * Update nightly-build.yml for Azure Pipelines * add dotnet interactive package * add dotnet interactive package * update pipeline * add nuget feed back * remove dotnet-tool feed * remove dotnet-tool feed comment * update pipeline * update build name * Update nightly-build.yml * Delete .github/workflows/dotnet-ci.yml * update * add working_dir to use step * add initateChat api * update oai package * Update dotnet-build.yml * Update dotnet-run-openai-test-and-notebooks.yml * update build workflow * update build workflow * update nuget feed * update nuget feed * update aoai and sk version * Update InteractiveService.cs * add support for GPT 4V * add DalleAndGPT4V example * update example * add user proxy agent * add readme * bump version * update example * add dotnet interactive hook * update * udpate tests * add website * update index.md * add docs * update doc * move sk dependency out of core package * udpate doc * Update Use-function-call.md * add type safe function call document * update doc * update doc * add dock * Update Use-function-call.md * add GenerateReplyOptions * remove IChatLLM * update version * update doc * update website * add sample * fix link * add middleware agent * clean up doc * bump version * update doc * update * add Other Language * remove warnings * add sign.props * add sign step * fix pipelien * auth * real sign * disable PR trigger * update * disable PR trigger * use microbuild machine * update build pipeline to add publish to internal feed * add internal feed * fix build pipeline * add dotnet prefix * update ci * add build number * update run number * update source * update token * update * remove adding source * add publish to github package * try again * try again * ask for write pacakge * disable package when branch is not main * update * implement streaming agent * add test for streaming function call * update * fix #1588 * enable PR check for dotnet branch * add website readme * only publish to dotnet feed when pushing to dotnet branch * remove openai-test-and-notebooks workflow * update readme * update readme * update workflow * update getting-start * upgrade test and sample proejct to use .net 8 * fix global.json format && make loadFromConfig API internal only before implementing * update * add support for LM studio * add doc * Update README.md * add push and workflow_dispatch trigger * disable PR for main * add dotnet env * Update Installation.md * add nuget * refer to newtonsoft 13 * update branch to dotnet in docfx * Update Installation.md * pull out HumanInputMiddleware and FunctionCallMiddleware * fix tests * add link to sample folder * refactor message * refactor over IMessage * add more tests * add more test * fix build error * rename header * add semantic kernel project * update sk example * update dotnet version * add LMStudio function call example * rename LLaMAFunctin * remove dotnet run openai test and notebook workflow * add FunctionContract and test * update doc * add documents * add workflow * update * update sample * fix warning in test * reult length can be less then maximumOutputToKeep (#1804) * merge with main * add option to retrieve inner agent and middlewares from MiddlewareAgent * update doc * adjust namespace * update readme * fix test * use IMessage * more updates * update * fix test * add comments * use FunctionContract to replace FunctionDefinition * move AutoGen contrac to AutoGen.Core * update installation * refactor streamingAgent by adding StreamingMessage type * update sample * update samples * update * update * add test * fix test * bump version * add openaichat test * update * Update Example03_Agent_FunctionCall.cs * [.Net] improve docs (#1862) * add doc * add doc * add doc * add doc * add doc * add doc * update * fix test error * fix some error * fix test * fix test * add more tests * edits --------- Co-authored-by: ekzhu <ekzhu@users.noreply.github.com> * [.Net] Add fill form example (#1911) * add form filler example * update * fix ci error * [.Net] Add using AutoGen.Core in source generator (#1983) * fix using namespace bug in source generator * remove using in sourcegenerator test * disable PR test * Add .idea to .gitignore (#1988) * [.Net] publish to nuget.org feed (#1987) * publish to nuget * update ci * update dotnet-release * update release pipeline * add source * remove empty symbol package * update pipeline * remove tag * update installation guide * [.Net] Rename some classes && APIs based on doc review (#1980) * rename sequential group chat to round robin group chat * rename to sendInstruction * rename workflow to graph * rename some api * bump version * move Graph to GroupChat folder * rename fill application example * [.Net] Improve package description (#2161) * add discord link and update package description * Update getting-start.md * [.Net] Fix document comment from the most recent AutoGen.Net engineer sync (#2231) * update * rename RegisterPrintMessageHook to RegisterPrintMessage * update website * update update.md * fix link error * [.Net] Enable JsonMode and deterministic output in AutoGen.OpenAI OpenAIChatAgent (#2347) * update openai version && add sample for json output * add example in web * update update.md * update image url * [.Net] Add AutoGen.Mistral package (#2330) * add mstral client * enable streaming support * add mistralClientAgent * add test for function call * add extension * add support for toolcall and toolcall result message * add support for aggregate message * implement streaming function call * track (#2471) * [.Net] add mistral example (#2482) * update existing examples to use messageCOnnector * add overview * add function call document * add example 14 * add mistral token count usage example * update version * Update dotnet-release.yml (#2488) * update * revert gitattributes --------- Co-authored-by: mhensen <mh@webvize.nl> Co-authored-by: ekzhu <ekzhu@users.noreply.github.com> Co-authored-by: Krzysztof Kasprowicz <60486987+Krzysztof318@users.noreply.github.com>
2 years ago
Bring Dotnet AutoGen (#924) * update readme * update * update * update * update * update * update * add sample project * revert notebook change back * update * update interactive version * add nuget package * refactor Message * update example * add azure nightly build pipeline * Set up CI with Azure Pipelines [skip ci] * Update nightly-build.yml for Azure Pipelines * add dotnet interactive package * add dotnet interactive package * update pipeline * add nuget feed back * remove dotnet-tool feed * remove dotnet-tool feed comment * update pipeline * update build name * Update nightly-build.yml * Delete .github/workflows/dotnet-ci.yml * update * add working_dir to use step * add initateChat api * update oai package * Update dotnet-build.yml * Update dotnet-run-openai-test-and-notebooks.yml * update build workflow * update build workflow * update nuget feed * update nuget feed * update aoai and sk version * Update InteractiveService.cs * add support for GPT 4V * add DalleAndGPT4V example * update example * add user proxy agent * add readme * bump version * update example * add dotnet interactive hook * update * udpate tests * add website * update index.md * add docs * update doc * move sk dependency out of core package * udpate doc * Update Use-function-call.md * add type safe function call document * update doc * update doc * add dock * Update Use-function-call.md * add GenerateReplyOptions * remove IChatLLM * update version * update doc * update website * add sample * fix link * add middleware agent * clean up doc * bump version * update doc * update * add Other Language * remove warnings * add sign.props * add sign step * fix pipelien * auth * real sign * disable PR trigger * update * disable PR trigger * use microbuild machine * update build pipeline to add publish to internal feed * add internal feed * fix build pipeline * add dotnet prefix * update ci * add build number * update run number * update source * update token * update * remove adding source * add publish to github package * try again * try again * ask for write pacakge * disable package when branch is not main * update * implement streaming agent * add test for streaming function call * update * fix #1588 * enable PR check for dotnet branch * add website readme * only publish to dotnet feed when pushing to dotnet branch * remove openai-test-and-notebooks workflow * update readme * update readme * update workflow * update getting-start * upgrade test and sample proejct to use .net 8 * fix global.json format && make loadFromConfig API internal only before implementing * update * add support for LM studio * add doc * Update README.md * add push and workflow_dispatch trigger * disable PR for main * add dotnet env * Update Installation.md * add nuget * refer to newtonsoft 13 * update branch to dotnet in docfx * Update Installation.md * pull out HumanInputMiddleware and FunctionCallMiddleware * fix tests * add link to sample folder * refactor message * refactor over IMessage * add more tests * add more test * fix build error * rename header * add semantic kernel project * update sk example * update dotnet version * add LMStudio function call example * rename LLaMAFunctin * remove dotnet run openai test and notebook workflow * add FunctionContract and test * update doc * add documents * add workflow * update * update sample * fix warning in test * reult length can be less then maximumOutputToKeep (#1804) * merge with main * add option to retrieve inner agent and middlewares from MiddlewareAgent * update doc * adjust namespace * update readme * fix test * use IMessage * more updates * update * fix test * add comments * use FunctionContract to replace FunctionDefinition * move AutoGen contrac to AutoGen.Core * update installation * refactor streamingAgent by adding StreamingMessage type * update sample * update samples * update * update * add test * fix test * bump version * add openaichat test * update * Update Example03_Agent_FunctionCall.cs * [.Net] improve docs (#1862) * add doc * add doc * add doc * add doc * add doc * add doc * update * fix test error * fix some error * fix test * fix test * add more tests * edits --------- Co-authored-by: ekzhu <ekzhu@users.noreply.github.com> * [.Net] Add fill form example (#1911) * add form filler example * update * fix ci error * [.Net] Add using AutoGen.Core in source generator (#1983) * fix using namespace bug in source generator * remove using in sourcegenerator test * disable PR test * Add .idea to .gitignore (#1988) * [.Net] publish to nuget.org feed (#1987) * publish to nuget * update ci * update dotnet-release * update release pipeline * add source * remove empty symbol package * update pipeline * remove tag * update installation guide * [.Net] Rename some classes && APIs based on doc review (#1980) * rename sequential group chat to round robin group chat * rename to sendInstruction * rename workflow to graph * rename some api * bump version * move Graph to GroupChat folder * rename fill application example * [.Net] Improve package description (#2161) * add discord link and update package description * Update getting-start.md * [.Net] Fix document comment from the most recent AutoGen.Net engineer sync (#2231) * update * rename RegisterPrintMessageHook to RegisterPrintMessage * update website * update update.md * fix link error * [.Net] Enable JsonMode and deterministic output in AutoGen.OpenAI OpenAIChatAgent (#2347) * update openai version && add sample for json output * add example in web * update update.md * update image url * [.Net] Add AutoGen.Mistral package (#2330) * add mstral client * enable streaming support * add mistralClientAgent * add test for function call * add extension * add support for toolcall and toolcall result message * add support for aggregate message * implement streaming function call * track (#2471) * [.Net] add mistral example (#2482) * update existing examples to use messageCOnnector * add overview * add function call document * add example 14 * add mistral token count usage example * update version * Update dotnet-release.yml (#2488) * update * revert gitattributes --------- Co-authored-by: mhensen <mh@webvize.nl> Co-authored-by: ekzhu <ekzhu@users.noreply.github.com> Co-authored-by: Krzysztof Kasprowicz <60486987+Krzysztof318@users.noreply.github.com>
2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // MiddlewareAgentCodeSnippet.cs
  3. using System.Text.Json;
  4. using AutoGen.Core;
  5. using AutoGen.OpenAI;
  6. using FluentAssertions;
  7. namespace AutoGen.BasicSample.CodeSnippet;
  8. public class MiddlewareAgentCodeSnippet
  9. {
  10. public async Task CreateMiddlewareAgentAsync()
  11. {
  12. #region create_middleware_agent_with_original_agent
  13. // Create an agent that always replies "Hello World"
  14. IAgent agent = new DefaultReplyAgent(name: "assistant", defaultReply: "Hello World");
  15. // Create a middleware agent on top of default reply agent
  16. var middlewareAgent = new MiddlewareAgent(innerAgent: agent);
  17. middlewareAgent.Use(async (messages, options, agent, ct) =>
  18. {
  19. var lastMessage = messages.Last() as TextMessage;
  20. lastMessage.Content = $"[middleware 0] {lastMessage.Content}";
  21. return await agent.GenerateReplyAsync(messages, options, ct);
  22. });
  23. var reply = await middlewareAgent.SendAsync("Hello World");
  24. reply.GetContent().Should().Be("[middleware 0] Hello World");
  25. #endregion create_middleware_agent_with_original_agent
  26. #region register_middleware_agent
  27. middlewareAgent = agent.RegisterMiddleware(async (messages, options, agent, ct) =>
  28. {
  29. var lastMessage = messages.Last() as TextMessage;
  30. lastMessage.Content = $"[middleware 0] {lastMessage.Content}";
  31. return await agent.GenerateReplyAsync(messages, options, ct);
  32. });
  33. #endregion register_middleware_agent
  34. #region short_circuit_middleware_agent
  35. // This middleware will short circuit the agent and return the last message directly.
  36. middlewareAgent.Use(async (messages, options, agent, ct) =>
  37. {
  38. var lastMessage = messages.Last() as TextMessage;
  39. lastMessage.Content = $"[middleware shortcut]";
  40. return lastMessage;
  41. });
  42. #endregion short_circuit_middleware_agent
  43. }
  44. public async Task RegisterStreamingMiddlewareAsync()
  45. {
  46. IStreamingAgent streamingAgent = default;
  47. #region register_streaming_middleware
  48. var connector = new OpenAIChatRequestMessageConnector();
  49. var agent = streamingAgent!
  50. .RegisterStreamingMiddleware(connector);
  51. #endregion register_streaming_middleware
  52. }
  53. public async Task CodeSnippet1()
  54. {
  55. #region code_snippet_1
  56. // Create an agent that always replies "Hello World"
  57. IAgent agent = new DefaultReplyAgent(name: "assistant", defaultReply: "Hello World");
  58. // Create a middleware agent on top of default reply agent
  59. var middlewareAgent = new MiddlewareAgent(innerAgent: agent);
  60. // Since no middleware is added, middlewareAgent will simply proxy into the inner agent to generate reply.
  61. var reply = await middlewareAgent.SendAsync("Hello World");
  62. reply.From.Should().Be("assistant");
  63. reply.GetContent().Should().Be("Hello World");
  64. #endregion code_snippet_1
  65. #region code_snippet_2
  66. middlewareAgent.Use(async (messages, options, agent, ct) =>
  67. {
  68. var lastMessage = messages.Last() as TextMessage;
  69. lastMessage.Content = $"[middleware 0] {lastMessage.Content}";
  70. return await agent.GenerateReplyAsync(messages, options, ct);
  71. });
  72. reply = await middlewareAgent.SendAsync("Hello World");
  73. reply.Should().BeOfType<TextMessage>();
  74. var textReply = (TextMessage)reply;
  75. textReply.Content.Should().Be("[middleware 0] Hello World");
  76. #endregion code_snippet_2
  77. #region code_snippet_2_1
  78. middlewareAgent = agent.RegisterMiddleware(async (messages, options, agnet, ct) =>
  79. {
  80. var lastMessage = messages.Last() as TextMessage;
  81. lastMessage.Content = $"[middleware 0] {lastMessage.Content}";
  82. return await agent.GenerateReplyAsync(messages, options, ct);
  83. });
  84. reply = await middlewareAgent.SendAsync("Hello World");
  85. reply.GetContent().Should().Be("[middleware 0] Hello World");
  86. #endregion code_snippet_2_1
  87. #region code_snippet_3
  88. middlewareAgent.Use(async (messages, options, agent, ct) =>
  89. {
  90. var lastMessage = messages.Last() as TextMessage;
  91. lastMessage.Content = $"[middleware 1] {lastMessage.Content}";
  92. return await agent.GenerateReplyAsync(messages, options, ct);
  93. });
  94. reply = await middlewareAgent.SendAsync("Hello World");
  95. reply.GetContent().Should().Be("[middleware 0] [middleware 1] Hello World");
  96. #endregion code_snippet_3
  97. #region code_snippet_4
  98. middlewareAgent.Use(async (messages, options, next, ct) =>
  99. {
  100. var lastMessage = messages.Last() as TextMessage;
  101. lastMessage.Content = $"[middleware shortcut]";
  102. return lastMessage;
  103. });
  104. reply = await middlewareAgent.SendAsync("Hello World");
  105. reply.GetContent().Should().Be("[middleware shortcut]");
  106. #endregion code_snippet_4
  107. #region retrieve_inner_agent
  108. var innerAgent = middlewareAgent.Agent;
  109. #endregion retrieve_inner_agent
  110. #region code_snippet_logging_to_console
  111. var agentWithLogging = middlewareAgent.RegisterMiddleware(async (messages, options, agent, ct) =>
  112. {
  113. var reply = await agent.GenerateReplyAsync(messages, options, ct);
  114. var formattedMessage = reply.FormatMessage();
  115. Console.WriteLine(formattedMessage);
  116. return reply;
  117. });
  118. #endregion code_snippet_logging_to_console
  119. #region code_snippet_response_format_forcement
  120. var jsonAgent = middlewareAgent.RegisterMiddleware(async (messages, options, agent, ct) =>
  121. {
  122. var maxAttempt = 5;
  123. var reply = await agent.GenerateReplyAsync(messages, options, ct);
  124. while (maxAttempt-- > 0)
  125. {
  126. if (JsonSerializer.Deserialize<Dictionary<string, object>>(reply.GetContent()) is { } dict)
  127. {
  128. return reply;
  129. }
  130. else
  131. {
  132. await Task.Delay(1000);
  133. var reviewPrompt = @"The format is not json, please modify your response to json format
  134. -- ORIGINAL MESSAGE --
  135. {reply.Content}
  136. -- END OF ORIGINAL MESSAGE --
  137. Reply again with json format.";
  138. reply = await agent.SendAsync(reviewPrompt, messages, ct);
  139. }
  140. }
  141. throw new Exception("agent fails to generate json response");
  142. });
  143. #endregion code_snippet_response_format_forcement
  144. }
  145. }