-
Notifications
You must be signed in to change notification settings - Fork 35
/
main.go
94 lines (77 loc) · 2.37 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go"
)
func main() {
client := openai.NewClient()
ctx := context.Background()
question := "What is the weather in New York City?"
print("> ")
println(question)
params := openai.ChatCompletionNewParams{
Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
openai.UserMessage(question),
}),
Tools: openai.F([]openai.ChatCompletionToolParam{
{
Type: openai.F(openai.ChatCompletionToolTypeFunction),
Function: openai.F(openai.FunctionDefinitionParam{
Name: openai.String("get_weather"),
Description: openai.String("Get weather at the given location"),
Parameters: openai.F(openai.FunctionParameters{
"type": "object",
"properties": map[string]interface{}{
"location": map[string]string{
"type": "string",
},
},
"required": []string{"location"},
}),
}),
},
}),
Seed: openai.Int(0),
Model: openai.F(openai.ChatModelGPT4o),
}
// Make initial chat completion request
completion, err := client.Chat.Completions.New(ctx, params)
if err != nil {
panic(err)
}
toolCalls := completion.Choices[0].Message.ToolCalls
// Abort early if there are no tool calls
if len(toolCalls) == 0 {
fmt.Printf("No function call")
return
}
// If there is a was a function call, continue the conversation
params.Messages.Value = append(params.Messages.Value, completion.Choices[0].Message)
for _, toolCall := range toolCalls {
if toolCall.Function.Name == "get_weather" {
// Extract the location from the function call arguments
var args map[string]interface{}
if err := json.Unmarshal([]byte(toolCall.Function.Arguments), &args); err != nil {
panic(err)
}
location := args["location"].(string)
// Simulate getting weather data
weatherData := getWeather(location)
// Print the weather data
fmt.Printf("Weather in %s: %s\n", location, weatherData)
params.Messages.Value = append(params.Messages.Value, openai.ToolMessage(toolCall.ID, weatherData))
}
}
completion, err = client.Chat.Completions.New(ctx, params)
if err != nil {
panic(err)
}
println(completion.Choices[0].Message.Content)
}
// Mock function to simulate weather data retrieval
func getWeather(location string) string {
// In a real implementation, this function would call a weather API
return "Sunny, 25°C"
}