Skip to content

Instantly share code, notes, and snippets.

@jeremytregunna
Created February 11, 2025 01:21
Show Gist options
  • Save jeremytregunna/e41c6f61356326155abbf3d7bd79a7c4 to your computer and use it in GitHub Desktop.
Save jeremytregunna/e41c6f61356326155abbf3d7bd79a7c4 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"log"
"os"
"time"
"github.com/joho/godotenv"
"github.com/openai/openai-go"
"github.com/openai/openai-go/option"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
apiKey := os.Getenv("OPENAI_API_KEY")
if apiKey == "" {
log.Fatal("OPENAI_API_KEY is required")
}
baseUrl := os.Getenv("OPENAI_BASE_URL")
model := os.Getenv("LLM_MODEL")
if model == "" {
log.Fatal("LLM_MODEL is required")
}
client := openai.NewClient(
option.WithAPIKey(apiKey),
option.WithBaseURL(baseUrl),
)
params := openai.ChatCompletionNewParams{
Messages: openai.F([]openai.ChatCompletionMessageParamUnion{
openai.UserMessage("What is the current date?"),
}),
Tools: openai.F([]openai.ChatCompletionToolParam{
{
Type: openai.F(openai.ChatCompletionToolTypeFunction),
Function: openai.F(openai.FunctionDefinitionParam{
Name: openai.String("get_current_date"),
Description: openai.String("Get the current date"),
Parameters: openai.F(openai.FunctionParameters{
"type": "object",
"properties": map[string]interface{}{},
}),
}),
},
}),
Seed: openai.Int(0),
Model: openai.F(model),
}
completion, err := client.Chat.Completions.New(context.TODO(), params)
if err != nil {
log.Fatalf("Error: %s", err)
}
toolCalls := completion.Choices[0].Message.ToolCalls
if len(toolCalls) == 0 {
log.Printf("No function call")
return
}
params.Messages.Value = append(params.Messages.Value, completion.Choices[0].Message)
for _, toolCall := range toolCalls {
if toolCall.Function.Name == "get_current_date" {
// No params, can ignore args
currentDate := time.Now().Format("2006-01-02")
log.Printf("Current date: %s", currentDate)
params.Messages.Value = append(params.Messages.Value, openai.ToolMessage(toolCall.ID, currentDate))
}
}
completion, err = client.Chat.Completions.New(context.TODO(), params)
if err != nil {
log.Fatalf("Error: %s", err)
}
log.Printf("Chat completion: %s", completion.Choices[0].Message.Content)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment