openai/openai-go

Public

mirrored from https://github.com/openai/openai-goAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
main

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

examples/chat-completion-tool-calling/main.go

92lines · modecode

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