openaigosdk

package module
v4.2.1 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2024 License: MIT Imports: 12 Imported by: 0

README

OpenAPI Go SDK

OpenAI_Logo_Black OpenAI_Logo_White

This is an unofficial SDK for the OpenAI API. The OpenAI API can be applied to virtually any task that involves understanding or generating natural language or code. We offer a spectrum of models with different levels of power suitable for different tasks, as well as the ability to fine-tune your own custom models. These models can be used for everything from content generation to semantic search and classification.

SDK Installation

go get github.com/speakeasy-sdks/openai-go-sdk

Authentication

The OpenAI API uses API keys for authentication. Visit your API Keys page to retrieve the API key you'll use in your requests.

Remember that your API key is a secret! Do not share it with others or expose it in any client-side code (browsers, apps). Production requests must be routed through your own backend server where your API key can be securely loaded from an environment variable or key management service.

All API requests should include your API key in an Authorization HTTP header as follows:

Authorization: Bearer YOUR_API_KEY

SDK Example Usage

Example
package main

import (
	"context"
	openaigosdk "github.com/speakeasy-sdks/openai-go-sdk/v4"
	"github.com/speakeasy-sdks/openai-go-sdk/v4/pkg/models/shared"
	"log"
)

func main() {
	s := openaigosdk.New(
		openaigosdk.WithSecurity("<YOUR_BEARER_TOKEN_HERE>"),
	)

	var runID string = "<value>"

	var threadID string = "<value>"

	ctx := context.Background()
	res, err := s.Assistants.CancelRun(ctx, runID, threadID)
	if err != nil {
		log.Fatal(err)
	}

	if res.RunObject != nil {
		// handle response
	}
}

Available Resources and Operations

Assistants
Audio
Chat
Completions
  • CreateCompletion - Creates a completion for the provided prompt and parameters.
Embeddings
  • CreateEmbedding - Creates an embedding vector representing the input text.
Files
  • CreateFile - Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB.

The size of individual files can be a maximum of 512 MB or 2 million tokens for Assistants. See the Assistants Tools guide to learn more about the types of files supported. The Fine-tuning API only supports .jsonl files.

Please contact us if you need to increase these storage limits.

  • DeleteFile - Delete a file.
  • DownloadFile - Returns the contents of the specified file.
  • ListFiles - Returns a list of files that belong to the user's organization.
  • RetrieveFile - Returns information about a specific file.
FineTuning

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

Learn more about fine-tuning

Images
Models
  • DeleteModel - Delete a fine-tuned model. You must have the Owner role in your organization to delete a model.
  • ListModels - Lists the currently available models, and provides basic information about each one such as the owner and availability.
  • RetrieveModel - Retrieves a model instance, providing basic information about the model such as the owner and permissioning.
Moderations

Error Handling

Handling errors in this SDK should largely match your expectations. All operations return a response object or an error, they will never return both. When specified by the OpenAPI spec document, the SDK will return the appropriate subclass.

Error Object Status Code Content Type
sdkerrors.SDKError 4xx-5xx /
Example
package main

import (
	"context"
	"errors"
	openaigosdk "github.com/speakeasy-sdks/openai-go-sdk/v4"
	"github.com/speakeasy-sdks/openai-go-sdk/v4/pkg/models/sdkerrors"
	"github.com/speakeasy-sdks/openai-go-sdk/v4/pkg/models/shared"
	"log"
)

func main() {
	s := openaigosdk.New(
		openaigosdk.WithSecurity("<YOUR_BEARER_TOKEN_HERE>"),
	)

	var runID string = "<value>"

	var threadID string = "<value>"

	ctx := context.Background()
	res, err := s.Assistants.CancelRun(ctx, runID, threadID)
	if err != nil {

		var e *sdkerrors.SDKError
		if errors.As(err, &e) {
			// handle error
			log.Fatal(e.Error())
		}
	}
}

Server Selection

Select Server by Index

You can override the default server globally using the WithServerIndex option when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the indexes associated with the available servers:

# Server Variables
0 https://api.openai.com/v1 None
Example
package main

import (
	"context"
	openaigosdk "github.com/speakeasy-sdks/openai-go-sdk/v4"
	"github.com/speakeasy-sdks/openai-go-sdk/v4/pkg/models/shared"
	"log"
)

func main() {
	s := openaigosdk.New(
		openaigosdk.WithServerIndex(0),
		openaigosdk.WithSecurity("<YOUR_BEARER_TOKEN_HERE>"),
	)

	var runID string = "<value>"

	var threadID string = "<value>"

	ctx := context.Background()
	res, err := s.Assistants.CancelRun(ctx, runID, threadID)
	if err != nil {
		log.Fatal(err)
	}

	if res.RunObject != nil {
		// handle response
	}
}

Override Server URL Per-Client

The default server can also be overridden globally using the WithServerURL option when initializing the SDK client instance. For example:

package main

import (
	"context"
	openaigosdk "github.com/speakeasy-sdks/openai-go-sdk/v4"
	"github.com/speakeasy-sdks/openai-go-sdk/v4/pkg/models/shared"
	"log"
)

func main() {
	s := openaigosdk.New(
		openaigosdk.WithServerURL("https://api.openai.com/v1"),
		openaigosdk.WithSecurity("<YOUR_BEARER_TOKEN_HERE>"),
	)

	var runID string = "<value>"

	var threadID string = "<value>"

	ctx := context.Background()
	res, err := s.Assistants.CancelRun(ctx, runID, threadID)
	if err != nil {
		log.Fatal(err)
	}

	if res.RunObject != nil {
		// handle response
	}
}

Custom HTTP Client

The Go SDK makes API calls that wrap an internal HTTP client. The requirements for the HTTP client are very simple. It must match this interface:

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

The built-in net/http client satisfies this interface and a default client based on the built-in is provided by default. To replace this default with a client of your own, you can implement this interface yourself or provide your own client configured as desired. Here's a simple example, which adds a client with a 30 second timeout.

import (
	"net/http"
	"time"
	"github.com/myorg/your-go-sdk"
)

var (
	httpClient = &http.Client{Timeout: 30 * time.Second}
	sdkClient  = sdk.New(sdk.WithClient(httpClient))
)

This can be a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration.

Special Types

Authentication

Per-Client Security Schemes

This SDK supports the following security scheme globally:

Name Type Scheme
APIKeyAuth http HTTP Bearer

You can configure it using the WithSecurity option when initializing the SDK client instance. For example:

package main

import (
	"context"
	openaigosdk "github.com/speakeasy-sdks/openai-go-sdk/v4"
	"log"
)

func main() {
	s := openaigosdk.New(
		openaigosdk.WithSecurity("<YOUR_BEARER_TOKEN_HERE>"),
	)

	var runID string = "<value>"

	var threadID string = "<value>"

	ctx := context.Background()
	res, err := s.Assistants.CancelRun(ctx, runID, threadID)
	if err != nil {
		log.Fatal(err)
	}

	if res.RunObject != nil {
		// handle response
	}
}

SDK Generated by Speakeasy

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ServerList = []string{
	"https://api.openai.com/v1",
}

ServerList contains the list of servers available to the SDK

Functions

func Bool

func Bool(b bool) *bool

Bool provides a helper function to return a pointer to a bool

func Float32

func Float32(f float32) *float32

Float32 provides a helper function to return a pointer to a float32

func Float64

func Float64(f float64) *float64

Float64 provides a helper function to return a pointer to a float64

func Int

func Int(i int) *int

Int provides a helper function to return a pointer to an int

func Int64

func Int64(i int64) *int64

Int64 provides a helper function to return a pointer to an int64

func String

func String(s string) *string

String provides a helper function to return a pointer to a string

Types

type Assistants

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

Build Assistants that can call models and use tools.

func (*Assistants) CancelRun

func (s *Assistants) CancelRun(ctx context.Context, runID string, threadID string) (*operations.CancelRunResponse, error)

CancelRun - Cancels a run that is `in_progress`.

func (*Assistants) CreateAssistant

CreateAssistant - Create an assistant with a model and instructions.

func (*Assistants) CreateAssistantFile

