Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Using OpenAI API with Go

Introduction

This tutorial demonstrates how to integrate and use the OpenAI API with Go to leverage advanced AI capabilities in your applications.

1. Setting Up Your OpenAI API Key

Before starting, make sure you have your OpenAI API key ready. You can obtain it from the OpenAI website after signing up for an account.

2. Making API Requests

To make requests to the OpenAI API using Go, you'll use Go's built-in HTTP client.

Text Completion

Here’s an example of making a request for text completion:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

func main() {
	apiKey := "YOUR_API_KEY_HERE"
	url := "https://api.openai.com/v1/completions"
	data := map[string]interface{}{
		"prompt":     "Translate English to French: Hello, how are you?",
		"max_tokens": 50,
	}

	payload, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		fmt.Println("Error decoding JSON response:", err)
		return
	}

	fmt.Println("<div class=\"output\"><pre>", result, "</pre></div>")
}
                    

Output: Bonjour, comment vas-tu ?

This Go program sends a POST request to the OpenAI API for text completion and prints the API response.

Code Generation

Here’s an example of making a request for code generation:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"net/http"
)

func main() {
	apiKey := "YOUR_API_KEY_HERE"
	url := "https://api.openai.com/v1/engines/davinci-codex/completions"
	data := map[string]interface{}{
		"prompt":     "Generate Python code to sort an array using bubble sort",
		"max_tokens": 150,
		"stop":       []string{"\n"},
	}

	payload, err := json.Marshal(data)
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(payload))
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+apiKey)

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error making request:", err)
		return
	}
	defer resp.Body.Close()

	var result map[string]interface{}
	err = json.NewDecoder(resp.Body).Decode(&result)
	if err != nil {
		fmt.Println("Error decoding JSON response:", err)
		return
	}

	fmt.Println("<div class=\"output\"><pre>", result, "</pre></div>")
}
                    

Output:

def sort_list(list):
    list.sort()
    return list

my_list = [3, 1, 4, 2]
print(sort_list(my_list))
                    

This Go program sends a POST request to the OpenAI Codex engine for code generation and prints the generated code.

3. Handling Responses

Once you receive a response from the API, you can handle it in your Go code.

Text Completion

Here’s how you might handle the completion response:

// Assuming result contains the API response
fmt.Println("<div class=\"output\"><pre>", result, "</pre></div>")
                    

In this example, result contains the JSON response from the OpenAI API.

Code Generation

Here’s how you might handle the code generation response:

// Assuming result contains the API response
fmt.Println("<div class=\"output\"><pre>", result, "</pre></div>")
                    

In this example, result contains the JSON response from the OpenAI API with the generated code.

Conclusion

Integrating the OpenAI API with Go enables you to enhance your applications with powerful AI capabilities. Explore more API endpoints and functionalities to innovate further.