-
Notifications
You must be signed in to change notification settings - Fork 348
Add ChatTools and ResponseTools helper classes #422
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
joseharriaga
merged 28 commits into
openai:main
from
christothes:chriss/chatToolsExtensions
May 9, 2025
Merged
Changes from 1 commit
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
a0ec8a3
wip
christothes 04b7069
wip
christothes 294ed2d
wip
christothes d909b21
wip
christothes 1dfadee
fix mcp name placeholder
christothes 12e8a87
make mcp types internal
christothes 47f3e2d
cleanup
christothes 93f94c6
docs
christothes 8ab51f1
cleanup
christothes 4309965
namespaces
christothes dcc655c
feedback
christothes 24f1821
feedback
christothes a63b571
feedback
christothes 7bc969c
feedback
christothes d8da69a
wip tests
christothes 567ffa0
tests
christothes fe67356
fb
christothes 385dd35
fb
christothes 78e3e5f
refactor
christothes f46fd40
fb
christothes 4009c2b
fb
christothes 5703fc0
fb
christothes 76b907a
fb
christothes 5ce1d02
fb
christothes c984bc8
async tools
christothes de89187
fix rename
christothes 869a455
remove McpClient
christothes 6079911
warnings
christothes File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,110 @@ | ||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.IO; | ||
| using System.Reflection; | ||
| using System.Text.Json; | ||
| using System.Threading.Tasks; | ||
| using OpenAI.Chat; | ||
| using OpenAI.Embeddings; | ||
|
|
||
| namespace OpenAI; | ||
|
|
||
| /// <summary> | ||
| /// The service client for OpenAI Chat Completions endpoint tools. | ||
| /// </summary> | ||
| public class ChatTools : ToolsBase<ChatTool> | ||
| { | ||
| public ChatTools(EmbeddingClient client = null) : base(client) { } | ||
|
|
||
| public ChatTools(Type tool, params Type[] additionalTools) : this((EmbeddingClient)null) | ||
| { | ||
| Add(tool); | ||
| if (additionalTools != null) | ||
| foreach (var t in additionalTools) | ||
| Add(t); | ||
| } | ||
|
|
||
| internal override ChatTool MethodInfoToTool(MethodInfo methodInfo) => | ||
| ChatTool.CreateFunctionTool(methodInfo.Name, GetMethodDescription(methodInfo), BuildParametersJson(methodInfo.GetParameters())); | ||
|
|
||
| protected override async Task Add(BinaryData toolDefinitions, McpClient client) | ||
| { | ||
| using var document = JsonDocument.Parse(toolDefinitions); | ||
| if (!document.RootElement.TryGetProperty("tools", out JsonElement toolsElement)) | ||
| throw new JsonException("The JSON document must contain a 'tools' array."); | ||
|
|
||
| var serverKey = client.ServerEndpoint.Host + client.ServerEndpoint.Port.ToString(); | ||
| List<ChatTool> toolsToVectorize = new(); | ||
|
|
||
| foreach (var tool in toolsElement.EnumerateArray()) | ||
| { | ||
| var name = $"{serverKey}{_mcpToolSeparator}{tool.GetProperty("name").GetString()!}"; | ||
| var description = tool.GetProperty("description").GetString()!; | ||
| #pragma warning disable IL2026, IL3050 | ||
| var inputSchema = JsonSerializer.Serialize( | ||
| JsonSerializer.Deserialize<JsonElement>(tool.GetProperty("inputSchema").GetRawText()), | ||
| new JsonSerializerOptions { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping }); | ||
| #pragma warning restore IL2026, IL3050 | ||
|
|
||
| var chatTool = ChatTool.CreateFunctionTool(name, description, BinaryData.FromString(inputSchema)); | ||
| _definitions.Add(chatTool); | ||
| toolsToVectorize.Add(chatTool); | ||
| _mcpMethods[name] = client.CallToolAsync; | ||
| } | ||
|
|
||
| await AddToolsToVectorBaseAsync(toolsToVectorize).ConfigureAwait(false); | ||
| } | ||
|
|
||
| protected override string GetDescription(ChatTool tool) => tool.FunctionDescription; | ||
|
|
||
| protected override BinaryData SerializeTool(ChatTool tool) | ||
| { | ||
| using var stream = new MemoryStream(); | ||
| using var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { Indented = true }); | ||
|
|
||
| writer.WriteStartObject(); | ||
| writer.WriteString("name", tool.FunctionName); | ||
| writer.WriteString("description", tool.FunctionDescription); | ||
| writer.WritePropertyName("inputSchema"); | ||
| using (var doc = JsonDocument.Parse(tool.FunctionParameters)) | ||
| doc.RootElement.WriteTo(writer); | ||
| writer.WriteEndObject(); | ||
| writer.Flush(); | ||
|
|
||
| stream.Position = 0; | ||
| return BinaryData.FromStream(stream); | ||
| } | ||
|
|
||
| protected override ChatTool ParseToolDefinition(BinaryData data) | ||
| { | ||
| using var document = JsonDocument.Parse(data); | ||
| var root = document.RootElement; | ||
|
|
||
| return ChatTool.CreateFunctionTool( | ||
| root.GetProperty("name").GetString()!, | ||
| root.GetProperty("description").GetString()!, | ||
| BinaryData.FromString(root.GetProperty("inputSchema").GetRawText())); | ||
| } | ||
|
|
||
| public ChatCompletionOptions ToOptions() | ||
| { | ||
| var options = new ChatCompletionOptions(); | ||
| foreach (var tool in _definitions) | ||
| options.Tools.Add(tool); | ||
| return options; | ||
| } | ||
|
|
||
| public ChatCompletionOptions ToOptions(string prompt, ToolFindOptions options = null) | ||
| { | ||
| if (!CanFilterTools) | ||
| return ToOptions(); | ||
|
|
||
| var completionOptions = new ChatCompletionOptions(); | ||
| foreach (var tool in RelatedTo(prompt, options?.MaxEntries ?? 5)) | ||
| completionOptions.Tools.Add(tool); | ||
| return completionOptions; | ||
| } | ||
|
|
||
| public static implicit operator ChatCompletionOptions(ChatTools tools) => tools.ToOptions(); | ||
| } | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| using System; | ||
| using System.ClientModel.Primitives; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace OpenAI; | ||
|
|
||
| public class McpClient | ||
| { | ||
| private readonly McpSession _session; | ||
| private readonly ClientPipeline _pipeline = ClientPipeline.Create(); | ||
|
|
||
| public virtual Uri ServerEndpoint { get; } | ||
|
|
||
| public McpClient(Uri endpoint) | ||
| { | ||
| _session = new McpSession(endpoint, _pipeline); | ||
| ServerEndpoint = endpoint; | ||
| } | ||
|
|
||
| public virtual async Task StartAsync() | ||
| { | ||
| await _session.EnsureInitializedAsync().ConfigureAwait(false); | ||
| } | ||
|
|
||
| public virtual async Task<BinaryData> ListToolsAsync() | ||
| { | ||
| if (_session == null) | ||
| throw new InvalidOperationException("Session is not initialized. Call StartAsync() first."); | ||
|
|
||
| return await _session.SendMethod("tools/list").ConfigureAwait(false); | ||
| } | ||
|
|
||
| public virtual async Task<BinaryData> CallToolAsync(string toolName, BinaryData parameters) | ||
| { | ||
| if (_session == null) | ||
| throw new InvalidOperationException("Session is not initialized. Call StartAsync() first."); | ||
|
|
||
| Console.WriteLine($"Calling tool {toolName}..."); | ||
| return await _session.CallTool(toolName, parameters).ConfigureAwait(false); | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.