/openai-go-sdk

OpenAI ChatGPT, GPT-3, GPT-4, DALL·E, API wrapper for Go

Primary LanguageGoMIT LicenseMIT

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

  • CreateCompletion - Creates a completion for the provided prompt and parameters.
  • CreateEmbedding - Creates an embedding vector representing the input text.
  • 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.

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

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

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