Created
January 14, 2024 21:19
-
-
Save marcboeker/6177ea03201c94ac188ef8c3dede970a to your computer and use it in GitHub Desktop.
OpenAI tool calling in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
openai "github.com/sashabaranov/go-openai" | |
"github.com/sashabaranov/go-openai/jsonschema" | |
) | |
func main() { | |
client := openai.NewClient("<your openai key>") | |
params := jsonschema.Definition{ | |
Type: jsonschema.Object, | |
Properties: map[string]jsonschema.Definition{ | |
"name": { | |
Type: jsonschema.String, | |
Description: "The contact's name without the salutation", | |
}, | |
"phone_number": { | |
Type: jsonschema.String, | |
Description: "The contact's phone number", | |
}, | |
"salutation": { | |
Type: jsonschema.String, | |
Enum: []string{"mrs", "mr"}, | |
Description: "The contact's salutation", | |
}, | |
}, | |
Required: []string{"name", "phone_number", "salutation"}, | |
} | |
f := openai.FunctionDefinition{ | |
Name: "extract_contact", | |
Description: "Extract a contact from a text", | |
Parameters: params, | |
} | |
t := openai.Tool{ | |
Type: openai.ToolTypeFunction, | |
Function: f, | |
} | |
dialogue := []openai.ChatCompletionMessage{ | |
{ | |
Role: openai.ChatMessageRoleUser, | |
Content: "You can reach Mrs. Miller at 123-456-7890 tomorrow afternoon.", | |
}, | |
} | |
resp, _ := client.CreateChatCompletion(context.Background(), | |
openai.ChatCompletionRequest{ | |
Model: openai.GPT3Dot5Turbo, | |
Messages: dialogue, | |
Tools: []openai.Tool{t}, | |
}, | |
) | |
for _, c := range resp.Choices { | |
for _, t := range c.Message.ToolCalls { | |
fmt.Printf("Function name: %s\nArguments:%v\n", t.Function.Name, t.Function.Arguments) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment