Skip to content

Instantly share code, notes, and snippets.

@arturo-source
Created February 26, 2024 09:50
Show Gist options
  • Save arturo-source/6e2f99d31e83d2789091632caff0ac3b to your computer and use it in GitHub Desktop.
Save arturo-source/6e2f99d31e83d2789091632caff0ac3b to your computer and use it in GitHub Desktop.
How to access to OpenAI API with Golang
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
type OpenAIRequest struct {
Model string `json:"model"`
Messages []Message `json:"messages"`
Temperature float64 `json:"temperature"`
}
type Message struct {
Role string `json:"role"`
Content string `json:"content"`
}
type OpenAIResponse struct {
ID string `json:"id"`
Object string `json:"object"`
Created int `json:"created"`
Model string `json:"model"`
Usage struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
TotalTokens int `json:"total_tokens"`
} `json:"usage"`
Choices []struct {
Message Message `json:"message"`
Logprobs any `json:"logprobs"`
FinishReason string `json:"finish_reason"`
Index int `json:"index"`
} `json:"choices"`
Error Error `json:"error"`
}
type Error struct {
Message string `json:"message"`
Type string `json:"type"`
Param any `json:"param"`
Code any `json:"code"`
}
func callOpenAI(data OpenAIRequest) (OpenAIResponse, error) {
// Generated by curl-to-Go: https://mholt.github.io/curl-to-go
// curl https://api.openai.com/v1/chat/completions \
// -H "Content-Type: application/json" \
// -H "Authorization: Bearer $OPENAI_API_KEY" \
// -d '{
// "model": "gpt-3.5-turbo",
// "messages": [{"role": "user", "content": "Say this is a test!"}],
// "temperature": 0.7
// }'
payloadBytes, err := json.Marshal(data)
if err != nil {
return OpenAIResponse{}, err
}
body := bytes.NewReader(payloadBytes)
req, err := http.NewRequest("POST", "https://api.openai.com/v1/chat/completions", body)
if err != nil {
return OpenAIResponse{}, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", os.ExpandEnv("Bearer $OPENAI_API_KEY"))
resp, err := http.DefaultClient.Do(req)
if err != nil {
return OpenAIResponse{}, err
}
defer resp.Body.Close()
var iaResp OpenAIResponse
err = json.NewDecoder(resp.Body).Decode(&iaResp)
return iaResp, err
}
func main() {
data := OpenAIRequest{
Model: "gpt-3.5-turbo",
Messages: []Message{{Role: "user", Content: "Say this is a test!"}},
Temperature: 0.7,
}
resp, err := callOpenAI(data)
if err != nil {
panic(err)
}
fmt.Printf("%+v\n", resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment