Skip to content

Instantly share code, notes, and snippets.

@vdparikh
Last active April 25, 2023 17:42
Show Gist options
  • Save vdparikh/2da7c5229b106a07f3f84ea265c88dc3 to your computer and use it in GitHub Desktop.
Save vdparikh/2da7c5229b106a07f3f84ea265c88dc3 to your computer and use it in GitHub Desktop.
OpenAI API for completion
package main
import (
"fmt"
"net/http"
"bytes"
"io/ioutil"
)
func main() {
api_key := "YOUR_API_KEY"
url := "https://api.openai.com/v1/engines/davinci-codex/completions"
input := "Hello, I'm a computer program"
params := []byte(`{
"prompt": "` + input + `",
"temperature": 0.5,
"max_tokens": 100
}`)
req, err := http.NewRequest("POST", url, bytes.NewBuffer(params))
req.Header.Set("Authorization", "Bearer " + api_key)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error: ", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println(string(body))
}
package main
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
)
const (
openaiEndpoint = "https://api.openai.com/v1/engines/davinci-codex/completions"
slackEndpoint = "https://slack.com/api/chat.postMessage"
slackChannel = "#general"
)
var (
openaiApiKey = os.Getenv("OPENAI_API_KEY")
slackApiToken = os.Getenv("SLACK_API_TOKEN")
httpClient = &http.Client{}
)
type OpenAIRequest struct {
Prompt string `json:"prompt"`
Temperature float32 `json:"temperature"`
MaxTokens int `json:"max_tokens"`
}
type OpenAIResponse struct {
Choices []struct {
Text string `json:"text"`
} `json:"choices"`
}
type SlackRequest struct {
Channel string `json:"channel"`
Text string `json:"text"`
}
func main() {
openaiRequest := OpenAIRequest{
Prompt: "Write a function that calculates the factorial of a number in GoLang.",
Temperature: 0.7,
MaxTokens: 100,
}
openaiResponse, err := getOpenAIResponse(openaiRequest)
if err != nil {
fmt.Println("Error getting OpenAI response:", err)
return
}
slackRequest := SlackRequest{
Channel: slackChannel,
Text: openaiResponse.Choices[0].Text,
}
err = postSlackMessage(slackRequest)
if err != nil {
fmt.Println("Error posting Slack message:", err)
return
}
}
func getOpenAIResponse(request OpenAIRequest) (*OpenAIResponse, error) {
requestBody, err := json.Marshal(request)
if err != nil {
return nil, errors.New("Error marshaling OpenAI request")
}
req, err := http.NewRequest("POST", openaiEndpoint, bytes.NewBuffer(requestBody))
if err != nil {
return nil, errors.New("Error creating OpenAI request")
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+openaiApiKey)
resp, err := httpClient.Do(req)
if err != nil {
return nil, errors.New("Error sending OpenAI request")
}
defer resp.Body.Close()
var openaiResponse OpenAIResponse
err = json.NewDecoder(resp.Body).Decode(&openaiResponse)
if err != nil {
return nil, errors.New("Error decoding OpenAI response")
}
return &openaiResponse, nil
}
func postSlackMessage(request SlackRequest) error {
requestBody, err := json.Marshal(request)
if err != nil {
return errors.New("Error marshaling Slack request")
}
req, err := http.NewRequest("POST", slackEndpoint, bytes.NewBuffer(requestBody))
if err != nil {
fmt.Println("Error creating Slack request:", err)
return
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer "+os.Getenv("SLACK_API_TOKEN"))
// Send Slack API request
resp, err = httpClient.Do(req)
if err != nil {
fmt.Println("Error sending Slack request:", err)
return errors.New("Error sending Slack request")
}
defer resp.Body.Close()
return nil
}
@vdparikh
Copy link
Author

You can also use the package created by OpenAI

go get github.com/openai/openai-go

and then use it

import (
    "github.com/openai/openai-go/v1"
)

client := openai.NewClient("<your api key>")
req := &openai.CompletionRequest{
    Prompt: "Hello, my name is",
    Model:  "text-davinci-002",
}

resp, err := client.Completions(req)
if err != nil {
    panic(err)
}

for _, choice := range resp.Choices {
    fmt.Println(choice.Text)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment