gogpt

package module
v0.0.0-...-2932b43 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2022 License: Apache-2.0 Imports: 11 Imported by: 0

README

go-gpt3

GoDoc Go Report Card

OpenAI GPT-3 API wrapper for Go

Installation:

go get github.com/sashabaranov/go-gpt3

Example usage:

package main

import (
	"context"
	"fmt"
	gogpt "github.com/sashabaranov/go-gpt3"
)

func main() {
	c := gogpt.NewClient("your token")
	ctx := context.Background()

	req := gogpt.CompletionRequest{
		MaxTokens: 5,
		Prompt:    "Lorem ipsum",
	}
	resp, err := c.CreateCompletion(ctx, "ada", req)
	if err != nil {
		return
	}
	fmt.Println(resp.Choices[0].Text)

	searchReq := gogpt.SearchRequest{
		Documents: []string{"White House", "hospital", "school"},
		Query:     "the president",
	}
	searchResp, err := c.Search(ctx, "ada", searchReq)
	if err != nil {
		return
	}
	fmt.Println(searchResp.SearchResults)
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AnswerRequest

type AnswerRequest struct {
	Documents       []string   `json:"documents,omitempty"`
	File            string     `json:"file,omitempty"`
	Question        string     `json:"question"`
	SearchModel     string     `json:"search_model,omitempty"`
	Model           string     `json:"model"`
	ExamplesContext string     `json:"examples_context"`
	Examples        [][]string `json:"examples"`
	MaxTokens       int        `json:"max_tokens,omitempty"`
	Stop            []string   `json:"stop,omitempty"`
	Temperature     *float64   `json:"temperature,omitempty"`
}

type AnswerResponse

type AnswerResponse struct {
	Answers           []string `json:"answers"`
	Completion        string   `json:"completion"`
	Model             string   `json:"model"`
	Object            string   `json:"object"`
	SearchModel       string   `json:"search_model"`
	SelectedDocuments []struct {
		Document int    `json:"document"`
		Text     string `json:"text"`
	} `json:"selected_documents"`
}

type Choice

type Choice struct {
	Text         string        `json:"text"`
	Index        int           `json:"index"`
	FinishReason string        `json:"finish_reason"`
	LogProbs     LogprobResult `json:"logprobs"`
}

Choice represents one of possible completions

type Client

type Client struct {
	BaseURL    string
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

Client is OpenAI GPT-3 API client

func NewClient

func NewClient(authToken string) *Client

NewClient creates new OpenAI API client

func NewOrgClient

func NewOrgClient(authToken, org string) *Client

NewOrgClient creates new OpenAI API client for specified Organization ID

func (*Client) Answers

func (c *Client) Answers(ctx context.Context, request AnswerRequest) (response AnswerResponse, err error)

Search — perform a semantic search api call over a list of documents.

func (*Client) CreateCompletion

func (c *Client) CreateCompletion(ctx context.Context, engineID string, request CompletionRequest) (response CompletionResponse, err error)

CreateCompletion — API call to create a completion. This is the main endpoint of the API. Returns new text as well as, if requested, the probabilities over each alternative token at each position.

func (*Client) CreateCompletionWithFineTunedModel

func (c *Client) CreateCompletionWithFineTunedModel(ctx context.Context, request CompletionRequest) (response CompletionResponse, err error)

CreateCompletionWithFineTunedModel - API call to create a completion with a fine tuned model See https://beta.openai.com/docs/guides/fine-tuning/use-a-fine-tuned-model In this case, the model is specified in the CompletionRequest object.

func (*Client) CreateEmbeddings

func (c *Client) CreateEmbeddings(ctx context.Context, request EmbeddingRequest, model EmbeddingModel) (resp EmbeddingResponse, err error)

CreateEmbeddings returns an EmbeddingResponse which will contain an Embedding for every item in |request.Input|. https://beta.openai.com/docs/api-reference/embeddings/create

func (*Client) CreateFile

func (c *Client) CreateFile(ctx context.Context, request FileRequest) (file File, err error)

CreateFile uploads a jsonl file to GPT3 FilePath can be either a local file path or a URL

func (*Client) DeleteFile

func (c *Client) DeleteFile(ctx context.Context, fileID string) (err error)

DeleteFile deletes an existing file

func (*Client) GetEngine

func (c *Client) GetEngine(ctx context.Context, engineID string) (engine Engine, err error)

GetEngine Retrieves an engine instance, providing basic information about the engine such as the owner and availability.

func (*Client) GetFile

func (c *Client) GetFile(ctx context.Context, fileID string) (file File, err error)

GetFile Retrieves a file instance, providing basic information about the file such as the file name and purpose.

func (*Client) ListEngines

func (c *Client) ListEngines(ctx context.Context) (engines EnginesList, err error)

ListEngines Lists the currently available engines, and provides basic information about each option such as the owner and availability.

func (*Client) ListFiles

func (c *Client) ListFiles(ctx context.Context) (files FilesList, err error)

ListFiles Lists the currently available files, and provides basic information about each file such as the file name and purpose.

func (*Client) Search

func (c *Client) Search(ctx context.Context, engineID string, request SearchRequest) (response SearchResponse, err error)

Search — perform a semantic search api call over a list of documents.

type CompletionRequest

type CompletionRequest struct {
	Prompt    string `json:"prompt,omitempty"`
	MaxTokens int    `json:"max_tokens,omitempty"`

	Temperature float32 `json:"temperature,omitempty"`
	TopP        float32 `json:"top_p,omitempty"`

	N int `json:"n,omitempty"`

	LogProbs int `json:"logprobs,omitempty"`

	Model *string `json:"model,omitempty"`

	Echo bool     `json:"echo,omitempty"`
	Stop []string `json:"stop,omitempty"`

	PresencePenalty  float32        `json:"presence_penalty,omitempty"`
	FrequencyPenalty float32        `json:"frequency_penalty,omitempty"`
	BestOf           int            `json:"best_of,omitempty"`
	LogitBias        map[string]int `json:"logit_bias,omitempty"`
}

CompletionRequest represents a request structure for completion API

type CompletionResponse

type CompletionResponse struct {
	ID      string   `json:"id"`
	Object  string   `json:"object"`
	Created uint64   `json:"created"`
	Model   string   `json:"model"`
	Choices []Choice `json:"choices"`
}

CompletionResponse represents a response structure for completion API

type Embedding

type Embedding struct {
	Object    string    `json:"object"`
	Embedding []float64 `json:"embedding"`
	Index     int       `json:"index"`
}

Embedding is a special format of data representation that can be easily utilized by machine learning models and algorithms. The embedding is an information dense representation of the semantic meaning of a piece of text. Each embedding is a vector of floating point numbers, such that the distance between two embeddings in the vector space is correlated with semantic similarity between two inputs in the original format. For example, if two texts are similar, then their vector representations should also be similar.

type EmbeddingModel

type EmbeddingModel int

EmbeddingModel enumerates the models which can be used to generate Embedding vectors.

const (
	Unknown EmbeddingModel = iota
	AdaSimilarity
	BabbageSimilarity
	CurieSimilarity
	DavinciSimilarity
	AdaSearchDocument
	AdaSearchQuery
	BabbageSearchDocument
	BabbageSearchQuery
	CurieSearchDocument
	CurieSearchQuery
	DavinciSearchDocument
	DavinciSearchQuery
	AdaCodeSearchCode
	AdaCodeSearchText
	BabbageCodeSearchCode
	BabbageCodeSearchText
)

func (EmbeddingModel) MarshalText

func (e EmbeddingModel) MarshalText() ([]byte, error)

MarshalText implements the encoding.TextMarshaler interface.

func (EmbeddingModel) String

func (e EmbeddingModel) String() string

String implements the fmt.Stringer interface.

func (*EmbeddingModel) UnmarshalText

func (e *EmbeddingModel) UnmarshalText(b []byte) error

UnmarshalText implements the encoding.TextUnmarshaler interface. On unrecognized value, it sets |e| to Unknown.

type EmbeddingRequest

type EmbeddingRequest struct {
	// Input is a slice of strings for which you want to generate an Embedding vector.
	// Each input must not exceed 2048 tokens in length.
	// OpenAPI suggests replacing newlines (\n) in your input with a single space, as they
	// have observed inferior results when newlines are present.
	// E.g.
	//	"The food was delicious and the waiter..."
	Input []string `json:"input"`
}

EmbeddingRequest is the input to a Create embeddings request.

type EmbeddingResponse

type EmbeddingResponse struct {
	Object string         `json:"object"`
	Data   []Embedding    `json:"data"`
	Model  EmbeddingModel `json:"model"`
}

EmbeddingResponse is the response from a Create embeddings request.

type Engine

type Engine struct {
	ID     string `json:"id"`
	Object string `json:"object"`
	Owner  string `json:"owner"`
	Ready  bool   `json:"ready"`
}

Engine struct represents engine from OpenAPI API

type EnginesList

type EnginesList struct {
	Engines []Engine `json:"data"`
}

EnginesList is a list of engines

type ErrorResponse

type ErrorResponse struct {
	Error *struct {
		Code    *int    `json:"code,omitempty"`
		Message string  `json:"message"`
		Param   *string `json:"param,omitempty"`
		Type    string  `json:"type"`
	} `json:"error,omitempty"`
}

type File

type File struct {
	Bytes     int    `json:"bytes"`
	CreatedAt int    `json:"created_at"`
	ID        string `json:"id"`
	FileName  string `json:"filename"`
	Object    string `json:"object"`
	Owner     string `json:"owner"`
	Purpose   string `json:"purpose"`
}

File struct represents an OpenAPI file

type FileRequest

type FileRequest struct {
	FileName string `json:"file"`
	FilePath string `json:"-"`
	Purpose  string `json:"purpose"`
}

type FilesList

type FilesList struct {
	Files []File `json:"data"`
}

FilesList is a list of files that belong to the user or organization

type LogprobResult

type LogprobResult struct {
	Tokens        []string             `json:"tokens"`
	TokenLogprobs []float32            `json:"token_logprobs"`
	TopLogprobs   []map[string]float32 `json:"top_logprobs"`
	TextOffset    []int                `json:"text_offset"`
}

LogprobResult represents logprob result of Choice

type SearchRequest

type SearchRequest struct {
	Documents []string `json:"documents"`
	Query     string   `json:"query"`
}

SearchRequest represents a request structure for search API

type SearchResponse

type SearchResponse struct {
	SearchResults []SearchResult `json:"data"`
}

SearchResponse represents a response structure for search API

type SearchResult

type SearchResult struct {
	Document int     `json:"document"`
	Score    float32 `json:"score"`
}

SearchResult represents single result from search API

Jump to

Keyboard shortcuts

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