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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 Azure.AI.OpenAI;
  7. using FluentAssertions;
  8. namespace AutoGen.BasicSample.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";
  27. var openaiClient = new OpenAIClient(apiKey);
  28. var agent = new OpenAIChatAgent(
  29. openAIClient: openaiClient,
  30. name: "agent",
  31. modelName: model,
  32. systemMessage: "You are a helpful AI assistant")
  33. .RegisterMessageConnector()
  34. .RegisterStreamingMiddleware(autoInvokeMiddleware)
  35. .RegisterPrintMessage();
  36. #endregion Create_Agent
  37. IMessage finalReply = null;
  38. var question = new TextMessage(Role.User, "What's the weather in Seattle");
  39. // In streaming function call
  40. // function can only be invoked untill all the chunks are collected
  41. // therefore, only one ToolCallAggregateMessage chunk will be return here.
  42. await foreach (var message in agent.GenerateStreamingReplyAsync([question]))
  43. {
  44. finalReply = message;
  45. }
  46. finalReply?.GetContent().Should().Be("The weather in Seattle is sunny.");
  47. }
  48. }