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 OpenAI. Chat ;
7+
8+ string key = Environment . GetEnvironmentVariable ( "OPENAI_API_KEY" ) ! ;
9+ ChatClient client = new ( "gpt-4.1" , key ) ;
10+
11+ ChatCompletionOptions options = new ( ) ;
12+ options . Tools . Add ( ChatTool . CreateFunctionTool (
13+ functionName : nameof ( MyTools . GetCurrentTime ) ,
14+ functionDescription : "Get the current time in HH:mm format" ,
15+ functionParameters : BinaryData . FromObjectAsJson ( new
16+ {
17+ type = "object" ,
18+ properties = new
19+ {
20+ utc = new
21+ {
22+ type = "boolean" ,
23+ description = "If true, return the time in UTC. If false, return the local time."
24+ }
25+ } ,
26+ required = new object [ 0 ]
27+ } )
28+ ) ) ;
29+
30+ List < ChatMessage > messages = [
31+ ChatMessage . CreateUserMessage ( "what is the current local time?" )
32+ ] ;
33+
34+ complete :
35+ ChatCompletion completion = client . CompleteChat ( messages , options ) ;
36+ messages . AddRange ( ChatMessage . CreateAssistantMessage ( completion ) ) ;
37+ switch ( completion . FinishReason )
38+ {
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 ) )
44+ {
45+ string result = MyTools . GetCurrentTime ( ) ;
46+ messages . Add ( ChatMessage . CreateToolMessage ( toolCall . Id , result ) ) ;
47+ }
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 ;
60+ }
61+
62+ public static class MyTools
63+ {
64+ public static string GetCurrentTime ( bool utc = false ) => utc ? DateTime . UtcNow . ToString ( "HH:mm" ) : DateTime . Now . ToString ( "HH:mm" ) ;
65+ }
0 commit comments