func (s *Assistants) CreateAssistantFile(ctx context.Context, createAssistantFileRequest shared.CreateAssistantFileRequest, assistantID string) (*operations.CreateAssistantFileResponse, error)

CreateAssistantFile - Create an assistant file by attaching a [File](/docs/api-reference/files) to an [assistant](/docs/api-reference/assistants).

func (*Assistants) CreateMessage

func (s *Assistants) CreateMessage(ctx context.Context, createMessageRequest shared.CreateMessageRequest, threadID string) (*operations.CreateMessageResponse, error)

CreateMessage - Create a message.

func (*Assistants) CreateRun

func (s *Assistants) CreateRun(ctx context.Context, createRunRequest shared.CreateRunRequest, threadID string) (*operations.CreateRunResponse, error)

CreateRun - Create a run.

func (*Assistants) CreateThread

CreateThread - Create a thread.

func (*Assistants) CreateThreadAndRun

CreateThreadAndRun - Create a thread and run it in one request.

func (*Assistants) DeleteAssistant

func (s *Assistants) DeleteAssistant(ctx context.Context, assistantID string) (*operations.DeleteAssistantResponse, error)

DeleteAssistant - Delete an assistant.

func (*Assistants) DeleteAssistantFile

func (s *Assistants) DeleteAssistantFile(ctx context.Context, assistantID string, fileID string) (*operations.DeleteAssistantFileResponse, error)

DeleteAssistantFile - Delete an assistant file.

func (*Assistants) DeleteThread

func (s *Assistants) DeleteThread(ctx context.Context, threadID string) (*operations.DeleteThreadResponse, error)

DeleteThread - Delete a thread.

func (*Assistants) GetAssistant

func (s *Assistants) GetAssistant(ctx context.Context, assistantID string) (*operations.GetAssistantResponse, error)

GetAssistant - Retrieves an assistant.

func (*Assistants) GetAssistantFile

func (s *Assistants) GetAssistantFile(ctx context.Context, assistantID string, fileID string) (*operations.GetAssistantFileResponse, error)

GetAssistantFile - Retrieves an AssistantFile.

func (*Assistants) GetMessage

func (s *Assistants) GetMessage(ctx context.Context, messageID string, threadID string) (*operations.GetMessageResponse, error)

GetMessage - Retrieve a message.

func (*Assistants) GetMessageFile

func (s *Assistants) GetMessageFile(ctx context.Context, fileID string, messageID string, threadID string) (*operations.GetMessageFileResponse, error)

GetMessageFile - Retrieves a message file.

func (*Assistants) GetRun

func (s *Assistants) GetRun(ctx context.Context, runID string, threadID string) (*operations.GetRunResponse, error)

GetRun - Retrieves a run.

func (*Assistants) GetRunStep

func (s *Assistants) GetRunStep(ctx context.Context, runID string, stepID string, threadID string) (*operations.GetRunStepResponse, error)

GetRunStep - Retrieves a run step.

func (*Assistants) GetThread

func (s *Assistants) GetThread(ctx context.Context, threadID string) (*operations.GetThreadResponse, error)

GetThread - Retrieves a thread.

func (*Assistants) ListAssistantFiles

ListAssistantFiles - Returns a list of assistant files.

func (*Assistants) ListAssistants

func (s *Assistants) ListAssistants(ctx context.Context, after *string, before *string, limit *int64, order *operations.QueryParamOrder) (*operations.ListAssistantsResponse, error)

ListAssistants - Returns a list of assistants.

func (*Assistants) ListMessageFiles

ListMessageFiles - Returns a list of message files.

func (*Assistants) ListMessages

ListMessages - Returns a list of messages for a given thread.

func (*Assistants) ListRunSteps

ListRunSteps - Returns a list of run steps belonging to a run.

func (*Assistants) ListRuns

ListRuns - Returns a list of runs belonging to a thread.

func (*Assistants) ModifyAssistant

func (s *Assistants) ModifyAssistant(ctx context.Context, modifyAssistantRequest shared.ModifyAssistantRequest, assistantID string) (*operations.ModifyAssistantResponse, error)

ModifyAssistant - Modifies an assistant.

func (*Assistants) ModifyMessage

func (s *Assistants) ModifyMessage(ctx context.Context, modifyMessageRequest shared.ModifyMessageRequest, messageID string, threadID string) (*operations.ModifyMessageResponse, error)

ModifyMessage - Modifies a message.

func (*Assistants) ModifyRun

func (s *Assistants) ModifyRun(ctx context.Context, modifyRunRequest shared.ModifyRunRequest, runID string, threadID string) (*operations.ModifyRunResponse, error)

ModifyRun - Modifies a run.

func (*Assistants) ModifyThread

func (s *Assistants) ModifyThread(ctx context.Context, modifyThreadRequest shared.ModifyThreadRequest, threadID string) (*operations.ModifyThreadResponse, error)

ModifyThread - Modifies a thread.

func (*Assistants) SubmitToolOuputsToRun

func (s *Assistants) SubmitToolOuputsToRun(ctx context.Context, submitToolOutputsRunRequest shared.SubmitToolOutputsRunRequest, runID string, threadID string) (*operations.SubmitToolOuputsToRunResponse, error)

SubmitToolOuputsToRun - When a run has the `status: "requires_action"` and `required_action.type` is `submit_tool_outputs`, this endpoint can be used to submit the outputs from the tool calls once they're all completed. All outputs must be submitted in a single request.

type Audio

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

Audio - Learn how to turn audio into text or text into audio.

func (*Audio) CreateSpeech

CreateSpeech - Generates audio from the input text.

func (*Audio) CreateTranscription

CreateTranscription - Transcribes audio into the input language.

func (*Audio) CreateTranslation

CreateTranslation - Translates audio into English.

type Chat

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

Chat - Given a list of messages comprising a conversation, the model will return a response.

func (*Chat) CreateChatCompletion

CreateChatCompletion - Creates a model response for the given chat conversation.

type Completions

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

Completions - Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.

func (*Completions) CreateCompletion

CreateCompletion - Creates a completion for the provided prompt and parameters.

type Embeddings

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

Embeddings - Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.

func (*Embeddings) CreateEmbedding

CreateEmbedding - Creates an embedding vector representing the input text.

type Files

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

Files are used to upload documents that can be used with features like Assistants and Fine-tuning.

func (*Files) CreateFile

CreateFile - Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB.

The size of individual files can be a maximum of 512 MB or 2 million tokens for Assistants. See the [Assistants Tools guide](/docs/assistants/tools) to learn more about the types of files supported. The Fine-tuning API only supports `.jsonl` files.

Please [contact us](https://help.openai.com/) if you need to increase these storage limits.

func (*Files) DeleteFile

func (s *Files) DeleteFile(ctx context.Context, fileID string) (*operations.DeleteFileResponse, error)

DeleteFile - Delete a file.

func (*Files) DownloadFile

func (s *Files) DownloadFile(ctx context.Context, fileID string) (*operations.DownloadFileResponse, error)

DownloadFile - Returns the contents of the specified file.

func (*Files) ListFiles

func (s *Files) ListFiles(ctx context.Context, purpose *string) (*operations.ListFilesResponse, error)

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

func (*Files) RetrieveFile

func (s *Files) RetrieveFile(ctx context.Context, fileID string) (*operations.RetrieveFileResponse, error)

RetrieveFile - Returns information about a specific file.

type FineTuning

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

FineTuning - Manage fine-tuning jobs to tailor a model to your specific training data.

func (*FineTuning) CancelFineTuningJob

func (s *FineTuning) CancelFineTuningJob(ctx context.Context, fineTuningJobID string) (*operations.CancelFineTuningJobResponse, error)

CancelFineTuningJob - Immediately cancel a fine-tune job.

func (*FineTuning) CreateFineTuningJob

CreateFineTuningJob - Creates a fine-tuning job which begins the process of creating a new 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)

func (*FineTuning) ListFineTuningEvents

func (s *FineTuning) ListFineTuningEvents(ctx context.Context, fineTuningJobID string, after *string, limit *int64) (*operations.ListFineTuningEventsResponse, error)

ListFineTuningEvents - Get status updates for a fine-tuning job.

func (*FineTuning) ListPaginatedFineTuningJobs

func (s *FineTuning) ListPaginatedFineTuningJobs(ctx context.Context, after *string, limit *int64) (*operations.ListPaginatedFineTuningJobsResponse, error)

ListPaginatedFineTuningJobs - List your organization's fine-tuning jobs

func (*FineTuning) RetrieveFineTuningJob

func (s *FineTuning) RetrieveFineTuningJob(ctx context.Context, fineTuningJobID string) (*operations.RetrieveFineTuningJobResponse, error)

RetrieveFineTuningJob - Get info about a fine-tuning job.

[Learn more about fine-tuning](/docs/guides/fine-tuning)

type Gpt

type Gpt struct {
	// Build Assistants that can call models and use tools.
	Assistants *Assistants
	// Learn how to turn audio into text or text into audio.
	Audio *Audio
	// Given a list of messages comprising a conversation, the model will return a response.
	Chat *Chat
	// Given a prompt, the model will return one or more predicted completions, and can also return the probabilities of alternative tokens at each position.
	Completions *Completions
	// Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
	Embeddings *Embeddings
	// Files are used to upload documents that can be used with features like Assistants and Fine-tuning.
	Files *Files
	// Manage fine-tuning jobs to tailor a model to your specific training data.
	FineTuning *FineTuning
	// Given a prompt and/or an input image, the model will generate a new image.
	Images *Images
	// List and describe the various models available in the API.
	Models *Models
	// Given a input text, outputs if the model classifies it as violating OpenAI's content policy.
	Moderations *Moderations
	// contains filtered or unexported fields
}

Gpt - OpenAI API: The OpenAI REST API. Please see https://platform.openai.com/docs/api-reference for more details.

func New

func New(opts ...SDKOption) *Gpt

New creates a new instance of the SDK with the provided options

type HTTPClient

type HTTPClient interface {
	Do(req *http.Request) (*http.Response, error)
}

HTTPClient provides an interface for suplying the SDK with a custom HTTP client

type Images

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

Images - Given a prompt and/or an input image, the model will generate a new image.

func (*Images) CreateImage

CreateImage - Creates an image given a prompt.

func (*Images) CreateImageEdit

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

func (*Images) CreateImageVariation

CreateImageVariation - Creates a variation of a given image.

type Models

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

Models - List and describe the various models available in the API.

func (*Models) DeleteModel

func (s *Models) DeleteModel(ctx context.Context, model string) (*operations.DeleteModelResponse, error)

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

func (*Models) ListModels

func (s *Models) ListModels(ctx context.Context) (*operations.ListModelsResponse, error)

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

func (*Models) RetrieveModel

func (s *Models) RetrieveModel(ctx context.Context, model string) (*operations.RetrieveModelResponse, error)

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

type Moderations

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

Moderations - Given a input text, outputs if the model classifies it as violating OpenAI's content policy.

func (*Moderations) CreateModeration

CreateModeration - Classifies if text violates OpenAI's Content Policy

type SDKOption

type SDKOption func(*Gpt)

func WithClient

func WithClient(client HTTPClient) SDKOption

WithClient allows the overriding of the default HTTP client used by the SDK

func WithRetryConfig

func WithRetryConfig(retryConfig utils.RetryConfig) SDKOption

func WithSecurity

func WithSecurity(apiKeyAuth string) SDKOption

WithSecurity configures the SDK to use the provided security details

func WithSecuritySource

func WithSecuritySource(security func(context.Context) (shared.Security, error)) SDKOption

WithSecuritySource configures the SDK to invoke the Security Source function on each method call to determine authentication

func WithServerIndex

func WithServerIndex(serverIndex int) SDKOption

WithServerIndex allows the overriding of the default server by index

func WithServerURL

func WithServerURL(serverURL string) SDKOption

WithServerURL allows the overriding of the default server URL

func WithTemplatedServerURL

func WithTemplatedServerURL(serverURL string, params map[string]string) SDKOption

WithTemplatedServerURL allows the overriding of the default server URL with a templated URL populated with the provided parameters

Directories

Path Synopsis
internal
pkg

Jump to

Keyboard shortcuts

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