openai/openai-dotnet

Public

mirrored from https://github.com/openai/openai-dotnetAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
jsquire-patch-1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

src/Utility/ChatTools.cs

287lines · modeblame

9308b2b1Christopher Scott1 years ago1using System;
2using System.ClientModel.Primitives;
3using System.Collections.Generic;
4using System.IO;
5using System.Linq;
6using System.Reflection;
7using System.Text.Json;
8using System.Threading.Tasks;
9using OpenAI.Agents;
10using OpenAI.Chat;
11using OpenAI.Embeddings;
12
13namespace OpenAI.Chat;
14
15/// <summary>
16/// Provides functionality to manage and execute OpenAI function tools for chat completions.
17/// </summary>
18//[Experimental("OPENAIMCP001")]
19public class ChatTools
20{
21private readonly Dictionary<string, MethodInfo> _methods = [];
22private readonly Dictionary<string, Func<string, BinaryData, Task<BinaryData>>> _mcpMethods = [];
23private readonly List<ChatTool> _tools = [];
24private readonly EmbeddingClient _client;
25private readonly List<VectorDatabaseEntry> _entries = [];
26private readonly List<McpClient> _mcpClients = [];
27private readonly Dictionary<string, McpClient> _mcpClientsByEndpoint = [];
28
29/// <summary>
30/// Initializes a new instance of the ChatTools 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>
33public ChatTools(EmbeddingClient client = null)
34{
35_client = client;
36}
37
38/// <summary>
39/// Initializes a new instance of the ChatTools class with the specified tool types.
40/// </summary>
41/// <param name="tools">Additional tool types to add.</param>
42public ChatTools(params Type[] tools) : this((EmbeddingClient)null)
43{
44foreach (var t in tools)
45AddFunctionTool(t);
46}
47
48/// <summary>
49/// Gets the list of defined tools.
50/// </summary>
51public IList<ChatTool> Tools => _tools;
52
53/// <summary>
54/// Gets whether tools can be filtered using embeddings provided by the provided <see cref="EmbeddingClient"/> .
55/// </summary>
56public 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>
62public void AddFunctionTools(params Type[] tools)
63{
64foreach (Type functionHolder in tools)
65AddFunctionTool(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>
72internal void AddFunctionTool(Type tool)
73{
74#pragma warning disable IL2070
75foreach (MethodInfo function in tool.GetMethods(BindingFlags.Public | BindingFlags.Static))
76{
77AddFunctionTool(function);
78}
79#pragma warning restore IL2070
80}
81
82internal void AddFunctionTool(MethodInfo function)
83{
84string name = function.Name;
85var tool = ChatTool.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>
95internal async Task AddMcpToolsAsync(McpClient client)
96{
97if (client == null) throw new ArgumentNullException(nameof(client));
98_mcpClientsByEndpoint[client.Endpoint.AbsoluteUri] = client;
99await client.StartAsync().ConfigureAwait(false);
100BinaryData tools = await client.ListToolsAsync().ConfigureAwait(false);
101await 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>
110public async Task AddMcpToolsAsync(Uri mcpEndpoint)
111{
112var client = new McpClient(mcpEndpoint);
113await AddMcpToolsAsync(client).ConfigureAwait(false);
114}
115
116private async Task AddMcpToolsAsync(BinaryData toolDefinitions, McpClient client)
117{
118List<ChatTool> toolsToVectorize = new();
119var parsedTools = ToolsUtility.ParseMcpToolDefinitions(toolDefinitions, client);
120
121foreach (var (name, description, inputSchema) in parsedTools)
122{
123var chatTool = ChatTool.CreateFunctionTool(name, description, BinaryData.FromString(inputSchema));
124_tools.Add(chatTool);
125toolsToVectorize.Add(chatTool);
126_mcpMethods[name] = client.CallToolAsync;
127}
128
129if (_client != null)
130{
131var embeddings = await _client.GenerateEmbeddingsAsync(toolsToVectorize.Select(t => t.FunctionDescription).ToList()).ConfigureAwait(false);
132foreach (var embedding in embeddings.Value)
133{
134var vector = embedding.ToFloats();
135var item = toolsToVectorize[embedding.Index];
136var toolDefinition = SerializeTool(item);
137_entries.Add(new VectorDatabaseEntry(vector, toolDefinition));
138}
139}
140}
141
142private BinaryData SerializeTool(ChatTool tool)
143{
144return ToolsUtility.SerializeTool(tool.FunctionName, tool.FunctionDescription, tool.FunctionParameters);
145}
146
147private ChatTool ParseToolDefinition(BinaryData data)
148{
149using var document = JsonDocument.Parse(data);
150var root = document.RootElement;
151
152return ChatTool.CreateFunctionTool(
153root.GetProperty("name").GetString()!,
154root.GetProperty("description").GetString()!,
155BinaryData.FromString(root.GetProperty("inputSchema").GetRawText()));
156}
157
158/// <summary>
159/// Converts the tools collection to chat completion options.
160/// </summary>
161/// <returns>A new ChatCompletionOptions containing all defined tools.</returns>
162public ChatCompletionOptions ToChatCompletionOptions()
163{
164var options = new ChatCompletionOptions();
165foreach (var tool in _tools)
166options.Tools.Add(tool);
167return options;
168}
169
170/// <summary>
171/// Converts the tools collection to <see cref="ChatCompletionOptions"/>, filtered by relevance to the given prompt.
172/// </summary>
173/// <param name="prompt">The prompt to find relevant tools for.</param>
174/// <param name="maxTools">The maximum number of tools to return. Default is 3.</param>
175/// <param name="minVectorDistance">The similarity threshold for including tools. Default is 0.29.</param>
176/// <returns>A new <see cref="ChatCompletionOptions"/> containing the most relevant tools.</returns>
177public ChatCompletionOptions CreateCompletionOptions(string prompt, int maxTools = 5, float minVectorDistance = 0.29f)
178{
179if (!CanFilterTools)
180return ToChatCompletionOptions();
181
182var completionOptions = new ChatCompletionOptions();
183foreach (var tool in FindRelatedTools(false, prompt, maxTools, minVectorDistance).GetAwaiter().GetResult())
184completionOptions.Tools.Add(tool);
185return completionOptions;
186}
187
188/// <summary>
189/// Converts the tools collection to <see cref="ChatCompletionOptions"/>, filtered by relevance to the given prompt.
190/// </summary>
191/// <param name="prompt">The prompt to find relevant tools for.</param>
192/// <param name="maxTools">The maximum number of tools to return. Default is 3.</param>
193/// <param name="minVectorDistance">The similarity threshold for including tools. Default is 0.29.</param>
194/// <returns>A new <see cref="ChatCompletionOptions"/> containing the most relevant tools.</returns>
195public async Task<ChatCompletionOptions> ToChatCompletionOptions(string prompt, int maxTools = 5, float minVectorDistance = 0.29f)
196{
197if (!CanFilterTools)
198return ToChatCompletionOptions();
199
200var completionOptions = new ChatCompletionOptions();
201foreach (var tool in await FindRelatedTools(true, prompt, maxTools, minVectorDistance).ConfigureAwait(false))
202completionOptions.Tools.Add(tool);
203return completionOptions;
204}
205
206private async Task<IEnumerable<ChatTool>> FindRelatedTools(bool async, string prompt, int maxTools, float minVectorDistance)
207{
208if (!CanFilterTools)
209return _tools;
210
211return (await FindVectorMatches(async, prompt, maxTools, minVectorDistance).ConfigureAwait(false))
212.Select(e => ParseToolDefinition(e.Data));
213}
214
215private async Task<IEnumerable<VectorDatabaseEntry>> FindVectorMatches(bool async, string prompt, int maxTools, float minVectorDistance)
216{
217var vector = async ?
218await ToolsUtility.GetEmbeddingAsync(_client, prompt).ConfigureAwait(false) :
219ToolsUtility.GetEmbedding(_client, prompt);
220
221lock (_entries)
222{
223return ToolsUtility.GetClosestEntries(_entries, maxTools, minVectorDistance, vector);
224}
225}
226
227internal async Task<string> CallFunctionToolAsync(ChatToolCall call)
228{
229var arguments = new List<object>();
230if (call.FunctionArguments != null)
231{
232if (!_methods.TryGetValue(call.FunctionName, out MethodInfo method))
233throw new InvalidOperationException($"Tool not found: {call.FunctionName}");
234
235ToolsUtility.ParseFunctionCallArgs(method, call.FunctionArguments, out arguments);
236}
237return await ToolsUtility.CallFunctionToolAsync(_methods, call.FunctionName, [.. arguments]);
238}
239
240internal async Task<string> CallMcpAsync(ChatToolCall call)
241{
242if (!_mcpMethods.TryGetValue(call.FunctionName, out var method))
243throw new NotImplementedException($"MCP tool {call.FunctionName} not found.");
244
245#if !NETSTANDARD2_0
246var actualFunctionName = call.FunctionName.Split(ToolsUtility.McpToolSeparator, 2)[1];
247#else
248var index = call.FunctionName.IndexOf(ToolsUtility.McpToolSeparator);
249var actualFunctionName = call.FunctionName.Substring(index + ToolsUtility.McpToolSeparator.Length);
250#endif
251var result = await method(actualFunctionName, call.FunctionArguments).ConfigureAwait(false);
252if (result == null)
253throw new InvalidOperationException($"MCP tool {call.FunctionName} returned null. Function tools should always return a value.");
254return result.ToString();
255}
256
257/// <summary>
258/// Executes all tool calls and returns their results.
259/// </summary>
260/// <param name="toolCalls">The collection of tool calls to execute.</param>
261/// <returns>A collection of tool chat messages containing the results.</returns>
262public async Task<IEnumerable<ToolChatMessage>> CallAsync(IEnumerable<ChatToolCall> toolCalls)
263{
264var messages = new List<ToolChatMessage>();
265foreach (ChatToolCall toolCall in toolCalls)
266{
267bool isMcpTool = false;
268if (!_methods.ContainsKey(toolCall.FunctionName))
269{
270if (_mcpMethods.ContainsKey(toolCall.FunctionName))
271{
272isMcpTool = true;
273}
274else
275{
276throw new InvalidOperationException("Tool not found: " + toolCall.FunctionName);
277}
278}
279
280var result = isMcpTool ? await CallMcpAsync(toolCall).ConfigureAwait(false) : await CallFunctionToolAsync(toolCall).ConfigureAwait(false);
281messages.Add(new ToolChatMessage(toolCall.Id, result));
282}
283
284return messages;
285}
286}
287