goopenai

package module
v0.18.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 9, 2023 License: MIT Imports: 8 Imported by: 0

README

Go OpenAI

This is a Go client library for the OpenAI API.

It implements the methods described in the docs: https://platform.openai.com/docs/api-reference/introduction

Implemented methods can be found in the Interface.go file.

Installation

go get github.com/mashley/goopenai

Usage

First, you need to create a client with the api key and organization id.

client := goopenai.NewClient(apiKey, organization)

Then, you can use the client to call the api.

Example:

package main

import (
	"context"
	"fmt"
	"github.com/mashley/goopenai"
)

func main() {
	apiKey := os.Getenv("API_KEY")
	organization := os.Getenv("API_ORG")

	client := goopenai.NewClient(apiKey, organization)

	r := goopenai.CreateCompletionsRequest{
		Model: "gpt-3.5-turbo",
		Messages: []goopenai.Message{
			{
				Role:    "user",
				Content: "Say this is a test!",
			},
		},
		Temperature: 0.7,
	}

	completions, err := client.CreateCompletions(context.Background(), r)
	if err != nil {
		panic(err)
	}

	fmt.Println(completions)
}

Run this code using:

API_KEY=<your-api-key> API_ORG=<your-org-id> go run .

Note

This library is not complete and not fully tested.

Feel free to contribute.

Documentation

Index

Constants

View Source
const CHATS_URL = "https://api.openai.com/v1/chat/completions"
View Source
const COMPLETIONS_URL = "https://api.openai.com/v1/chat/completions"
View Source
const EDITS_URL = "https://api.openai.com/v1/edits"
View Source
const EMBEDDINGS_URL = "https://api.openai.com/v1/embeddings"
View Source
const IMAGES_EDITS_URL = "https://api.openai.com/v1/images/edits"
View Source
const IMAGES_URL = "https://api.openai.com/v1/images/generations"
View Source
const IMAGES_VARIATIONS_URL = "https://api.openai.com/v1/images/variations"
View Source
const MODELS_URL = "https://api.openai.com/v1/models"
View Source
const MODEL_URL = "https://api.openai.com/v1/models/"
View Source
const MODERATIONS_URL = "https://api.openai.com/v1/moderations"
View Source
const TRANSCRIPTIONS_URL = "https://api.openai.com/v1/audio/transcriptions"
View Source
const TRANSLATIONS_URL = "https://api.openai.com/v1/audio/translations"

Variables

View Source
var ErrStrArrayUnsupportedType = errors.New("unsupported type, must be string or []string")

Functions

This section is empty.

Types

type Client

type Client struct {
	Organization string
	// contains filtered or unexported fields
}

func NewClient

func NewClient(apiKey string, organization string) *Client

NewClient creates a new client

func (*Client) Call

func (c *Client) Call(ctx context.Context, method string, url string, body io.Reader) (response *http.Response, err error)

Call makes a request

func (*Client) CreateChats

func (c *Client) CreateChats(ctx context.Context, r CreateChatsRequest) (response CreateChatsResponse, err error)

func (*Client) CreateChatsRaw

func (c *Client) CreateChatsRaw(ctx context.Context, r CreateChatsRequest) ([]byte, error)

func (*Client) CreateCompletions

func (c *Client) CreateCompletions(ctx context.Context, r CreateCompletionsRequest) (response CreateCompletionsResponse, err error)

func (*Client) CreateCompletionsRaw

func (c *Client) CreateCompletionsRaw(ctx context.Context, r CreateCompletionsRequest) ([]byte, error)

func (*Client) CreateEdits

func (c *Client) CreateEdits(ctx context.Context, r CreateEditsRequest) (response CreateEditsResponse, err error)

func (*Client) CreateEditsRaw

func (c *Client) CreateEditsRaw(ctx context.Context, r CreateEditsRequest) ([]byte, error)

func (*Client) CreateEmbeddings

func (c *Client) CreateEmbeddings(ctx context.Context, r CreateEmbeddingsRequest) (response CreateEmbeddingsResponse, err error)

func (*Client) CreateEmbeddingsRaw

func (c *Client) CreateEmbeddingsRaw(ctx context.Context, r CreateEmbeddingsRequest) ([]byte, error)

func (*Client) CreateImages

func (c *Client) CreateImages(ctx context.Context, r CreateImagesRequest) (response CreateImagesResponse, err error)

func (*Client) CreateImagesEdits

func (c *Client) CreateImagesEdits(ctx context.Context, r CreateImagesEditsRequest) (response CreateImagesEditsResponse, err error)

func (*Client) CreateImagesEditsRaw

func (c *Client) CreateImagesEditsRaw(ctx context.Context, r CreateImagesEditsRequest) ([]byte, error)

func (*Client) CreateImagesRaw

func (c *Client) CreateImagesRaw(ctx context.Context, r CreateImagesRequest) ([]byte, error)

func (*Client) CreateImagesVariations

func (c *Client) CreateImagesVariations(ctx context.Context, r CreateImagesVariationsRequest) (response CreateImagesVariationsResponse, err error)

func (*Client) CreateImagesVariationsRaw

func (c *Client) CreateImagesVariationsRaw(ctx context.Context, r CreateImagesVariationsRequest) ([]byte, error)

func (*Client) CreateModerations

func (c *Client) CreateModerations(ctx context.Context, r CreateModerationsRequest) (response CreateModerationsResponse, err error)

func (*Client) CreateModerationsRaw

func (c *Client) CreateModerationsRaw(ctx context.Context, r CreateModerationsRequest) ([]byte, error)

func (*Client) CreateTranscriptions

func (c *Client) CreateTranscriptions(ctx context.Context, r CreateTranscriptionsRequest) (response CreateTranscriptionsResponse, err error)

func (*Client) CreateTranscriptionsRaw

func (c *Client) CreateTranscriptionsRaw(ctx context.Context, r CreateTranscriptionsRequest) ([]byte, error)

func (*Client) CreateTranslations

func (c *Client) CreateTranslations(ctx context.Context, r CreateTranslationsRequest) (response CreateTranslationsResponse, err error)

func (*Client) CreateTranslationsRaw

func (c *Client) CreateTranslationsRaw(ctx context.Context, r CreateTranslationsRequest) ([]byte, error)

func (*Client) Get

func (c *Client) Get(ctx context.Context, url string, input any) (response []byte, err error)

Get makes a get request

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) (response ListModelsResponse, err error)

func (*Client) ListModelsRaw

func (c *Client) ListModelsRaw(ctx context.Context) ([]byte, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, url string, input any) (response []byte, err error)

Post makes a post request

func (*Client) RetrieveModel

func (c *Client) RetrieveModel(ctx context.Context, id string) (response RetrieveModelResponse, err error)

func (*Client) RetrieveModelRaw

func (c *Client) RetrieveModelRaw(ctx context.Context, id string) ([]byte, error)

type ClientInterface

type ClientInterface interface {
	// ListModels Lists the currently available models, and provides basic information about each one such as the owner and availability.
	ListModels(ctx context.Context) (response ListModelsResponse, err error)

	// RetrieveModel Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
	RetrieveModel(ctx context.Context, id string) (response RetrieveModelResponse, err error)

	// CreateCompletions Creates a completion for the provided prompt and parameters
	CreateCompletions(ctx context.Context, r CreateCompletionsRequest) (response CreateCompletionsResponse, err error)

	// CreateChats Creates a completion for the chat message
	CreateChats(ctx context.Context, r CreateChatsRequest) (response CreateChatsResponse, err error)

	// CreateEdits Creates a new edit for the provided input, instruction, and parameters.
	CreateEdits(ctx context.Context, r CreateEditsRequest) (response CreateEditsResponse, err error)

	// CreateImages Creates an image given a prompt.
	CreateImages(ctx context.Context, r CreateImagesRequest) (response CreateImagesResponse, err error)

	// CreateImagesEdits Creates an edited or extended image given an original image and a prompt.
	CreateImagesEdits(ctx context.Context, r CreateImagesEditsRequest) (response CreateImagesEditsResponse, err error)

	// CreateImagesVariations Creates a variation of a given image.
	CreateImagesVariations(ctx context.Context, r CreateImagesVariationsRequest) (response CreateImagesVariationsResponse, err error)

	// CreateEmbeddings Creates an embedding vector representing the input text.
	CreateEmbeddings(ctx context.Context, r CreateEmbeddingsRequest) (response CreateEmbeddingsResponse, err error)

	// CreateTranscriptions Transcribes audio into the input language.
	CreateTranscriptions(ctx context.Context, r CreateTranscriptionsRequest) (response CreateTranscriptionsResponse, err error)

	// CreateTranslations Translates audio into into English.
	CreateTranslations(ctx context.Context, r CreateTranslationsRequest) (response CreateTranslationsResponse, err error)

	// CreateModerations Classifies if text violates OpenAI's Content Policy
	CreateModerations(ctx context.Context, r CreateModerationsRequest) (response CreateModerationsResponse, err error)
}

ClientInterface is the interface for the OpenAI API client. Documentation at https://platform.openai.com/docs/api-reference/introduction

type CreateChatsRequest

type CreateChatsRequest struct {
	Model            string            `json:"model,omitempty"`
	Messages         []Message         `json:"messages,omitempty"`
	Temperature      float64           `json:"temperature,omitempty"`
	TopP             float64           `json:"top_p,omitempty"`
	N                int               `json:"n,omitempty"`
	Stream           bool              `json:"stream,omitempty"`
	Stop             StrArray          `json:"stop,omitempty"`
	MaxTokens        int               `json:"max_tokens,omitempty"`
	PresencePenalty  float64           `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64           `json:"frequency_penalty,omitempty"`
	LogitBias        map[string]string `json:"logit_bias,omitempty"`
	User             string            `json:"user,omitempty"`
}

type CreateChatsResponse

type CreateChatsResponse struct {
	ID      string `json:"id,omitempty"`
	Object  string `json:"object,omitempty"`
	Created int    `json:"created,omitempty"`
	Choices []struct {
		Index   int `json:"index,omitempty"`
		Message struct {
			Role    string `json:"role,omitempty"`
			Content string `json:"content,omitempty"`
		} `json:"message"`
		FinishReason string `json:"finish_reason,omitempty"`
	} `json:"choices,omitempty"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens,omitempty"`
		CompletionTokens int `json:"completion_tokens,omitempty"`
		TotalTokens      int `json:"total_tokens,omitempty"`
	} `json:"usage,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateCompletionsRequest

type CreateCompletionsRequest struct {
	Model            string            `json:"model,omitempty"`
	Messages         []Message         `json:"messages,omitempty"`
	Prompt           StrArray          `json:"prompt,omitempty"`
	Suffix           string            `json:"suffix,omitempty"`
	MaxTokens        int               `json:"max_tokens,omitempty"`
	Temperature      float64           `json:"temperature,omitempty"`
	TopP             float64           `json:"top_p,omitempty"`
	N                int               `json:"n,omitempty"`
	Stream           bool              `json:"stream,omitempty"`
	LogProbs         int               `json:"logprobs,omitempty"`
	Echo             bool              `json:"echo,omitempty"`
	Stop             StrArray          `json:"stop,omitempty"`
	PresencePenalty  float64           `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64           `json:"frequency_penalty,omitempty"`
	BestOf           int               `json:"best_of,omitempty"`
	LogitBias        map[string]string `json:"logit_bias,omitempty"`
	User             string            `json:"user,omitempty"`
}

type CreateCompletionsResponse

