Hey there, fellow Go developer! Ready to supercharge your applications with some AI goodness? You're in the right place. We're about to dive into integrating Azure OpenAI Service into your Go projects using the nifty azopenai package. Buckle up!
Before we jump in, make sure you've got:
Let's get this show on the road:
mkdir azure-openai-go cd azure-openai-go go mod init azure-openai-go go get github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai
Boom! You're all set up.
Time to get your keys:
export AZURE_OPENAI_KEY=your_api_key_here export AZURE_OPENAI_ENDPOINT=your_endpoint_here
Pro tip: Add these to your .bashrc
or .zshrc
to avoid typing them every time.
Let's write some Go! Create a main.go
file and add this:
package main import ( "github.com/Azure/azure-sdk-for-go/sdk/ai/azopenai" "os" ) func main() { client, err := azopenai.NewClient(os.Getenv("AZURE_OPENAI_ENDPOINT"), os.Getenv("AZURE_OPENAI_KEY"), nil) if err != nil { panic(err) } // We'll use this client later }
Now for the fun part! Let's generate some text:
func main() { // ... client initialization code ... resp, err := client.GetCompletions(context.Background(), azopenai.CompletionsOptions{ Prompt: []string{"Write a haiku about coding in Go"}, MaxTokens: 100, Temperature: 0.7, }, nil) if err != nil { panic(err) } fmt.Println(resp.Choices[0].Text) }
Run it and watch the magic happen!
Always check for errors (you're doing great so far!). Also, keep an eye on those rate limits. Azure OpenAI Service has quotas, so be nice and don't spam requests.
Let's build a simple chatbot:
func chatbot() { client, _ := azopenai.NewClient(os.Getenv("AZURE_OPENAI_ENDPOINT"), os.Getenv("AZURE_OPENAI_KEY"), nil) for { fmt.Print("You: ") input, _ := bufio.NewReader(os.Stdin).ReadString('\n') resp, err := client.GetChatCompletions(context.Background(), azopenai.ChatCompletionsOptions{ Messages: []azopenai.ChatMessage{ {Role: azopenai.ChatRoleUser, Content: input}, }, MaxTokens: 100, }, nil) if err != nil { fmt.Println("Error:", err) continue } fmt.Println("Bot:", resp.Choices[0].Message.Content) } }
Don't forget to test! Here's a quick example:
func TestGetCompletions(t *testing.T) { client, _ := azopenai.NewClient(os.Getenv("AZURE_OPENAI_ENDPOINT"), os.Getenv("AZURE_OPENAI_KEY"), nil) resp, err := client.GetCompletions(context.Background(), azopenai.CompletionsOptions{ Prompt: []string{"Hello"}, MaxTokens: 5, }, nil) assert.NoError(t, err) assert.NotEmpty(t, resp.Choices[0].Text) }
And there you have it! You've just built an Azure OpenAI Service integration in Go. Pretty cool, right? Remember, this is just scratching the surface. There's so much more you can do with this powerful API.
For more info, check out the Azure OpenAI Service docs and the azopenai package documentation.
Now go forth and build some awesome AI-powered Go applications! The sky's the limit. Happy coding!