openai

package module
v0.0.0-...-fcb1265 Latest Latest
Warning

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

Go to latest
Published: Jul 3, 2024 License: MIT Imports: 15 Imported by: 1

README

OpenAI Go

GoReport

This package provides an interface for interacting with services offered by OpenAI, such as Text-to-Speech (TTS), Transcription, and Chat (Completion, Function Calling) using advanced language models.

Installation

To install the OpenAI package, use the go get command:

go get github.com/Simplou/openai

Usage

Text-to-Speech (TTS)
package main

import (
	"fmt"
	"io"
	"os"
	"context"

	"github.com/Simplou/goxios"
	"github.com/Simplou/openai"
)

const fileName = "hello.mp3"

var (
	ctx        = context.Background()
	apiKey     = os.Getenv("OPENAI_KEY")
	client     = openai.New(ctx, apiKey)
	httpClient = goxios.New(ctx)
	audioFilePath = fmt.Sprintf("./temp/%s", fileName)
)

func main() {
	audio, err := openai.TextToSpeech(client, httpClient, &openai.SpeechRequestBody{
		Model: "tts-1",
		Input: "Hello",
		Voice: openai.SpeechVoices.Onyx,
	})
	if err != nil {
		panic(err)
	}
	defer audio.Close()
	b, err := io.ReadAll(audio)
	if err != nil {
		panic(err)
	}
	if err := os.WriteFile(audioFilePath, b, os.ModePerm); err != nil {
		panic(err)
	}
}
Audio Transcription
package main

import (
	"log"
	"os"
	"context"

	"github.com/Simplou/goxios"
    "github.com/Simplou/openai"
)

const fileName = "hello.mp3"

var (
	ctx        = context.Background()
	apiKey     = os.Getenv("OPENAI_KEY")
	client     = openai.New(ctx, apiKey)
	httpClient = goxios.New(ctx)
)

func main() {
	transcription, err := openai.Transcription(client, httpClient, &openai.TranscriptionsRequestBody{
		Model: openai.DefaultTranscriptionModel,
		Filename: fileName,
		AudioFilePath: audioFilePath,
	})
	if err != nil{
		panic(err)
	}
	println(transcription.Text)
}
Chat Completion
package main

import (
	"log"
	"os"
	"context"

	"github.com/Simplou/goxios"
	"github.com/Simplou/openai"
)

var (
	ctx        = context.Background()
	apiKey     = os.Getenv("OPENAI_KEY")
	client     = openai.New(ctx, apiKey)
	httpClient = goxios.New(ctx)
)

func main() {
	body := &openai.CompletionRequest[openai.DefaultMessages]{
		Model: "gpt-3.5-turbo",
		Messages: openai.DefaultMessages{
			{Role: "user", Content: "Hello"},
		},
	}

	res, err := openai.ChatCompletion(client, httpClient, body)
	if err != nil {
		panic(err)
	}
	log.Println(res.Choices[0].Message.Content)
}
Function Calling
package main

import (
	"encoding/json"
	"os"
	"context"

	"github.com/Simplou/goxios"
	"github.com/Simplou/openai"
)

var (
	ctx        = context.Background()
	apiKey     = os.Getenv("OPENAI_KEY")
	client     = openai.New(ctx, apiKey)
	httpClient = goxios.New(ctx)
)

func main() {
	type function func(string)
	functionRegistry := goxios.GenericJSON[function]{}
	sendEmailFnName  := "sendEmail"
	functionRegistry[sendEmailFnName] = func(email string) {
		println("email ", email)
	}
	body := &openai.CompletionRequest[openai.DefaultMessages]{
		Model: "gpt-3.5-turbo",
		Messages: openai.DefaultMessages{
			{Role: "user", Content: "send email to 93672097+gabrielluizsf@users.noreply.github.com"},
		},
		Tools: []openai.Tool{
			{
				Type: "function",
				Function: openai.Function{
					Name:        sendEmailFnName,
					Description: "send email",
					Parameters: openai.FunctionParameters{
						Type: "object",
						FunctionProperties: openai.FunctionProperties{
							"email": {
								Type:        "string",
								Description: "email provided by user",
							},
						},
					},
				},
			},
		},
		ToolChoice: "auto",
	}
	res, err := openai.ChatCompletion(client, httpClient, body)
	if err != nil {
		panic(err)
	}
	toolCalls := res.Choices[0].Message.ToolCalls
	if len(toolCalls) > 0 {
		var argumentsMap goxios.GenericJSON[string]
		if err := json.Unmarshal([]byte(toolCalls[0].Function.Args), &argumentsMap); err != nil {
			panic(err)
		}
		functionRegistry[toolCalls[0].Function.Name](argumentsMap["email"])
	}
}

Contribution

If you want to contribute improvements to this package, feel free to open an issue or send a pull request.

License

This package is licensed under the MIT License. See the LICENSE file for details.

Documentation

Index

Constants

View Source
const DefaultTranscriptionModel = "whisper-1"

Variables

View Source
var SpeechVoices = &openaiSpeechVoices{
	Alloy:   alloy,
	Echo:    echo,
	Fable:   fable,
	Onyx:    onyx,
	Nova:    nova,
	Shimmer: shimmer,
}

Functions

func ChatCompletion

func ChatCompletion[Messages any](api OpenAIClient, httpClient HTTPClient, body *CompletionRequest[Messages]) (*CompletionResponse, *OpenAIErr)

func ChunkText

func ChunkText(opts ChunkTextOpts) []string

ChunkText splits the input text into chunks of specified size.

func ChunksSummary

func ChunksSummary(client OpenAIClient, httpClient HTTPClient, relevantChunks []string, query string) (string, error)

ChunksSummary returns the summary of a randomly selected relevant chunk

func CreateEmbedding

func CreateEmbedding[Input string | []string, Encoding []float64 | Base64](api OpenAIClient, httpClient HTTPClient, body *EmbeddingRequest[Input]) (*EmbeddingResponse[Encoding], *OpenAIErr)

CreateEmbedding sends a request to create embeddings for the given input.

func FindMostRelevantEmbeddings

func FindMostRelevantEmbeddings(q, e [][]float64) ([]int, error)

FindMostRelevantEmbeddings finds the most relevant embeddings. q is the query embedding, and e is the matrix of embeddings to search in.

func ImageUrl

func ImageUrl(url string) *imageUrl

func Moderator

func Moderator[Input string | []string](api OpenAIClient, httpClient HTTPClient, body *ModerationRequest[Input]) (*ModerationResponse, *OpenAIErr)

func NaturalImageStyle

func NaturalImageStyle() imageStyle

NaturalImageStyle causes the model to produce more natural, less hyper-real looking images.

func VividImageStyle

func VividImageStyle() imageStyle

VividImageStyle causes the model to lean towards generating hyper-real and dramatic images

Types

type Base64

type Base64 string

type Choice

type Choice struct {
	Index        int             `json:"index"`
	Message      Message[string] `json:"message"`
	Logprobs     interface{}     `json:"logprobs,omitempty"`
	FinishReason string          `json:"finish_reason"`
}

Choice represents a response choice in the conversation.

type ChunkTextOpts

type ChunkTextOpts struct {
	Text      string
	ChunkSize int
}

type Client

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

func New

func New(ctx context.Context, apiKey string) *Client

func (*Client) AddHeader

func (c *Client) AddHeader(h goxios.Header)

func (*Client) ApiKey

func (c *Client) ApiKey() string

func (*Client) BaseURL

func (c *Client) BaseURL() string

func (*Client) Context

func (c *Client) Context() context.Context

func (*Client) Headers

func (c *Client) Headers() []goxios.Header

type CompletionRequest

type CompletionRequest[T any] struct {
	Model      string `json:"model"`
	Messages   T      `json:"messages"`
	ToolChoice string `json:"tool_choice,omitempty"`
	Tools      []Tool `json:"tools,omitempty"`
}

CompletionRequest represents the structure of the request sent to the OpenAI API.

type CompletionResponse

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

CompletionResponse represents the structure of the response received from the OpenAI API.

type DefaultMessages

type DefaultMessages []Message[string]

type Embedding

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

type EmbeddingRequest

type EmbeddingRequest[Input string | []string] struct {
	// Input text to embed, encoded as a string or array of tokens.
	Input Input `json:"input"`
	// ID of the model to use.
	Model string `json:"model"`
	// The format to return the embeddings in. Can be either float or base64.
	Encoding string `json:"encoding_format,omitempty"`
	// The number of dimensions the resulting output embeddings should have. Only supported in text-embedding-3 and later models.
	Dimensions int `json:"dimensions,omitempty"`
	// A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse.
	User string `json:"user,omitempty"`
}

type EmbeddingResponse

type EmbeddingResponse[Encoding []float64 | Base64] struct {
	Object string                `json:"object"`
	Data   []Embedding[Encoding] `json:"data"`
	Model  string                `json:"model"`
	Usage  Usage                 `json:"usage"`
}

type Function

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

Function represents a function call that can be used as a tool.

type FunctionParameters

type FunctionParameters struct {
	Type               string `json:"type"`
	FunctionProperties `json:"properties"`
}

FunctionParameters represents the parameters of a function

type FunctionPropertie

type FunctionPropertie struct {
	Type        string   `json:"type"`
	Description string   `json:"description"`
	Enum        []string `json:"enum,omitempty"`
}

FunctionPropertie represents a property of a function.

type FunctionProperties

type FunctionProperties goxios.GenericJSON[FunctionPropertie]

type HTTPClient

type HTTPClient interface {
	Post(string, *goxios.RequestOpts) (*http.Response, error)
	Get(string, *goxios.RequestOpts) (*http.Response, error)
}

type ImagesGenerationsRequestBody

type ImagesGenerationsRequestBody struct {
	Model  string `json:"model"`
	Prompt string `json:"prompt"`
	N      int    `json:"n"`
	Size   string `json:"size"`
	Style  string `json:"style,omitempty"` //This param is only supported for dall-e-3.
}

type ImagesGenerationsResponse

type ImagesGenerationsResponse struct {
	Created int64 `json:"created"`
	Data    []struct {
		Url string `json:"url"`
	} `json:"data"`
}

func (*ImagesGenerationsResponse) Download

func (igr *ImagesGenerationsResponse) Download(httpClient HTTPClient, filePaths []string) error

type JSONErr

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

type MediaMessage

type MediaMessage struct {
	Type     string    `json:"type"`
	Text     string    `json:"text,omitempty"`
	ImageUrl *imageUrl `json:"image_url,omitempty"`
}

type MediaMessages

type MediaMessages []Message[[]MediaMessage]

type Message

type Message[T string | []MediaMessage] struct {
	Role      string     `json:"role"`
	Content   T          `json:"content"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
}

Message represents a message in the conversation.

type ModerationRequest

type ModerationRequest[Input string | []string] struct {
	Input Input  `json:"input"`
	Model string `json:"model,omitempty"`
}

type ModerationResponse

type ModerationResponse struct {
	Id      string `json:"id"`
	Model   string `json:"model"`
	Results []struct {
		Flagged    bool                     `json:"flagged"`
		Categories goxios.GenericJSON[bool] `json:"categories"`
	} `json:"results"`
	CategoryScores goxios.GenericJSON[float64] `json:"category_scores"`
}

type OpenAIClient

type OpenAIClient interface {
	Context() context.Context
	ApiKey() string
	BaseURL() string
	AddHeader(goxios.Header)
	Headers() []goxios.Header
}

type OpenAIErr

type OpenAIErr struct {
	Err JSONErr `json:"error"`
	// contains filtered or unexported fields
}

func NewOpenAIErr

func NewOpenAIErr(err error, statusCode int, t string) *OpenAIErr

func TextToSpeech

func TextToSpeech(api OpenAIClient, httpClient HTTPClient, body *SpeechRequestBody) (io.ReadCloser, *OpenAIErr)

func (*OpenAIErr) Error

func (o *OpenAIErr) Error() string

func (*OpenAIErr) Status

func (o *OpenAIErr) Status() int

type SpeechRequestBody

type SpeechRequestBody struct {
	Model string `json:"model"` // The model for speech synthesis.
	Input string `json:"input"` // The input text for synthesis.
	Voice string `json:"voice"` // The voice to be used for synthesis.
}

SpeechRequestBody represents the request body for the speech API.

type Tool

type Tool struct {
	Type     string   `json:"type"`
	Function Function `json:"function,omitempty"`
}

Tool represents a tool that can be used during the conversation.

type ToolCall

type ToolCall struct {
	Id       string `json:"id"`
	Type     string `json:"type"`
	Function struct {
		Name string `json:"name"`
		Args string `json:"arguments"`
	} `json:"function"`
}

type TranscriptionResponse

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

type TranscriptionsRequestBody

type TranscriptionsRequestBody struct {
	Model, Filename, AudioFilePath string
}

type Usage

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens,omitempty"`
	TotalTokens      int `json:"total_tokens"`
}

Usage represents the token usage in the request and response.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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