type CreateCompletionsResponse struct {
	ID      string `json:"id,omitempty"`
	Object  string `json:"object,omitempty"`
	Created int    `json:"created,omitempty"`
	Model   string `json:"model,omitempty"`
	Choices []struct {
		Message struct {
			Role    string `json:"role,omitempty"`
			Content string `json:"content,omitempty"`
		} `json:"message"`
		Text         string      `json:"text,omitempty"`
		Index        int         `json:"index,omitempty"`
		Logprobs     interface{} `json:"logprobs,omitempty"`
		FinishReason string      `json:"finish_reason,omitempty"`
	} `json:"choices,omitempty"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens,omitempty"`
		CompletionTokens int `json:"completion_tokens,omitempty"`
		TotalTokens      int `json:"total_tokens,omitempty"`
	} `json:"usage,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateEditsRequest

type CreateEditsRequest struct {
	Model       string  `json:"model,omitempty"`
	Input       string  `json:"input,omitempty"`
	Instruction string  `json:"instruction,omitempty"`
	N           int     `json:"n,omitempty"`
	Temperature float64 `json:"temperature,omitempty"`
	TopP        float64 `json:"top_p,omitempty"`
}

type CreateEditsResponse

type CreateEditsResponse struct {
	Object  string `json:"object,omitempty"`
	Created int    `json:"created,omitempty"`
	Choices []struct {
		Text  string `json:"text,omitempty"`
		Index int    `json:"index,omitempty"`
	} `json:"choices,omitempty"`
	Usage struct {
		PromptTokens     int `json:"prompt_tokens,omitempty"`
		CompletionTokens int `json:"completion_tokens,omitempty"`
		TotalTokens      int `json:"total_tokens,omitempty"`
	} `json:"usage,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateEmbeddingsRequest

type CreateEmbeddingsRequest struct {
	Model string   `json:"model,omitempty"`
	Input StrArray `json:"input,omitempty"`
	User  string   `json:"user,omitempty"`
}

type CreateEmbeddingsResponse

type CreateEmbeddingsResponse struct {
	Object string `json:"object,omitempty"`
	Data   []struct {
		Object    string    `json:"object,omitempty"`
		Embedding []float64 `json:"embedding,omitempty"`
		Index     int       `json:"index,omitempty"`
	} `json:"data,omitempty"`
	Model string `json:"model,omitempty"`
	Usage struct {
		PromptTokens int `json:"prompt_tokens,omitempty"`
		TotalTokens  int `json:"total_tokens,omitempty"`
	} `json:"usage,omitempty"`

	Error Error `json:"error"`
}

type CreateImagesEditsRequest

type CreateImagesEditsRequest struct {
	Image          string `json:"image,omitempty"`
	Mask           string `json:"mask,omitempty"`
	Prompt         string `json:"prompt,omitempty"`
	N              int    `json:"n,omitempty"`
	Size           string `json:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"`
	User           string `json:"user,omitempty"`
}

type CreateImagesEditsResponse

type CreateImagesEditsResponse struct {
	Created int `json:"created,omitempty"`
	Data    []struct {
		URL string `json:"url,omitempty"`
	} `json:"data,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateImagesRequest

type CreateImagesRequest struct {
	Prompt         string `json:"prompt,omitempty"`
	N              int    `json:"n,omitempty"`
	Size           string `json:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"`
	User           string `json:"user,omitempty"`
}

type CreateImagesResponse

