openai

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2023 License: Apache-2.0 Imports: 22 Imported by: 0

README

OpenAI Go SDK

This is an unofficial Go SDK for interacting with the OpenAI API, which allows you to leverage the power of OpenAI's models like GPT-4 within your Go applications. This SDK aims to simplify the process of integrating OpenAI's API with your projects by providing an easy-to-use interface.

Note: This SDK is not officially supported by OpenAI and comes with no warranty.

Table of Contents

Features

  • Easy integration with the OpenAI API
  • Support for various OpenAI models
  • Simple and intuitive function calls
  • Extensible for future API updates

Supported Services

The following services are currently supported by the SDK:

Installation

You can install the OpenAI Go SDK using the following command:

go get -u github.com/uzziahlin/openai

Usage

The following code snippet shows how to use the SDK to create a chat completion using the gpt-3.5-turbo model:

package main

import (
	"context"
	"fmt"
	"github.com/uzziahlin/openai"
	"os"
)

func main() {
	// get api key, suggest to use environment variable
	apiKey := os.Getenv("OPENAI_API_KEY")

	// create a new client
	client, err := openai.New(openai.App{
		ApiUrl: "https://api.openai.com",
		ApiKey: apiKey,
	})

	// if you want to use proxy, you can use the following code
	//client, err := openai.New(openai.App{
	//	ApiUrl: "https://api.openai.com",
	//	ApiKey: apiKey,
	//}, openai.WithProxy(&openai.Proxy{
	//	Url:      "your proxy url"
	//	Username: "your proxy username, if not need, just leave it",
	//	Password: "your proxy password, if not need, just leave it",
	//}))

	if err != nil {
		// handle error
	}

	// create a new chat session, not stream
	resp, err := client.Chat.Create(context.TODO(), &openai.ChatCreateRequest{
		Model: "gpt-3.5-turbo",
		Messages: []*openai.Message{
			// can add more messages here
			{
				Role:    "user",
				Content: "Hello, How are you?",
			},
		},
	})

	// To be compatible with the streaming API, the returned value is a channel
	// and since it is not a stream, there is only one element, which can be taken out directly
	res, ok := <-resp

	if !ok {
		// if the channel is closed, it means that the request has been completed
	}

	// handle response
	// for example, print the first choice
	fmt.Println(res.Choices[0].Message.Content)
}

if you want to use the streaming API, you can use the following code:

// The flow of creating a client and a non-streaming flow is the same
// only when creating a session, the stream parameter is set to true
resp, err := client.Chat.Create(context.TODO(), &openai.ChatCreateRequest{
    Model: "gpt-3.5-turbo",
    Messages: []*openai.Message{
        // can add more messages here
        {
            Role:    "user",
            Content: "Hello, How are you?",
        },
    },
    Stream: true,
})

if err != nil {
    // handle error
}

for {
    res, ok := <-resp
    if !ok {
        // channel is closed
        break
    }
    
    // handle response
    // for example, print the response
    // the content of the response is in the res.Choices[0].Delta.Content
    fmt.Println(res.Choices[0].Delta.Content)
}

other services are similar to the above usage, so I won't repeat it here.

License

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

Documentation

Index

Constants

View Source
const (
	AudioTranscriptionsPath = "/audio/transcriptions"
	AudioTranslationsPath   = "/audio/translations"
)
View Source
const (
	// ChatCreatePath 聊天创建路径
	ChatCreatePath = "/chat/completions"

	FunctionCallNone = FunctionCallString("none")
	FunctionCallAuto = FunctionCallString("auto")

	FinishReasonFunctionCall = "function_call"
	FinishReasonStop         = "stop"
)
View Source
const (
	FilesListPath           = "/files"
	FileUploadPath          = "/files"
	FileDeletePath          = "/files/%s"
	FileRetrievePath        = "/files/%s"
	FileContentRetrievePath = "/files/%s/content"
)
View Source
const (
	FineTuneCreatePath   = "/fine-tunes"
	FineTuneListPath     = "/fine-tunes"
	FineTuneRetrievePath = "/fine-tunes/%s"
	FineTuneCancelPath   = "/fine-tunes/%s/cancel"
	EventsListPath       = "/fine-tunes/%s/events"
	ModelDeletePath      = "/models/%s"
)
View Source
const (
	ImageCreatePath    = "/images/generations"
	ImageEditPath      = "/images/edits"
	ImageVariationPath = "/images/variations"
)
View Source
const (
	ModelListPath     = "/models"
	ModelRetrievePath = "/models/%s"

	GPT35Turbo        = "gpt-3.5-turbo"
	GPT35Turbo0301    = "gpt-3.5-turbo-0301"
	GPT35Turbo0613    = "gpt-3.5-turbo-0613"
	GPT35Turbo16k     = "gpt-3.5-turbo-16k"
	GPT35Turbo16k0613 = "gpt-3.5-turbo-16k-0613"
	GPT4              = "gpt-4"
	GPT40314          = "gpt-4-0314"
	GPT40613          = "gpt-4-0613"

	Ada        = "ada"
	TextAda001 = "text-ada-001"

	Babbage        = "babbage"
	TextBabbage001 = "text-babbage-001"

	Curie        = "curie"
	TextCurie001 = "text-curie-001"

	DaVinci        = "davinci"
	TextDaVinci001 = "text-davinci-001"
	TextDaVinci002 = "text-davinci-002"
	TextDaVinci003 = "text-davinci-003"
)
View Source
const (
	CompletionsCreatePath = "/completions"
)
View Source
const (
	EditCreatePath = "/edits"
)
View Source
const (
	EmbeddingCreatePath = "/embeddings"
)
View Source
const (
	ModerationCreatePath = "/moderations"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	ApiUrl string
	ApiKey string
}

type AudioService

type AudioService interface {
	Transcriptions(ctx context.Context, req *TranscriptionsRequest) (*TranscriptionsResponse, error)
	Translations(ctx context.Context, req *TranslationsRequest) (*TranslationsResponse, error)
}

type AudioServiceOp

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

func (AudioServiceOp) Transcriptions

func (AudioServiceOp) Translations

type ChatCompletion

type ChatCompletion struct {
	Index        int64    `json:"index"`
	Delta        *Delta   `json:"delta"`
	Message      *Message `json:"message"`
	FinishReason string   `json:"finish_reason"`
}

type ChatCreateRequest

type ChatCreateRequest struct {
	Model            string           `json:"model"`
	Messages         []*Message       `json:"messages,omitempty"`
	Functions        []*Function      `json:"functions,omitempty"`
	FunctionCall     IFunctionCall    `json:"function_call,omitempty"`
	Temperature      float64          `json:"temperature,omitempty"`
	TopP             float64          `json:"top_p,omitempty"`
	N                int64            `json:"n,omitempty"`
	Stream           bool             `json:"stream,omitempty"`
	Stop             []string         `json:"stop,omitempty"`
	MaxTokens        int64            `json:"max_tokens,omitempty"`
	PresencePenalty  float64          `json:"presence_penalty,omitempty"`
	FrequencyPenalty float64          `json:"frequency_penalty,omitempty"`
	LogitBias        map[string]int64 `json:"logit_bias,omitempty"`
	User             string           `json:"user,omitempty"`
}

type ChatCreateResponse

type ChatCreateResponse struct {
	Id      string            `json:"id"`
	Object  string            `json:"object"`
	Created int64             `json:"created"`
	Choices []*ChatCompletion `json:"choices"`
	Usage   Usage             `json:"usage"`
}

type ChatService

type ChatService interface {
	Create(ctx context.Context, req *ChatCreateRequest) (chan *ChatCreateResponse, error)
}

type ChatServiceOp

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

func (ChatServiceOp) Create

Create 创建一个新的聊天,为了兼容 stream 模式,返回一个 channel,如果不是 stream 模式,返回的 channel 会在第一次返回后关闭 如果是 stream 模式,返回的 channel 会在 ctx.Done() 或者 stream 关闭后关闭 这里其实也可以考虑拆分为两个方法,一个是 Create,一个是 CreateStream,但是这样会导致 API 不一致,所以这里就不拆分了

type Client

type Client struct {
	Models      ModelService
	Completions CompletionService
	Chat        ChatService
	Edits       EditService
	Images      ImageService
	Embeddings  EmbeddingService
	Audio       AudioService
	Files       FileService
	FineTunes   FineTuneService
	Moderations ModerationService
	// contains filtered or unexported fields
}

func New

func New(app App, opts ...Option) (*Client, error)

func (*Client) Close

func (c *Client) Close() error

func (*Client) Delete

func (c *Client) Delete(ctx context.Context, relPath string, params, resp any) error

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, relPath string, headers map[string]string, params, body, v any) error

func (*Client) Get

func (c *Client) Get(ctx context.Context, relPath string, params, resp any) error

func (*Client) GetByStream

func (c *Client) GetByStream(ctx context.Context, relPath string, params any) (EventSource, error)

func (*Client) GetBytes

func (c *Client) GetBytes(ctx context.Context, method, relPath string, headers map[string]string, params, body any) ([]byte, error)

GetBytes 获取字节流, 也可以考虑合并到Do中 但是由于api中大部分都是json, 所以这里单独提取出来

func (*Client) NewRequest

func (c *Client) NewRequest(ctx context.Context, method string, relPath string, headers map[string]string, params any, body any) (*http.Request, error)

func (*Client) Post

func (c *Client) Post(ctx context.Context, relPath string, body, resp any) error

func (*Client) PostByStream

func (c *Client) PostByStream(ctx context.Context, relPath string, body any) (EventSource, error)

func (*Client) Stream

func (c *Client) Stream(ctx context.Context, method, relPath string, headers map[string]string, params, body any) (EventSource, error)

Stream 为请求提供流式处理

func (*Client) Upload

func (c *Client) Upload(ctx context.Context, relPath string, files []*FormFile, v any, fields ...*FormField) error

Upload file to openai files: file to upload v: response data fields: other fields

func (*Client) V

func (c *Client) V(version string) Client

V 设置版本,返回一个新的Client实例,不会修改原有实例

type Completion

type Completion struct {
	Text         string `json:"text"`
	Delta        *Delta `json:"delta"`
	Index        int64  `json:"index"`
	Logprobs     int64  `json:"logprobs"`
	FinishReason string `json:"finish_reason"`
}

type CompletionCreateRequest

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

type CompletionCreateResponse

type CompletionCreateResponse struct {
	Id      string        `json:"id"`
	Object  string        `json:"object"`
	Created int64         `json:"created"`
	Model   string        `json:"model"`
	Choices []*Completion `json:"choices"`
	Usage   Usage         `json:"usage"`
}

type CompletionService

type CompletionService interface {
	Create(ctx context.Context, req *CompletionCreateRequest) (chan *CompletionCreateResponse, error)
}

type CompletionServiceOp

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

func (CompletionServiceOp) Create

Create 创建一个新的聊天,为了兼容 stream 模式,返回一个 channel,如果不是 stream 模式,返回的 channel 会在第一次返回后关闭 如果是 stream 模式,返回的 channel 会在 ctx.Done() 或者 stream 关闭后关闭 这里其实也可以考虑拆分为两个方法,一个是 Create,一个是 CreateStream,但是这样会导致 API 不一致,所以这里就不拆分了

type Delta

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

type Edit

type Edit struct {
	Text  string `json:"text"`
	Index int64  `json:"index"`
}

type EditCreateRequest

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

type EditCreateResponse

type EditCreateResponse struct {
	Object  string  `json:"object"`
	Created int64   `json:"created"`
	Choices []*Edit `json:"choices"`
	Usage   Usage   `json:"usage"`
}

type EditService

type EditService interface {
	Create(ctx context.Context, request *EditCreateRequest) (*EditCreateResponse, error)
}

type EditServiceOp

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

func (EditServiceOp) Create

type Embedding

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

type EmbeddingCreateRequest

type EmbeddingCreateRequest struct {
	Model string   `json:"model"`
	Input []string `json:"input"`
	User  string   `json:"user,omitempty"`
}

type EmbeddingCreateResponse

type EmbeddingCreateResponse struct {
	Object string          `json:"object"`
	Data   []*Embedding    `json:"data"`
	Model  string          `json:"model"`
	Usage  *EmbeddingUsage `json:"usage"`
}

type EmbeddingService

type EmbeddingService interface {
	Create(ctx context.Context, req *EmbeddingCreateRequest) (*EmbeddingCreateResponse, error)
}

type EmbeddingServiceOp

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

func (EmbeddingServiceOp) Create

type EmbeddingUsage

type EmbeddingUsage struct {
	PromptTokens int64 `json:"prompt_tokens"`
	TotalTokens  int64 `json:"total_tokens"`
}

type Event

type Event struct {
	Id    string
	Event string
	Data  string
	Retry time.Duration
	Err   error
}

type EventListResponse

type EventListResponse struct {
	Object string           `json:"object"`
	Data   []*FineTuneEvent `json:"data"`
}

type EventSource

type EventSource chan Event

func NewEventSource

func NewEventSource(ctx context.Context, r io.ReadCloser, doneStr string) EventSource

NewEventSource 处理SSE

type File

type File struct {
	Id        string `json:"id"`
	Object    string `json:"object"`
	Bytes     int64  `json:"bytes"`
	CreatedAt int64  `json:"created_at"`
	Filename  string `json:"filename"`
	Purpose   string `json:"purpose"`
}

type FileDeleteResponse

type FileDeleteResponse struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

type FileListResponse

type FileListResponse struct {
	Data []*File `json:"data"`
}

type FileService

type FileService interface {
	List(ctx context.Context) (*FileListResponse, error)
	Upload(ctx context.Context, req *FileUploadRequest) (*File, error)
	Delete(ctx context.Context, fileId string) (*FileDeleteResponse, error)
	Retrieve(ctx context.Context, fileId string) (*File, error)
	RetrieveContent(ctx context.Context, fileId string) ([]byte, error)
}

type FileServiceOp

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

func (FileServiceOp) Delete

func (f FileServiceOp) Delete(ctx context.Context, fileId string) (*FileDeleteResponse, error)

func (FileServiceOp) List

func (FileServiceOp) Retrieve

func (f FileServiceOp) Retrieve(ctx context.Context, fileId string) (*File, error)

func (FileServiceOp) RetrieveContent

func (f FileServiceOp) RetrieveContent(ctx context.Context, fileId string) ([]byte, error)

func (FileServiceOp) Upload

func (f FileServiceOp) Upload(ctx context.Context, req *FileUploadRequest) (*File, error)

type FileUploadRequest

type FileUploadRequest struct {
	File    string `json:"file"`
	Purpose string `json:"purpose"`
}

type FineTune

type FineTune struct {
	Id              string           `json:"id"`
	Object          string           `json:"object"`
	Model           string           `json:"model"`
	CreateAt        int64            `json:"create_at"`
	Events          []*FineTuneEvent `json:"events"`
	FineTunedModel  string           `json:"fine_tuned_model"`
	Hyperparams     Hyperparams      `json:"hyperparams"`
	OrganizationId  string           `json:"organization_id"`
	ResultFiles     []*File          `json:"result_files"`
	Status          string           `json:"status"`
	ValidationFiles []*File          `json:"validation_files"`
	TrainingFiles   []*File          `json:"training_files"`
	UpdatedAt       int64            `json:"updated_at"`
}

type FineTuneCreateRequest

type FineTuneCreateRequest struct {
	// TrainingFile is the ID to the training file
	TrainingFile                  string    `json:"training_file"`
	ValidationFile                string    `json:"validation_file,omitempty"`
	Model                         string    `json:"model,omitempty"`
	NEpochs                       int       `json:"n_epochs,omitempty"`
	BatchSize                     int       `json:"batch_size,omitempty"`
	LearningRateMultiplier        float64   `json:"learning_rate_multiplier,omitempty"`
	PromptLossWeight              float64   `json:"prompt_loss_weight,omitempty"`
	ComputeClassificationMetrics  bool      `json:"compute_classification_metrics,omitempty"`
	ClassificationNClasses        int64     `json:"classification_n_classes,omitempty"`
	ClassificationPositiveClasses string    `json:"classification_positive_classes,omitempty"`
	ClassificationBetas           []float64 `json:"classification_betas,omitempty"`
	Suffix                        string    `json:"suffix,omitempty"`
}

type FineTuneEvent

type FineTuneEvent struct {
	Object   string `json:"object"`
	CreateAt int64  `json:"create_at"`
	Level    string `json:"level"`
	Message  string `json:"message"`
}

type FineTuneListResponse

type FineTuneListResponse struct {
	Object string      `json:"object"`
	Data   []*FineTune `json:"data"`
}

type FineTuneService

type FineTuneService interface {
	Create(ctx context.Context, req *FineTuneCreateRequest) (*FineTune, error)
	List(ctx context.Context) (*FineTuneListResponse, error)
	Retrieve(ctx context.Context, id string) (*FineTune, error)
	Cancel(ctx context.Context, id string) (*FineTune, error)
	ListEvents(ctx context.Context, id string, stream ...bool) (chan *EventListResponse, error)
	DeleteModel(ctx context.Context, model string) (*ModelDeleteResponse, error)
}

type FineTuneServiceOp

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

func (FineTuneServiceOp) Cancel

func (f FineTuneServiceOp) Cancel(ctx context.Context, id string) (*FineTune, error)

Cancel Cancels a fine-tuning job.

func (FineTuneServiceOp) Create

Create 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.

func (FineTuneServiceOp) DeleteModel

func (f FineTuneServiceOp) DeleteModel(ctx context.Context, model string) (*ModelDeleteResponse, error)

DeleteModel Deletes a fine-tuned model.

func (FineTuneServiceOp) List

List Returns a list of all fine-tuning jobs.

func (FineTuneServiceOp) ListEvents

func (f FineTuneServiceOp) ListEvents(ctx context.Context, id string, stream ...bool) (chan *EventListResponse, error)

ListEvents Returns a list of events for a fine-tuning job. If stream=true, the response will be a stream of events as they are generated. by default, the response will be a list of all events generated so far.

func (FineTuneServiceOp) Retrieve

func (f FineTuneServiceOp) Retrieve(ctx context.Context, id string) (*FineTune, error)

Retrieve Returns a fine-tuning job by ID.

type FormBuilder

type FormBuilder interface {
	CreateFormFile(name string, filename string) error
	CreateFormField(name string, value string) error
	FormDataContentType() string
	io.Closer
}

FormBuilder is a builder for multipart/form-data requests.

func NewMultiPartFormBuilder

func NewMultiPartFormBuilder(w io.Writer) FormBuilder

type FormField

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

func NewFormField

func NewFormField(fieldName, fieldValue string) *FormField

type FormFile

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

func NewFormFile

func NewFormFile(fieldName, filename string) *FormFile

type Function added in v1.0.1

type Function struct {
	Name        string    `json:"name"`
	Description string    `json:"description,omitempty"`
	Parameters  Parameter `json:"parameters,omitempty"`
}

type FunctionCall added in v1.0.1

type FunctionCall struct {
	Name      string `json:"name"`
	Arguments []byte `json:"arguments,omitempty"`
}

func (FunctionCall) Call added in v1.0.1

func (f FunctionCall) Call()

type FunctionCallString added in v1.0.1

type FunctionCallString string

func (FunctionCallString) Call added in v1.0.1

func (f FunctionCallString) Call()

type Hyperparams

type Hyperparams struct {
	BatchSize              int64   `json:"batch_size"`
	LearningRateMultiplier float64 `json:"learning_rate_multiplier"`
	NEpochs                int64   `json:"n_epochs"`
	PromptLossWeight       float64 `json:"prompt_loss_weight"`
}

type IFunctionCall added in v1.0.1

type IFunctionCall interface {
	Call()
}

type Image

type Image struct {
	Url string `json:"url"`
}

type ImageAttributes

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

type ImageCreateRequest

type ImageCreateRequest struct {
	Prompt string `json:"prompt"`
	ImageAttributes
}

type ImageEditRequest

type ImageEditRequest struct {
	// Image is the path to the image file
	Image string `json:"image"`
	// Mask is the path to the mask file
	Mask   string `json:"mask,omitempty"`
	Prompt string `json:"prompt"`
	ImageAttributes
}

type ImageResponse

type ImageResponse struct {
	Created int64   `json:"created"`
	Data    []Image `json:"data"`
}

type ImageService

type ImageService interface {
	Create(ctx context.Context, req *ImageCreateRequest) (*ImageResponse, error)
	Edit(ctx context.Context, req *ImageEditRequest) (*ImageResponse, error)
	Variation(ctx context.Context, req *ImageVariationRequest) (*ImageResponse, error)
}

type ImageServiceOp

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

func (ImageServiceOp) Create

func (ImageServiceOp) Edit

func (ImageServiceOp) Variation

type ImageVariationRequest

type ImageVariationRequest struct {
	Image string `json:"image"`
	ImageAttributes
}

type Message

type Message struct {
	Role         string       `json:"role"` // user,assistant,system,function
	Content      string       `json:"content,omitempty"`
	Name         string       `json:"name,omitempty"`
	FunctionCall FunctionCall `json:"function_call,omitempty"`
}

type Model

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

type ModelDeleteResponse

type ModelDeleteResponse struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Deleted bool   `json:"deleted"`
}

type ModelResponse

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

type ModelService

type ModelService interface {
	List(ctx context.Context) (*ModelResponse, error)
	Retrieve(ctx context.Context, model string) (*Model, error)
}

type ModelServiceOp

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

func (ModelServiceOp) List

func (ModelServiceOp) Retrieve

func (m ModelServiceOp) Retrieve(ctx context.Context, model string) (*Model, error)

type Moderation

type Moderation struct {
	Categories     ModerationCategory      `json:"categories"`
	CategoryScores ModerationCategoryScore `json:"category_scores"`
	Flagged        bool                    `json:"flagged"`
}

type ModerationCategory

type ModerationCategory struct {
	Hate            bool `json:"hate"`
	HateThreatening bool `json:"hate/threatening"`
	SelfHarm        bool `json:"self-harm"`
	Sexual          bool `json:"sexual"`
	SexualMinors    bool `json:"sexual/minors"`
	Violence        bool `json:"violence"`
	ViolenceGraphic bool `json:"violence/graphic"`
}

type ModerationCategoryScore

type ModerationCategoryScore struct {
	Hate            float64 `json:"hate"`
	HateThreatening float64 `json:"hate/threatening"`
	SelfHarm        float64 `json:"self-harm"`
	Sexual          float64 `json:"sexual"`
	SexualMinors    float64 `json:"sexual/minors"`
	Violence        float64 `json:"violence"`
	ViolenceGraphic float64 `json:"violence/graphic"`
}

type ModerationCreateRequest

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

type ModerationCreateResponse

type ModerationCreateResponse struct {
	Id      string        `json:"id"`
	Model   string        `json:"model"`
	Results []*Moderation `json:"results"`
}

type ModerationService

type ModerationService interface {
	Create(ctx context.Context, req *ModerationCreateRequest) (*ModerationCreateResponse, error)
}

type ModerationServiceOp

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

func (ModerationServiceOp) Create

type Option

type Option func(*Client)

func WithFormBuilder

func WithFormBuilder(builder func(w io.Writer) FormBuilder) Option

func WithLogger

func WithLogger(logger logr.Logger) Option

func WithProxy

func WithProxy(proxy *Proxy) Option

func WithRetries

func WithRetries(retries int) Option

func WithVersion

func WithVersion(version string) Option

WithVersion 设置默认版本,如果不设置,默认为v1

type Parameter added in v1.0.1

type Parameter struct {
	Type       string               `json:"type"` // object only
	Properties map[string]*Property `json:"properties,omitempty"`
	Required   []string             `json:"required,omitempty"`
}

type Property added in v1.0.1

type Property struct {
	Type        string               `json:"type"`
	Description string               `json:"description,omitempty"`
	Properties  map[string]*Property `json:"properties,omitempty"` // if type is object, this field will be set
}

type Proxy

type Proxy struct {
	Url      string
	Username string
	Password string
	TlsCfg   *tls.Config
}

type TranscriptionsRequest

type TranscriptionsRequest struct {
	// File is the path to the audio file
	File           string  `json:"file"`
	Model          string  `json:"model"`
	Prompt         string  `json:"prompt,omitempty"`
	ResponseFormat string  `json:"response_format,omitempty"`
	Temperature    float64 `json:"temperature,omitempty"`
	Language       string  `json:"language,omitempty"`
}

type TranscriptionsResponse

type TranscriptionsResponse struct {
	Text string `json:"text"`
}

type TranslationsRequest

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

type TranslationsResponse

type TranslationsResponse struct {
	Text string `json:"text"`
}

type Usage

type Usage struct {
	PromptTokens     int64 `json:"prompt_tokens"`
	CompletionTokens int64 `json:"completion_tokens"`
	TotalTokens      int64 `json:"total_tokens"`
}

Jump to

Keyboard shortcuts

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