Hey there, fellow Go enthusiast! Ready to dive into the exciting world of AI with OpenAI's powerful API? You're in for a treat. In this guide, we'll walk through integrating OpenAI's API into your Go project using the nifty go-openai package. It's easier than you might think, and the possibilities are endless!
Before we jump in, make sure you've got:
Let's get our hands dirty! First things first:
mkdir openai-go-project cd openai-go-project go mod init openai-go-project go get github.com/sashabaranov/go-openai
Great! You've just created a new Go module and installed the go-openai package. We're off to a flying start!
Now, let's write some code. Create a new file called main.go
and add this:
package main import ( "context" "fmt" "os" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient(os.Getenv("OPENAI_API_KEY")) // We'll use this client to make API calls }
Make sure to set your API key as an environment variable. Security first, folks!
Let's try generating some text with GPT-3. Add this to your main
function:
resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, Messages: []openai.ChatCompletionMessage{ { Role: openai.ChatMessageRoleUser, Content: "Write a haiku about Go programming.", }, }, }, ) if err != nil { fmt.Printf("ChatCompletion error: %v\n", err) return } fmt.Println(resp.Choices[0].Message.Content)
Run it and voilà! You've just generated AI poetry. Who said programmers can't be artistic?
As you've seen, the response comes in a nice, structured format. The Message.Content
field gives you the generated text. But don't forget to handle those errors – they're not just there for decoration!
Feeling adventurous? Let's try streaming responses:
stream, err := client.CreateChatCompletionStream( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, Messages: []openai.ChatCompletionMessage{ { Role: openai.ChatMessageRoleUser, Content: "Tell me a short story about a Go gopher.", }, }, }, ) if err != nil { fmt.Printf("StreamCompletion error: %v\n", err) return } defer stream.Close() for { response, err := stream.Recv() if errors.Is(err, io.EOF) { return } if err != nil { fmt.Printf("Stream error: %v\n", err) return } fmt.Printf(response.Choices[0].Delta.Content) }
Now you're cooking with gas! This will print the story as it's generated, giving your users a more interactive experience.
A couple of quick tips to keep you out of trouble:
And there you have it! You're now equipped to harness the power of OpenAI in your Go projects. We've only scratched the surface here – there's so much more you can do with image generation, embeddings, and more.
Remember, the key to mastering any API is experimentation. So go forth, try things out, and build something awesome. The AI world is your oyster!
Happy coding, Gophers!