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.

Streaming_Tool_Call.cs 2.0 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Streaming_Tool_Call.cs
  3. using AutoGen.Core;
  4. using AutoGen.OpenAI;
  5. using AutoGen.OpenAI.Extension;
  6. using FluentAssertions;
  7. using OpenAI;
  8. namespace AutoGen.Basic.Sample.GettingStart;
  9. internal class Streaming_Tool_Call
  10. {
  11. public static async Task RunAsync()
  12. {
  13. #region Create_tools
  14. var tools = new Tools();
  15. #endregion Create_tools
  16. #region Create_auto_invoke_middleware
  17. var autoInvokeMiddleware = new FunctionCallMiddleware(
  18. functions: [tools.GetWeatherFunctionContract],
  19. functionMap: new Dictionary<string, Func<string, Task<string>>>()
  20. {
  21. { tools.GetWeatherFunctionContract.Name, tools.GetWeatherWrapper },
  22. });
  23. #endregion Create_auto_invoke_middleware
  24. #region Create_Agent
  25. var apiKey = Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? throw new Exception("Please set OPENAI_API_KEY environment variable.");
  26. var model = "gpt-4o-mini";
  27. var openaiClient = new OpenAIClient(apiKey);
  28. var agent = new OpenAIChatAgent(
  29. chatClient: openaiClient.GetChatClient(model),
  30. name: "agent",
  31. systemMessage: "You are a helpful AI assistant")
  32. .RegisterMessageConnector()
  33. .RegisterStreamingMiddleware(autoInvokeMiddleware)
  34. .RegisterPrintMessage();
  35. #endregion Create_Agent
  36. IMessage finalReply = null;
  37. var question = new TextMessage(Role.User, "What's the weather in Seattle");
  38. // In streaming function call
  39. // function can only be invoked untill all the chunks are collected
  40. // therefore, only one ToolCallAggregateMessage chunk will be return here.
  41. await foreach (var message in agent.GenerateStreamingReplyAsync([question]))
  42. {
  43. finalReply = message;
  44. }
  45. finalReply?.GetContent().Should().Be("The weather in Seattle is sunny.");
  46. }
  47. }