Skip to content

Commit c4fc94a

Browse files
chat tool calls sample
1 parent 1e5da07 commit c4fc94a

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
// SAMPLE: Generate text from a simple prompt
2+
// GUIDANCE: Instructions to run this code: https://aka.ms/oai/net/start
3+
#:package OpenAI@2.2.*-*
4+
#:property PublishAot=false
5+
6+
using System.Net.NetworkInformation;
7+
using OpenAI.Chat;
8+
9+
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
10+
ChatClient client = new("gpt-4.1", key);
11+
12+
ChatCompletionOptions options = new();
13+
options.Tools.Add(ChatTool.CreateFunctionTool(
14+
functionName: nameof(MyTools.GetCurrentTime),
15+
functionDescription: "Get the current time in HH:mm format",
16+
functionParameters: BinaryData.FromObjectAsJson(new
17+
{
18+
type = "object",
19+
properties = new
20+
{
21+
utc = new
22+
{
23+
type = "boolean",
24+
description = "If true, return the time in UTC. If false, return the local time."
25+
}
26+
},
27+
required = new object[0]
28+
})
29+
));
30+
31+
List<ChatMessage> messages = [
32+
ChatMessage.CreateUserMessage("what is the current local time?")
33+
];
34+
35+
while (true)
36+
{
37+
complete:
38+
ChatCompletion completion = client.CompleteChat(messages, options);
39+
messages.AddRange(ChatMessage.CreateAssistantMessage(completion));
40+
switch(completion.FinishReason)
41+
{
42+
case ChatFinishReason.ToolCalls:
43+
Console.WriteLine($"{completion.ToolCalls.Count} tool call[s] detected.");
44+
foreach (ChatToolCall toolCall in completion.ToolCalls)
45+
{
46+
if (toolCall.FunctionName == nameof(MyTools.GetCurrentTime))
47+
{
48+
string result = MyTools.GetCurrentTime();
49+
messages.Add(ChatMessage.CreateToolMessage(toolCall.Id, result));
50+
}
51+
else
52+
{
53+
Console.WriteLine($"Unknown tool call: {toolCall.FunctionName}");
54+
}
55+
}
56+
goto complete;
57+
case ChatFinishReason.Stop:
58+
Console.WriteLine(completion.Content[0].Text);
59+
return;
60+
default:
61+
Console.WriteLine("Unexpected finish reason: " + completion.FinishReason);
62+
return;
63+
}
64+
}
65+
public static class MyTools
66+
{
67+
public static string GetCurrentTime(bool utc = false) => utc ? DateTime.UtcNow.ToString("HH:mm") : DateTime.Now.ToString("HH:mm");
68+
}

0 commit comments

Comments
 (0)