Files
stainless-app[bot] 13778d44fe release: 3.0.0
2025-09-30 16:35:20 +00:00

93 lines
2.2 KiB
Go

package main
import (
"context"
"encoding/json"
"fmt"
"github.com/openai/openai-go/v3"
)
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.ChatCompletionMessageParamUnion{
openai.UserMessage(question),
},
Tools: []openai.ChatCompletionToolUnionParam{
openai.ChatCompletionFunctionTool(openai.FunctionDefinitionParam{
Name: "get_weather",
Description: openai.String("Get weather at the given location"),
Parameters: openai.FunctionParameters{
"type": "object",
"properties": map[string]any{
"location": map[string]string{
"type": "string",
},
},
"required": []string{"location"},
},
}),
},
Seed: openai.Int(0),
Model: 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
// Return 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 = append(params.Messages, completion.Choices[0].Message.ToParam())
for _, toolCall := range toolCalls {
if toolCall.Function.Name == "get_weather" {
// Extract the location from the function call arguments
var args map[string]interface{}
err := json.Unmarshal([]byte(toolCall.Function.Arguments), &args)
if 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 = append(params.Messages, openai.ToolMessage(weatherData, toolCall.ID))
}
}
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"
}