openaiclient

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2023 License: Apache-2.0 Imports: 29 Imported by: 0

README

OpenAI Golang SDK Go Reference

This is an unofficial Golang SDK for the OpenAI API. It provides a simple and easy-to-use way to interact with the OpenAI API using Golang.

Installation

To install the OpenAI Golang SDK, simply run:

go get github.com/gopenai/openai-client

Usage

The OpenAI Golang SDK can be easily generated using a _oas/schema.yaml file that defines specification for the OpenAI API. To generate the SDK, project uses the ogen tool, which is a code generator for OpenAPI specifications. This allows you to easily update the SDK as the OpenAI API changes. If you change schema and want to generate sdk you can run the following command in makefile:

make generate

To use the OpenAI Golang SDK, you will need to have an API key for the OpenAI API. You can obtain an API key by creating an account on the OpenAI website.

Once you have your API key, you can create a new OpenAI client and start making requests to the API. Here's an example:

package main

import (
	"context"
	"fmt"

	openai "github.com/gopenai/openai-client"
)

func main() {
	// Replace SERVER_URL with your actual SERVER_URL key
	client, err := openai.NewClient("SERVER_URL")
	if err != nil {
		panic(err)
	}

	// Generate a text completion
	prompt := "Once upon a time,"
	req := &openai.CreateChatCompletionRequest{
		Model: "gpt-3.5-turbo",
		Messages: []openai.ChatCompletionRequestMessage{
			{
				Role:    openai.ChatCompletionRequestMessageRoleUser,
				Content: prompt,
			},
		},
	}
	response, err := client.CreateChatCompletion(context.Background(), req)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Print the completed text
	fmt.Println(response.Choices[0].Message.Value.Content)
}


This example generates a text completion using the OpenAI API, based on a prompt of "Once upon a time,". The resulting completed text is printed to the console.

You can also use bearer token auth. Here's an example:

package main

import (
	"context"
	"fmt"
	"os"

	openai "github.com/gopenai/openai-client"
)

func main() {
	// Replace SERVER_URL and API_TOKEN with your actual SERVER_URL and API_TOKEN values
	client, err := openai.NewBearerAuthClient(os.Getenv("SERVER_URL"), os.Getenv("API_TOKEN"))
	if err != nil {
		panic(err)
	}

	// Generate a text completion
	prompt := "Introduce himself please"
	req := &openai.CreateChatCompletionRequest{
		Model: "gpt-3.5-turbo",
		Messages: []openai.ChatCompletionRequestMessage{
			{
				Role:    openai.ChatCompletionRequestMessageRoleUser,
				Content: prompt,
			},
		},
	}
	response, err := client.CreateChatCompletion(context.Background(), req)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	// Print the completed text
	fmt.Println(response.Choices[0].Message.Value.Content)
}

Contributing

This SDK is open source, and contributions are welcome! If you have any bug reports, feature requests, or patches, please submit them through the GitHub issue tracker and pull request system.

Licence

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewBearerAuthClient

func NewBearerAuthClient(serverURL, token string) (*bearerAuthClient, error)

NewBearerAuthClient creates new client ready for doing requests with bearer token.

func WithServerURL

func WithServerURL(ctx context.Context, u *url.URL) context.Context

WithServerURL sets context key to override server URL.

Types

type CancelFineTuneParams

type CancelFineTuneParams struct {
	// The ID of the fine-tune job to cancel.
	FineTuneID string
}

CancelFineTuneParams is parameters of cancelFineTune operation.

type ChatCompletionRequestMessage

type ChatCompletionRequestMessage struct {
	// The role of the author of this message.
	Role ChatCompletionRequestMessageRole `json:"role"`
	// The contents of the message.
	Content string `json:"content"`
	// The name of the user in a multi-user chat.
	Name OptString `json:"name"`
}

Ref: #/components/schemas/ChatCompletionRequestMessage

func (*ChatCompletionRequestMessage) Decode

Decode decodes ChatCompletionRequestMessage from json.

func (*ChatCompletionRequestMessage) Encode

func (s *ChatCompletionRequestMessage) Encode(e *jx.Encoder)

Encode implements json.Marshaler.

func (*ChatCompletionRequestMessage) GetContent

func (s *ChatCompletionRequestMessage) GetContent() string

GetContent returns the value of Content.

func (*ChatCompletionRequestMessage) GetName

GetName returns the value of Name.

func (*ChatCompletionRequestMessage) GetRole

GetRole returns the value of Role.

func (*ChatCompletionRequestMessage) MarshalJSON

func (s *ChatCompletionRequestMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements stdjson.Marshaler.

func (*ChatCompletionRequestMessage) SetContent

func (s *ChatCompletionRequestMessage) SetContent(val string)

SetContent sets the value of Content.

func (*ChatCompletionRequestMessage) SetName

func (s *ChatCompletionRequestMessage) SetName(val OptString)

SetName sets the value of Name.

func (*ChatCompletionRequestMessage) SetRole

SetRole sets the value of Role.

func (*ChatCompletionRequestMessage) UnmarshalJSON

func (s *ChatCompletionRequestMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements stdjson.Unmarshaler.

func (*ChatCompletionRequestMessage) Validate

func (s *ChatCompletionRequestMessage) Validate() error

type ChatCompletionRequestMessageRole

type ChatCompletionRequestMessageRole string

The role of the author of this message.

const (
	ChatCompletionRequestMessageRoleSystem    ChatCompletionRequestMessageRole = "system"
	ChatCompletionRequestMessageRoleUser      ChatCompletionRequestMessageRole = "user"
	ChatCompletionRequestMessageRoleAssistant ChatCompletionRequestMessageRole = "assistant"
)

func (*ChatCompletionRequestMessageRole) Decode

Decode decodes ChatCompletionRequestMessageRole from json.

func (ChatCompletionRequestMessageRole) Encode

Encode encodes ChatCompletionRequestMessageRole as json.

func (ChatCompletionRequestMessageRole) MarshalJSON

func (s ChatCompletionRequestMessageRole) MarshalJSON() ([]byte, error)

MarshalJSON implements stdjson.Marshaler.

func (ChatCompletionRequestMessageRole) MarshalText

func (s ChatCompletionRequestMessageRole) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*ChatCompletionRequestMessageRole) UnmarshalJSON

func (s *ChatCompletionRequestMessageRole) UnmarshalJSON(data []byte) error

UnmarshalJSON implements stdjson.Unmarshaler.

func (*ChatCompletionRequestMessageRole) UnmarshalText

func (s *ChatCompletionRequestMessageRole) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (ChatCompletionRequestMessageRole) Validate

type ChatCompletionResponseMessage

type ChatCompletionResponseMessage struct {
	// The role of the author of this message.
	Role ChatCompletionResponseMessageRole `json:"role"`
	// The contents of the message.
	Content string `json:"content"`
}

Ref: #/components/schemas/ChatCompletionResponseMessage

func (*ChatCompletionResponseMessage) Decode

Decode decodes ChatCompletionResponseMessage from json.

func (*ChatCompletionResponseMessage) Encode

Encode implements json.Marshaler.

func (*ChatCompletionResponseMessage) GetContent

func (s *ChatCompletionResponseMessage) GetContent() string

GetContent returns the value of Content.

func (*ChatCompletionResponseMessage) GetRole

GetRole returns the value of Role.

func (*ChatCompletionResponseMessage) MarshalJSON

func (s *ChatCompletionResponseMessage) MarshalJSON() ([]byte, error)

MarshalJSON implements stdjson.Marshaler.

func (*ChatCompletionResponseMessage) SetContent

func (s *ChatCompletionResponseMessage) SetContent(val string)

SetContent sets the value of Content.

func (*ChatCompletionResponseMessage) SetRole

SetRole sets the value of Role.

func (*ChatCompletionResponseMessage) UnmarshalJSON

func (s *ChatCompletionResponseMessage) UnmarshalJSON(data []byte) error

UnmarshalJSON implements stdjson.Unmarshaler.

func (*ChatCompletionResponseMessage) Validate

func (s *ChatCompletionResponseMessage) Validate() error

type ChatCompletionResponseMessageRole

type ChatCompletionResponseMessageRole string

The role of the author of this message.

const (
	ChatCompletionResponseMessageRoleSystem    ChatCompletionResponseMessageRole = "system"
	ChatCompletionResponseMessageRoleUser      ChatCompletionResponseMessageRole = "user"
	ChatCompletionResponseMessageRoleAssistant ChatCompletionResponseMessageRole = "assistant"
)

func (*ChatCompletionResponseMessageRole) Decode

Decode decodes ChatCompletionResponseMessageRole from json.

func (ChatCompletionResponseMessageRole) Encode

Encode encodes ChatCompletionResponseMessageRole as json.

func (ChatCompletionResponseMessageRole) MarshalJSON

func (s ChatCompletionResponseMessageRole) MarshalJSON() ([]byte, error)

MarshalJSON implements stdjson.Marshaler.

func (ChatCompletionResponseMessageRole) MarshalText

func (s ChatCompletionResponseMessageRole) MarshalText() ([]byte, error)

MarshalText implements encoding.TextMarshaler.

func (*ChatCompletionResponseMessageRole) UnmarshalJSON

func (s *ChatCompletionResponseMessageRole) UnmarshalJSON(data []byte) error

UnmarshalJSON implements stdjson.Unmarshaler.

func (*ChatCompletionResponseMessageRole) UnmarshalText

func (s *ChatCompletionResponseMessageRole) UnmarshalText(data []byte) error

UnmarshalText implements encoding.TextUnmarshaler.

func (ChatCompletionResponseMessageRole) Validate

type Client

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

Client implements OAS client.

func NewClient

func NewClient(serverURL string, opts ...ClientOption) (*Client, error)

NewClient initializes new Client defined by OAS.

func (*Client) CancelFineTune

func (c *Client) CancelFineTune(ctx context.Context, params CancelFineTuneParams) (FineTune, error)

CancelFineTune invokes cancelFineTune operation.

Immediately cancel a fine-tune job.

POST /fine-tunes/{fine_tune_id}/cancel

func (*Client) CreateChatCompletion

func (c *Client) CreateChatCompletion(ctx context.Context, request *CreateChatCompletionRequest) (*CreateChatCompletionResponse, error)

CreateChatCompletion invokes createChatCompletion operation.

Creates a completion for the chat message.

POST /chat/completions

func (*Client) CreateEdit

func (c *Client) CreateEdit(ctx context.Context, request *CreateEditRequest) (*CreateEditResponse, error)

CreateEdit invokes createEdit operation.

Creates a new edit for the provided input, instruction, and parameters.

POST /edits

func (*Client) CreateFineTune

func (c *Client) CreateFineTune(ctx context.Context, request *CreateFineTuneRequest) (FineTune, error)

CreateFineTune invokes createFineTune operation.

Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning).

POST /fine-tunes

func (*Client) CreateImage

func (c *Client) CreateImage(ctx context.Context, request *CreateImageRequest) (ImagesResponse, error)

CreateImage invokes createImage operation.

Creates an image given a prompt.

POST /images/generations

func (*Client) CreateImageEdit

func (c *Client) CreateImageEdit(ctx context.Context, request *CreateImageEditRequestForm) (ImagesResponse, error)

CreateImageEdit invokes createImageEdit operation.

Creates an edited or extended image given an original image and a prompt.

POST /images/edits

func (*Client) CreateImageVariation

func (c *Client) CreateImageVariation(ctx context.Context, request *CreateImageVariationRequestForm) (ImagesResponse, error)

CreateImageVariation invokes createImageVariation operation.

Creates a variation of a given image.

POST /images/variations

func (*Client) CreateModeration

func (c *Client) CreateModeration(ctx context.Context, request *CreateModerationRequest) (*CreateModerationResponse, error)

CreateModeration invokes createModeration operation.

Classifies if text violates OpenAI's Content Policy.

POST /moderations

func (*Client) DeleteFile

func (c *Client) DeleteFile(ctx context.Context, params DeleteFileParams) (*DeleteFileResponse, error)

DeleteFile invokes deleteFile operation.

Delete a file.

DELETE /files/{file_id}

func (*Client) DeleteModel

func (c *Client) DeleteModel(ctx context.Context, params DeleteModelParams) (*DeleteModelResponse, error)

DeleteModel invokes deleteModel operation.

Delete a fine-tuned model. You must have the Owner role in your organization.

DELETE /models/{model}

func (*Client) DownloadFile

func (c *Client) DownloadFile(ctx context.Context, params DownloadFileParams) (string, error)

DownloadFile invokes downloadFile operation.

Returns the contents of the specified file.

GET /files/{file_id}/content

func (*Client) ListFiles

func (c *Client) ListFiles(ctx context.Context) (*ListFilesResponse, error)

ListFiles invokes listFiles operation.

Returns a list of files that belong to the user's organization.

GET /files

func (*Client) ListFineTuneEvents

func (c *Client) ListFineTuneEvents(ctx context.Context, params ListFineTuneEventsParams) (*ListFineTuneEventsResponse, error)

ListFineTuneEvents invokes listFineTuneEvents operation.

Get fine-grained status updates for a fine-tune job.

GET /fine-tunes/{fine_tune_id}/events

func (*Client) ListFineTunes

func (c *Client) ListFineTunes(ctx context.Context) (*ListFineTunesResponse, error)

ListFineTunes invokes listFineTunes operation.

List your organization's fine-tuning jobs.

GET /fine-tunes

func (*Client) ListModels

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

ListModels invokes listModels operation.

Lists the currently available models, and provides basic information about each one such as the owner and availability.

GET /models

func (*Client) RetrieveFile

func (c *Client) RetrieveFile(ctx context.Context, params RetrieveFileParams) (OpenAIFile, error)

RetrieveFile invokes retrieveFile operation.

Returns information about a specific file.

GET /files/{file_id}

func (*Client) RetrieveFineTune

func (c *Client) RetrieveFineTune(ctx context.Context, params RetrieveFineTuneParams) (FineTune, error)

RetrieveFineTune invokes retrieveFineTune operation.

Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning).

GET /fine-tunes/{fine_tune_id}

func (*Client) RetrieveModel

func (c *Client) RetrieveModel(ctx context.Context, params RetrieveModelParams) (Model, error)

RetrieveModel invokes retrieveModel operation.

Retrieves a model instance, providing basic information about the model such as the owner and permissioning.

GET /models/{model}

type ClientOption

type ClientOption interface {
	// contains filtered or unexported methods
}

ClientOption is client config option.

func WithClient

func WithClient(client ht.Client) ClientOption

WithClient specifies http client to use.

type CreateChatCompletionRequest

type CreateChatCompletionRequest struct {
	// ID of the model to use. Currently, only `gpt-3.5-turbo` and `gpt-3.5-turbo-0301` are supported.
	Model string `json:"model"`
	// The messages to generate chat completions for, in the [chat
	// format](/docs/guides/chat/introduction).
	Messages []ChatCompletionRequestMessage `json:"messages"`
	// What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output
	// more random, while lower values like 0.2 will make it more focused and deterministic.
	// We generally recommend altering this or `top_p` but not both.
	Temperature OptNilFloat64 `json:"temperature"`
	// An alternative to sampling with temperature, called nucleus sampling, where the model considers
	// the results of the tokens with top_p probability mass. So 0.1 means only the tokens comprising the
	// top 10% probability mass are considered.
	// We generally recommend altering this or `temperature` but not both.
	TopP OptNilFloat64 `json:"top_p"`
	// How many chat completion choices to generate for each input message.
	N OptNilInt `json:"n"`
	// If set, partial message deltas will be sent, like in ChatGPT. Tokens will be sent as data-only
	// [server-sent events](https://developer.mozilla.
	// org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they
	// become available, with the stream terminated by a `data: [DONE]` message.
	Stream OptNilBool `json:"stream"`
	// Up to 4 sequences where the API will stop generating further tokens.
	Stop OptCreateChatCompletionRequestStop `json:"stop"`
	// The maximum number of tokens allowed for the generated answer. By default, the number of tokens
	// the model can return will be (4096 - prompt tokens).
	MaxTokens OptInt `json:"max_tokens"`
	// Number between -2.0 and 2.0. Positive values penalize new tokens based on whether they appear in
	// the text so far, increasing the model's likelihood to talk about new topics.
	// [See more information about frequency and presence penalties.
	// ](/docs/api-reference/parameter-details).
	PresencePenalty OptNilFloat64 `json:"presence_penalty"`
	// Number between -2.0 and 2.0. Positive values penalize new tokens based on their existing frequency
	// in the text so far, decreasing the model's likelihood to repeat the same line verbatim.
	// [See more information about frequency and presence penalties.
	// ](/docs/api-reference/parameter-details).
	FrequencyPenalty OptNilFloat64 `json:"frequency_penalty"`
	// Modify the likelihood of specified tokens appearing in the completion.
	// Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an
	// associated bias value from -100 to 100. Mathematically, the bias is added to the logits generated
	// by the model prior to sampling. The exact effect will vary per model, but values between -1 and 1
	// should decrease or increase likelihood of selection; values like -100 or 100 should result in a
	// ban or exclusive selection of the relevant token.
	LogitBias OptCreateChatCompletionRequestLogitBias `json:"logit_bias"`
	// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
	// [Learn more](/docs/guides/safety-best-practices/end-user-ids).
	User OptString `json:"user"`
}

Ref: #/components/schemas/CreateChatCompletionRequest

func (*CreateChatCompletionRequest) Decode

Decode decodes CreateChatCompletionRequest from json.

func (*CreateChatCompletionRequest) Encode

func (s *CreateChatCompletionRequest) Encode(e *jx.Encoder)

Encode implements json.Marshaler.

func (*CreateChatCompletionRequest) GetFrequencyPenalty

func (s *CreateChatCompletionRequest) GetFrequencyPenalty() OptNilFloat64

GetFrequencyPenalty returns the value of FrequencyPenalty.

func (*CreateChatCompletionRequest) GetLogitBias

GetLogitBias returns the value of LogitBias.

func (*CreateChatCompletionRequest) GetMaxTokens

func (s *CreateChatCompletionRequest) GetMaxTokens() OptInt

GetMaxTokens returns the value of MaxTokens.

func (*CreateChatCompletionRequest) GetMessages

GetMessages returns the value of Messages.

func (*CreateChatCompletionRequest) GetModel

func (s *CreateChatCompletionRequest) GetModel() string

GetModel returns the value of Model.

func (*CreateChatCompletionRequest) GetN

GetN returns the value of N.

func (*CreateChatCompletionRequest) GetPresencePenalty

func (s *CreateChatCompletionRequest) GetPresencePenalty() OptNilFloat64

GetPresencePenalty returns the value of PresencePenalty.

func (*CreateChatCompletionRequest) GetStop

GetStop returns the value of Stop.

func (*CreateChatCompletionRequest) GetStream

func (s *CreateChatCompletionRequest) GetStream() OptNilBool

GetStream returns the value of Stream.

func (*CreateChatCompletionRequest) GetTemperature