api

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: May 17, 2023 License: MIT Imports: 11 Imported by: 0

README

Prompt: please respond with only the code, no commentary: please write a readme for this package, including enviornment variales.

Response: $!FILENAME=README.md

OpenAI API Go Client

This is a Go client for the OpenAI API. It currently supports the following endpoints:

Usage

To use this client, you will need an OpenAI API key. You can sign up for an API key here.

Environment Variables

This client requires the following environment variables to be set:

  • OPENAI_API_KEY: Your OpenAI API key
Examples
Chat API
package main

import (
	"fmt"

	"github.com/openai/api-go"
)

func main() {
	response, err := api.AnalyzeCode(api.GPT4, "Hello, how are you?", "", 0.5)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(response.String())
}
Completion API
package main

import (
	"fmt"

	"github.com/openai/api-go"
)

func main() {
	cr := api.CompletionRequest{
		Model:       api.Davinci,
		Prompt:      "Hello, how are you?",
		MaxTokens:   10,
		Temperature: 0.5,
	}

	response, err := api.Complete(cr)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(response.Choices[0].Text)
}
Image API
package main

import (
	"fmt"

	"github.com/openai/api-go"
)

func main() {
	imageURLs, err := api.ImageGeneration("A painting of a cat", 1, api.ImageSize256)
	if err != nil {
		fmt.Println(err)
		return
	}

	fmt.Println(imageURLs[0])
}
Models API
package main

import (
	"fmt"

	"github.com/openai/api-go"
)

func main() {
	models, err := api.GetAvailableModels()
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, model := range models {
		fmt.Println(model.ID)
	}
}

Contributing

Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.

Please make sure to update tests as appropriate.

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DumpChatThread

func DumpChatThread(chatThread *ChatThread)

DumpChatThread is a function that archives the chat thread by marshalling it into json before writing it to a file

func ImageGeneration

func ImageGeneration(prompt string, n int, size ImageSizes) ([]string, error)

ImageGeneration is a function that generates images from a text prompt

func PromptForInput

func PromptForInput() (input string, breakLoop bool)

func SaveConversation

func SaveConversation(prompt string, context *ChatThread)

SaveConversation is a function that saves the conversation to a file

func StartConversation

func StartConversation()

StartConversation starts a conversation with the bot in a for loop reading from stdin and sending the input to the OpenAI Chat API.

The bot responds to the user's input with a response from the OpenAI Chat API and an ongoing conversation is saved to a ChatThread so it can be provided as context to the ongoing discussion.

Commands: - "save this conversation" saves the conversation to frybot_conversation.md - "exit" exits the conversation and saves the conversation to frybot_conversation.md when the user types "save this conversation"

Types

type APIError

type APIError struct {
	Message string `json:"message"`
	Type    string `json:"type"`
	Param   string `json:"param"`
	Code    string `json:"code"`
}

APIError is the response body for the OpenAI API when an error occurs

func (*APIError) Error

func (e *APIError) Error() string

satisfy the error interface

type ChatChoice

type ChatChoice struct {
	Index        int                 `json:"index"`
	Message      ChatMessageResponse `json:"message"`
	FinishReason string              `json:"finish_reason"`
}

type ChatMessage

type ChatMessage struct {
	Role    ChatRole `json:"role"`
	Content string   `json:"content"`
}

ChatMessage is a struct that represents a message in the OpenAI Chat API

func NewChatMessage

func NewChatMessage(role ChatRole, content string) ChatMessage

NewChatMessage is a function that returns a new ChatMessage

type ChatMessageResponse

type ChatMessageResponse struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type ChatResponse

type ChatResponse struct {
	Error   *APIError    `json:"error,omitempty"`
	ID      string       `json:"id"`
	Object  string       `json:"object"`
	Created int          `json:"created"`
	Choices []ChatChoice `json:"choices"`
	Usage   struct {
		PromptTokens     int `json:"prompt_tokens"`
		CompletionTokens int `json:"completion_tokens"`
		TotalTokens      int `json:"total_tokens"`
	} `json:"usage"`
}

func AnalyzeCode

func AnalyzeCode(model Models, prompt, context string, temp float32) (*ChatResponse, error)

AnalyzeCode is a function that completes a CompletionRequest

func SendChatRequest

func SendChatRequest(requestBody RequestBody) (*ChatResponse, error)

SendChatRequest is a function that sends a request to the OpenAI Chat API

func (ChatResponse) LogAPIResponse added in v0.0.2

func (cr ChatResponse) LogAPIResponse()

LogAPIResponse is a function that logs the entire API response

func (ChatResponse) String

func (cr ChatResponse) String() string

String is a function that returns the text of the first ChatChoice if an error occurs, it returns the error

type ChatRole

type ChatRole string

ChatRole is a string that represents the role of a message in the OpenAI Chat API

const (
	// RoleUser is the role of the user in the OpenAI Chat API
	RoleUser ChatRole = "user"
	// RoleSystem is the role of the system in the OpenAI Chat API
	RoleSystem ChatRole = "system"
	// RoleAssistant is the role of the assistant in the OpenAI Chat API
	RoleAssistant ChatRole = "assistant"
)

type ChatThread

type ChatThread []ChatMessage

ChatThread is a slice of ChatMessages with special helper functions

func RecoverChatThread

func RecoverChatThread(chat *ChatThread) *ChatThread

RecoverChatThread is a function that recovers the chat thread from a file

func (ChatThread) Add

func (ct ChatThread) Add(role ChatRole, message string) ChatThread

Add will add a new ChatMessage to the ChatThread

func (*ChatThread) MarshalJSON

func (ct *ChatThread) MarshalJSON() ([]byte, error)

MarshalJSON is a function that marshals the ChatThread into json

func (ChatThread) String

func (ct ChatThread) String() string

func (*ChatThread) UnmarshalJSON

func (ct *ChatThread) UnmarshalJSON(byteData []byte)

UnmarshalJSON is a function that unmarshals the ChatThread from json

type CompletionChoice

type CompletionChoice struct {
	Text         string          `json:"text"`
	Index        int             `json:"index"`
	Logprobs     any             `json:"logprobs"`
	FinishReason string          `json:"finish_reason"`
	Usage        CompletionUsage `json:"usage"`
}

CompletionChoice is the response body for the OpenAI Completion API

type CompletionRequest

type CompletionRequest struct {
	Model       string `json:"model"`
	Prompt      string `json:"prompt"`
	MaxTokens   int    `json:"max_tokens"`
	Temperature int    `json:"temperature"`
	TopP        int    `json:"top_p"`
	N           int    `json:"n"`
	Stream      bool   `json:"stream"`
	Logprobs    any    `json:"logprobs"`
	Stop        string `json:"stop"`
}

CompletionRequest is the request body for the OpenAI Completion API

type CompletionResponse

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

CompletionResponse is the response body for the OpenAI Completion API

func Complete

Complete is a function that completes a CompletionRequest

type CompletionUsage

type CompletionUsage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

CompletionUsage is part of the response body for the OpenAI Completion API

type EnvVars

type EnvVars struct {
	OpenAIAPIKey     string `env:"OPENAI_API_KEY,notEmpty"`
	ChatAPIURL       string `env:"CHAT_API_URL" envDefault:"https://api.openai.com/v1/chat/completions"`
	CompletionAPIURL string `env:"COMPLETION_API_URL" envDefault:"https://api.openai.com/v1/completions"`
	ImageAPIURL      string `env:"IMAGE_API_URL" envDefault:"https://api.openai.com/v1/images/generations"`
	ModelsAPIURL     string `env:"MODELS_API_URL" envDefault:"https://api.openai.com/v1/models"`
}

EnvVars is the struct for the environment variables used in this application

type ImageRequestBody

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

ImageRequestBody is the request body for the OpenAI Image Generation API

type ImageSizes

type ImageSizes string

ImageSizes is a type for the image sizes enum

const (
	// ImageSize256 256x256
	ImageSize256 ImageSizes = "256x256"
	// ImageSize512 512x512
	ImageSize512 ImageSizes = "512x512"
	// ImageSize1024 1024x1024
	ImageSize1024 ImageSizes = "1024x1024"
)

type Model

type Model struct {
	ID         string        `json:"id"`
	Object     string        `json:"object"`
	OwnedBy    string        `json:"owned_by"`
	Permission []interface{} `json:"permission"`
}

Model is a struct representing an individual model from the API

func GetAvailableModels

func GetAvailableModels() ([]Model, error)

GetAvailableModels is a function that retrieves the list of available models from the API

type ModelListResponse

type ModelListResponse struct {
	Data   []Model `json:"data"`
	Object string  `json:"object"`
}

ModelListResponse is a struct representing the list of models returned by the API

type Models

type Models string
const (
	// Davinci is a bit slower than gpt3.5 turbo but has a higher token limit of ~8k
	Davinci Models = "text-davinci-003"

	// GPT3Turbo is a reasonably new and cheap gpt model, but has a lower token limit of ~4k
	GPT3Turbo Models = "gpt-3.5-turbo"

	// GPT4 is the most expensive model, but has a token limit of ~8k and quality analysis
	GPT4 Models = "gpt-4"
)

type RequestBody

type RequestBody struct {
	Model       string        `json:"model"`
	Messages    []ChatMessage `json:"messages"`
	Temperature float32       `json:"temperature,omitempty"`
	MaxTokens   int           `json:"max_tokens,omitempty"`
}

RequestBody is the request body for the OpenAI Chat API

func NewRequestBody

func NewRequestBody(model Models, messages []ChatMessage, temperature float32) RequestBody

NewRequestBody is a function that returns the request body for the OpenAI Chat API

Jump to

Keyboard shortcuts

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