Created
November 20, 2023 04:54
-
-
Save zephiransas/ced9cdef65481a36488c238fc9e21b82 to your computer and use it in GitHub Desktop.
OpenAI Function calling sample with go-openai
This file contains hidden or 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" | |
"encoding/json" | |
"fmt" | |
"os" | |
"github.com/sashabaranov/go-openai" | |
"github.com/sashabaranov/go-openai/jsonschema" | |
) | |
type ResponseArgs struct { | |
Artist string `json:"artist"` | |
Song string `json:"song"` | |
} | |
func main() { | |
ctx := context.TODO() | |
token := os.Getenv("OPENAI_API_KEY") | |
client := openai.NewClient(token) | |
res, err := client.CreateChatCompletion(ctx, openai.ChatCompletionRequest{ | |
Model: openai.GPT4TurboPreview, | |
Messages: []openai.ChatCompletionMessage{ | |
{ | |
Role: openai.ChatMessageRoleUser, | |
Content: "ミューズのスノーハレーション", | |
}, | |
}, | |
Tools: []openai.Tool{ | |
{ | |
Type: openai.ToolTypeFunction, | |
Function: openai.FunctionDefinition{ | |
Name: "get_artist_and_song_title", | |
Description: "アーティスト名と曲名を取得します", | |
Parameters: jsonschema.Definition{ | |
Type: jsonschema.Object, | |
Properties: map[string]jsonschema.Definition{ | |
"artist": { | |
Type: jsonschema.String, | |
Description: "アーティスト名。アーティスト名が省略されている場合、フルネームにしてください。 例:Ado", | |
}, | |
"song": { | |
Type: jsonschema.String, | |
Description: "曲名。 曲名が省略されている場合、フルネームにしてください。例:うっせぇわ", | |
}, | |
}, | |
Required: []string{"artist", "song"}, | |
}, | |
}, | |
}, | |
}, | |
}) | |
if err != nil { | |
fmt.Printf("error: %v\n", err) | |
panic(err) | |
} | |
var args ResponseArgs | |
err = json.Unmarshal([]byte(res.Choices[0].Message.ToolCalls[0].Function.Arguments), &args) | |
fmt.Println(args.Artist) | |
fmt.Println(args.Song) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment