Skip to content

wikylyu/gopenai

Repository files navigation

GOpenAI

GoDoc Go Report Card

Unofficial Go implemention for OpenAI API, adhering to their official OpenAPI spec.

GOpenAI provides their python-style like api. It's easy to understand and use.

  • openai.Completion.Create(...)
  • openai.Edit.Create(...)
  • ...

Usage

Create Completion

package main

import (
	"fmt"
	"os"

	"github.com/wikylyu/gopenai"
	"github.com/wikylyu/gopenai/completions"
	"github.com/wikylyu/gopenai/models"
)

func main() {
	openai := gopenai.New(&gopenai.Config{
		ApiKey: os.Getenv("OPENAI_API_KEY"),
	})

	prompt := []string{"Say this is a test"}
	resp, err := openai.Completion.Create(&completions.CreateRequest{
		Model:       models.ModelTextDavinci003,
		Prompt:      prompt,
		MaxTokens:   256,
		Temperature: 0,
	})
	if err != nil {
		panic(err)
	}
	for _, choice := range resp.Choices {
		fmt.Printf("%s\n", choice.Text)
	}
}

For more usages, see examples/ folder.

Error Handling

There're two kinds of errors that api method may return.

  1. OpenAI api error
  2. Network or general error

You can use following code to process errors.

resp,err:=openai.Completion.Create(...)
if err!=nil{
	if apierr:=err.(*api.Error);apierr!=nil{
		/* OpenAI api error, read apierr.Message or apierr.Type to determine exact error reason */
	}else {
		/* Network error */
	}
}

Command line tool

See tool/ folder for more details.

API List

  • Model

    • Create
    • Retrieve
    • Delete
  • Completion

    • Create
  • Chat

    • Create
  • Edit

    • Create
  • Images

    • Create
    • Edit
    • Variation
  • Embeddings

    • Create
  • Audio

    • Transcribe
    • Translate
  • Files

    • Create
    • Retrieve
    • Download
  • Fine-tunes

    • Create
    • Retrieve
    • List
    • Cancel
    • Events
  • Moderations

    • Create
  • Engines

Development

Engines is not going to be implemented, cause it's deprecated. Models is their replacement.