type CreateImagesResponse struct {
	Created int `json:"created,omitempty"`
	Data    []struct {
		URL string `json:"url,omitempty"`
	} `json:"data,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateImagesVariationsRequest

type CreateImagesVariationsRequest struct {
	Image          string `json:"image,omitempty"`
	N              int    `json:"n,omitempty"`
	Size           string `json:"size,omitempty"`
	ResponseFormat string `json:"response_format,omitempty"`
	User           string `json:"user,omitempty"`
}

type CreateImagesVariationsResponse

type CreateImagesVariationsResponse struct {
	Created int `json:"created,omitempty"`
	Data    []struct {
		URL string `json:"url,omitempty"`
	} `json:"data,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateModerationsRequest

type CreateModerationsRequest struct {
	Input StrArray `json:"input,omitempty"`
	Model string   `json:"model,omitempty"`
}

type CreateModerationsResponse

type CreateModerationsResponse struct {
	ID      string `json:"id,omitempty"`
	Model   string `json:"model,omitempty"`
	Results []struct {
		Categories struct {
			Hate            bool `json:"hate,omitempty"`
			HateThreatening bool `json:"hate/threatening,omitempty"`
			SelfHarm        bool `json:"self-harm,omitempty"`
			Sexual          bool `json:"sexual,omitempty"`
			SexualMinors    bool `json:"sexual/minors,omitempty"`
			Violence        bool `json:"violence,omitempty"`
			ViolenceGraphic bool `json:"violence/graphic,omitempty"`
		} `json:"categories,omitempty"`
		CategoryScores struct {
			Hate            float64 `json:"hate,omitempty"`
			HateThreatening float64 `json:"hate/threatening,omitempty"`
			SelfHarm        float64 `json:"self-harm,omitempty"`
			Sexual          float64 `json:"sexual,omitempty"`
			SexualMinors    float64 `json:"sexual/minors,omitempty"`
			Violence        float64 `json:"violence,omitempty"`
			ViolenceGraphic float64 `json:"violence/graphic,omitempty"`
		} `json:"category_scores,omitempty"`
		Flagged bool `json:"flagged,omitempty"`
	} `json:"results,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateTranscriptionsRequest

type CreateTranscriptionsRequest struct {
	File           string  `json:"file,omitempty"`
	Model          string  `json:"model,omitempty"`
	Prompt         string  `json:"prompt,omitempty"`
	ResponseFormat string  `json:"response_format,omitempty"`
	Temperature    float64 `json:"temperature,omitempty"`
	Language       string  `json:"language,omitempty"`
}

type CreateTranscriptionsResponse

type CreateTranscriptionsResponse struct {
	Text string `json:"text,omitempty"`

	Error Error `json:"error,omitempty"`
}

type CreateTranslationsRequest

type CreateTranslationsRequest struct {
	File           string  `json:"file,omitempty"`
	Model          string  `json:"model,omitempty"`
	Prompt         string  `json:"prompt,omitempty"`
	ResponseFormat string  `json:"response_format,omitempty"`
	Temperature    float64 `json:"temperature,omitempty"`
}

type CreateTranslationsResponse

type CreateTranslationsResponse struct {
	Text string `json:"text,omitempty"`

	Error Error `json:"error,omitempty"`
}

type Error

type Error struct {
	Message string      `json:"message,omitempty"`
	Type    string      `json:"type,omitempty"`
	Param   interface{} `json:"param,omitempty"`
	Code    interface{} `json:"code,omitempty"`
}

Error is the error standard response from the API

type ListModelsResponse

type ListModelsResponse struct {
	Data []struct {
		ID          string   `json:"id,omitempty"`
		Object      string   `json:"object,omitempty"`
		OwnedBy     string   `json:"owned_by,omitempty"`
		Permissions []string `json:"permissions,omitempty"`
	} `json:"data,omitempty"`
	Object string `json:"object,omitempty"`

	Error Error `json:"error,omitempty"`
}

type Message

type Message struct {
	Role    string `json:"role,omitempty"`
	Content string `json:"content,omitempty"`
}

type RetrieveModelResponse

type RetrieveModelResponse struct {
	ID          string   `json:"id,omitempty"`
	Object      string   `json:"object,omitempty"`
	OwnedBy     string   `json:"owned_by,omitempty"`
	Permissions []string `json:"permissions,omitempty"`

	Error Error `json:"error,omitempty"`
}

type StrArray

type StrArray []string

func (*StrArray) UnmarshalJSON

func (sa *StrArray) UnmarshalJSON(data []byte) error

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL