openai/openai-dotnet
Publicmirrored from https://github.com/openai/openai-dotnetAvailable
src/Utility/ResponseTools.cs
282lines · modecode
| 1 | using System; |
| 2 | using System.ClientModel.Primitives; |
| 3 | using System.Collections.Generic; |
| 4 | using System.IO; |
| 5 | using System.Linq; |
| 6 | using System.Reflection; |
| 7 | using System.Text.Json; |
| 8 | using System.Threading.Tasks; |
| 9 | using OpenAI.Agents; |
| 10 | using OpenAI.Embeddings; |
| 11 | using OpenAI.Responses; |
| 12 | |
| 13 | namespace OpenAI.Responses; |
| 14 | |
| 15 | /// <summary> |
| 16 | /// Provides functionality to manage and execute OpenAI function tools for responses. |
| 17 | /// </summary> |
| 18 | //[Experimental("OPENAIMCP001") |
| 19 | public class ResponseTools |
| 20 | { |
| 21 | private readonly Dictionary<string, MethodInfo> _methods = []; |
| 22 | private readonly Dictionary<string, Func<string, BinaryData, Task<BinaryData>>> _mcpMethods = []; |
| 23 | private readonly List<ResponseTool> _tools = []; |
| 24 | private readonly EmbeddingClient _client; |
| 25 | private readonly List<VectorDatabaseEntry> _entries = []; |
| 26 | private readonly List<McpClient> _mcpClients = []; |
| 27 | private readonly Dictionary<string, McpClient> _mcpClientsByEndpoint = []; |
| 28 | |
| 29 | /// <summary> |
| 30 | /// Initializes a new instance of the ResponseTools class with an optional embedding client. |
| 31 | /// </summary> |
| 32 | /// <param name="client">The embedding client used for tool vectorization, or null to disable vectorization.</param> |
| 33 | public ResponseTools(EmbeddingClient client = null) |
| 34 | { |
| 35 | _client = client; |
| 36 | } |
| 37 | |
| 38 | /// <summary> |
| 39 | /// Initializes a new instance of the ResponseTools class with the specified tool types. |
| 40 | /// </summary> |
| 41 | /// <param name="tools">Additional tool types to add.</param> |
| 42 | public ResponseTools(params Type[] tools) : this((EmbeddingClient)null) |
| 43 | { |
| 44 | foreach (var t in tools) |
| 45 | AddFunctionTool(t); |
| 46 | } |
| 47 | |
| 48 | /// <summary> |
| 49 | /// Gets the list of defined tools. |
| 50 | /// </summary> |
| 51 | public IList<ResponseTool> Tools => _tools; |
| 52 | |
| 53 | /// <summary> |
| 54 | /// Gets whether tools can be filtered using embeddings provided by the provided <see cref="EmbeddingClient"/> . |
| 55 | /// </summary> |
| 56 | public bool CanFilterTools => _client != null; |
| 57 | |
| 58 | /// <summary> |
| 59 | /// Adds local tool implementations from the provided types. |
| 60 | /// </summary> |
| 61 | /// <param name="tools">Types containing static methods to be used as tools.</param> |
| 62 | public void AddFunctionTools(params Type[] tools) |
| 63 | { |
| 64 | foreach (Type functionHolder in tools) |
| 65 | AddFunctionTool(functionHolder); |
| 66 | } |
| 67 | |
| 68 | /// <summary> |
| 69 | /// Adds all public static methods from the specified type as tools. |
| 70 | /// </summary> |
| 71 | /// <param name="tool">The type containing tool methods.</param> |
| 72 | internal void AddFunctionTool(Type tool) |
| 73 | { |
| 74 | #pragma warning disable IL2070 |
| 75 | foreach (MethodInfo function in tool.GetMethods(BindingFlags.Public | BindingFlags.Static)) |
| 76 | { |
| 77 | AddFunctionTool(function); |
| 78 | } |
| 79 | #pragma warning restore IL2070 |
| 80 | } |
| 81 | |
| 82 | internal void AddFunctionTool(MethodInfo function) |
| 83 | { |
| 84 | string name = function.Name; |
| 85 | var tool = ResponseTool.CreateFunctionTool(name, ToolsUtility.GetMethodDescription(function), ToolsUtility.BuildParametersJson(function.GetParameters())); |
| 86 | _tools.Add(tool); |
| 87 | _methods[name] = function; |
| 88 | } |
| 89 | |
| 90 | /// <summary> |
| 91 | /// Adds a remote MCP server as a tool provider. |
| 92 | /// </summary> |
| 93 | /// <param name="client">The MCP client instance.</param> |
| 94 | /// <returns>A task representing the asynchronous operation.</returns> |
| 95 | internal async Task AddMcpToolsAsync(McpClient client) |
| 96 | { |
| 97 | if (client == null) throw new ArgumentNullException(nameof(client)); |
| 98 | _mcpClientsByEndpoint[client.Endpoint.AbsoluteUri] = client; |
| 99 | await client.StartAsync().ConfigureAwait(false); |
| 100 | BinaryData tools = await client.ListToolsAsync().ConfigureAwait(false); |
| 101 | await AddMcpToolsAsync(tools, client).ConfigureAwait(false); |
| 102 | _mcpClients.Add(client); |
| 103 | } |
| 104 | |
| 105 | /// <summary> |
| 106 | /// Adds a remote MCP server as a tool provider. |
| 107 | /// </summary> |
| 108 | /// <param name="mcpEndpoint">The URI endpoint of the MCP server.</param> |
| 109 | /// <returns>A task representing the asynchronous operation.</returns> |
| 110 | public async Task AddMcpToolsAsync(Uri mcpEndpoint) |
| 111 | { |
| 112 | var client = new McpClient(mcpEndpoint); |
| 113 | await AddMcpToolsAsync(client).ConfigureAwait(false); |
| 114 | } |
| 115 | |
| 116 | private async Task AddMcpToolsAsync(BinaryData toolDefinitions, McpClient client) |
| 117 | { |
| 118 | List<ResponseTool> toolsToVectorize = new(); |
| 119 | var parsedTools = ToolsUtility.ParseMcpToolDefinitions(toolDefinitions, client); |
| 120 | |
| 121 | foreach (var (name, description, inputSchema) in parsedTools) |
| 122 | { |
| 123 | var responseTool = ResponseTool.CreateFunctionTool(name, description, BinaryData.FromString(inputSchema)); |
| 124 | _tools.Add(responseTool); |
| 125 | toolsToVectorize.Add(responseTool); |
| 126 | _mcpMethods[name] = client.CallToolAsync; |
| 127 | } |
| 128 | |
| 129 | if (_client != null) |
| 130 | { |
| 131 | var embeddings = await _client.GenerateEmbeddingsAsync(toolsToVectorize.ConvertAll(GetDescription)).ConfigureAwait(false); |
| 132 | foreach (var embedding in embeddings.Value) |
| 133 | { |
| 134 | var vector = embedding.ToFloats(); |
| 135 | var item = toolsToVectorize[embedding.Index]; |
| 136 | var toolDefinition = SerializeTool(item); |
| 137 | _entries.Add(new VectorDatabaseEntry(vector, toolDefinition)); |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | private string GetDescription(ResponseTool tool) => (tool as InternalResponsesFunctionTool)?.Description ?? ""; |
| 143 | |
| 144 | private BinaryData SerializeTool(ResponseTool tool) |
| 145 | { |
| 146 | var functionTool = tool as InternalResponsesFunctionTool; |
| 147 | return ToolsUtility.SerializeTool(functionTool?.Name, functionTool?.Description, functionTool?.Parameters ?? BinaryData.FromString("{}")); |
| 148 | } |
| 149 | |
| 150 | private ResponseTool ParseToolDefinition(BinaryData data) |
| 151 | { |
| 152 | using var document = JsonDocument.Parse(data); |
| 153 | var root = document.RootElement; |
| 154 | |
| 155 | return ResponseTool.CreateFunctionTool( |
| 156 | root.GetProperty("name").GetString()!, |
| 157 | root.GetProperty("description").GetString()!, |
| 158 | BinaryData.FromString(root.GetProperty("inputSchema").GetRawText())); |
| 159 | } |
| 160 | |
| 161 | /// <summary> |
| 162 | /// Converts the tools collection to <see cref="ResponseCreationOptions"> configured with the tools contained in this instance.. |
| 163 | /// </summary> |
| 164 | /// <returns>A new ResponseCreationOptions containing all defined tools.</returns> |
| 165 | public ResponseCreationOptions ToResponseCreationOptions() |
| 166 | { |
| 167 | var options = new ResponseCreationOptions(); |
| 168 | foreach (var tool in _tools) |
| 169 | options.Tools.Add(tool); |
| 170 | return options; |
| 171 | } |
| 172 | |
| 173 | /// <summary> |
| 174 | /// Converts the tools collection to <see cref="ResponseCreationOptions">, filtered by relevance to the given prompt. |
| 175 | /// </summary> |
| 176 | /// <param name="prompt">The prompt to find relevant tools for.</param> |
| 177 | /// <param name="maxTools">The maximum number of tools to return. Default is 5.</param> |
| 178 | /// <param name="minVectorDistance">The similarity threshold for including tools. Default is 0.29.</param> |
| 179 | /// <returns>A new ResponseCreationOptions containing the most relevant tools.</returns> |
| 180 | public ResponseCreationOptions ToResponseCreationOptions(string prompt, int maxTools = 5, float minVectorDistance = 0.29f) |
| 181 | { |
| 182 | if (!CanFilterTools) |
| 183 | return ToResponseCreationOptions(); |
| 184 | |
| 185 | var completionOptions = new ResponseCreationOptions(); |
| 186 | foreach (var tool in FindRelatedTools(false, prompt, maxTools, minVectorDistance).GetAwaiter().GetResult()) |
| 187 | completionOptions.Tools.Add(tool); |
| 188 | return completionOptions; |
| 189 | } |
| 190 | |
| 191 | /// <summary> |
| 192 | /// Converts the tools collection to <see cref="ResponseCreationOptions">, filtered by relevance to the given prompt. |
| 193 | /// </summary> |
| 194 | /// <param name="prompt">The prompt to find relevant tools for.</param> |
| 195 | /// <param name="maxTools">The maximum number of tools to return. Default is 5.</param> |
| 196 | /// <param name="minVectorDistance">The similarity threshold for including tools. Default is 0.29.</param> |
| 197 | /// <returns>A new ResponseCreationOptions containing the most relevant tools.</returns> |
| 198 | public async Task<ResponseCreationOptions> ToResponseCreationOptionsAsync(string prompt, int maxTools = 5, float minVectorDistance = 0.29f) |
| 199 | { |
| 200 | if (!CanFilterTools) |
| 201 | return ToResponseCreationOptions(); |
| 202 | |
| 203 | var completionOptions = new ResponseCreationOptions(); |
| 204 | foreach (var tool in await FindRelatedTools(true, prompt, maxTools, minVectorDistance).ConfigureAwait(false)) |
| 205 | completionOptions.Tools.Add(tool); |
| 206 | return completionOptions; |
| 207 | } |
| 208 | |
| 209 | private async Task<IEnumerable<ResponseTool>> FindRelatedTools(bool async, string prompt, int maxTools, float minVectorDistance) |
| 210 | { |
| 211 | if (!CanFilterTools) |
| 212 | return _tools; |
| 213 | |
| 214 | return (await FindVectorMatches(async, prompt, maxTools, minVectorDistance).ConfigureAwait(false)) |
| 215 | .Select(e => ParseToolDefinition(e.Data)); |
| 216 | } |
| 217 | |
| 218 | private async Task<IEnumerable<VectorDatabaseEntry>> FindVectorMatches(bool async, string prompt, int maxTools, float minVectorDistance) |
| 219 | { |
| 220 | var vector = async ? |
| 221 | await ToolsUtility.GetEmbeddingAsync(_client, prompt).ConfigureAwait(false) : |
| 222 | ToolsUtility.GetEmbedding(_client, prompt); |
| 223 | lock (_entries) |
| 224 | { |
| 225 | return ToolsUtility.GetClosestEntries(_entries, maxTools, minVectorDistance, vector); |
| 226 | } |
| 227 | } |
| 228 | |
| 229 | internal async Task<string> CallFunctionToolAsync(FunctionCallResponseItem call) |
| 230 | { |
| 231 | List<object> arguments = new(); |
| 232 | if (call.FunctionArguments != null) |
| 233 | { |
| 234 | if (!_methods.TryGetValue(call.FunctionName, out MethodInfo method)) |
| 235 | return $"I don't have a tool called {call.FunctionName}"; |
| 236 | |
| 237 | ToolsUtility.ParseFunctionCallArgs(method, call.FunctionArguments, out arguments); |
| 238 | } |
| 239 | |
| 240 | return await ToolsUtility.CallFunctionToolAsync(_methods, call.FunctionName, [.. arguments]); |
| 241 | } |
| 242 | |
| 243 | internal async Task<string> CallMcpAsync(FunctionCallResponseItem call) |
| 244 | { |
| 245 | if (!_mcpMethods.TryGetValue(call.FunctionName, out var method)) |
| 246 | throw new NotImplementedException($"MCP tool {call.FunctionName} not found."); |
| 247 | |
| 248 | #if !NETSTANDARD2_0 |
| 249 | var actualFunctionName = call.FunctionName.Split(ToolsUtility.McpToolSeparator, 2)[1]; |
| 250 | #else |
| 251 | var index = call.FunctionName.IndexOf(ToolsUtility.McpToolSeparator); |
| 252 | var actualFunctionName = call.FunctionName.Substring(index + ToolsUtility.McpToolSeparator.Length); |
| 253 | #endif |
| 254 | var result = await method(actualFunctionName, call.FunctionArguments).ConfigureAwait(false); |
| 255 | return result.ToString(); |
| 256 | } |
| 257 | |
| 258 | /// <summary> |
| 259 | /// Executes a function call and returns its result as a FunctionCallOutputResponseItem. |
| 260 | /// </summary> |
| 261 | /// <param name="toolCall">The function call to execute.</param> |
| 262 | /// <returns>A task that represents the asynchronous operation and contains the function call result.</returns> |
| 263 | public async Task<FunctionCallOutputResponseItem> CallAsync(FunctionCallResponseItem toolCall) |
| 264 | { |
| 265 | bool isMcpTool = false; |
| 266 | if (!_methods.ContainsKey(toolCall.FunctionName)) |
| 267 | { |
| 268 | if (_mcpMethods.ContainsKey(toolCall.FunctionName)) |
| 269 | { |
| 270 | isMcpTool = true; |
| 271 | } |
| 272 | else |
| 273 | { |
| 274 | return new FunctionCallOutputResponseItem(toolCall.CallId, $"I don't have a tool called {toolCall.FunctionName}"); |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | var result = isMcpTool ? await CallMcpAsync(toolCall).ConfigureAwait(false) : await CallFunctionToolAsync(toolCall); |
| 279 | return new FunctionCallOutputResponseItem(toolCall.CallId, result); |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | |