Skip to content

Commit c620096

Browse files
eliminated while loop
1 parent c4fc94a commit c620096

File tree

1 file changed

+24
-27
lines changed

1 file changed

+24
-27
lines changed

docs/guides/text/chat/chat_tools.cs

Lines changed: 24 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
#:package OpenAI@2.2.*-*
44
#:property PublishAot=false
55

6-
using System.Net.NetworkInformation;
76
using OpenAI.Chat;
87

98
string key = Environment.GetEnvironmentVariable("OPENAI_API_KEY")!;
@@ -32,36 +31,34 @@
3231
ChatMessage.CreateUserMessage("what is the current local time?")
3332
];
3433

35-
while (true)
34+
complete:
35+
ChatCompletion completion = client.CompleteChat(messages, options);
36+
messages.AddRange(ChatMessage.CreateAssistantMessage(completion));
37+
switch(completion.FinishReason)
3638
{
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)
39+
case ChatFinishReason.ToolCalls:
40+
Console.WriteLine($"{completion.ToolCalls.Count} tool call[s] detected.");
41+
foreach (ChatToolCall toolCall in completion.ToolCalls)
42+
{
43+
if (toolCall.FunctionName == nameof(MyTools.GetCurrentTime))
4544
{
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-
}
45+
string result = MyTools.GetCurrentTime();
46+
messages.Add(ChatMessage.CreateToolMessage(toolCall.Id, result));
5547
}
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-
}
48+
else
49+
{
50+
Console.WriteLine($"Unknown tool call: {toolCall.FunctionName}");
51+
}
52+
}
53+
goto complete;
54+
case ChatFinishReason.Stop:
55+
Console.WriteLine(completion.Content[0].Text);
56+
return;
57+
default:
58+
Console.WriteLine("Unexpected finish reason: " + completion.FinishReason);
59+
return;
6460
}
61+
6562
public static class MyTools
6663
{
6764
public static string GetCurrentTime(bool utc = false) => utc ? DateTime.UtcNow.ToString("HH:mm") : DateTime.Now.ToString("HH:mm");

0 commit comments

Comments
 (0)