### List and Get Models with Go OpenAI Source: https://context7.com/sashabaranov/go-openai/llms.txt This Go example shows how to retrieve a list of all available models from OpenAI and also how to fetch detailed information about a specific model. It's useful for understanding model capabilities and selecting the appropriate one for your tasks. Requires an API key. ```Go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") // List all available models models, err := client.ListModels(context.Background()) if err != nil { fmt.Printf("List models error: %v\n", err) return } fmt.Println("Available models:") for _, model := range models.Models { fmt.Printf("- %s (owned by: %s)\n", model.ID, model.OwnedBy) } // Get specific model details model, _ := client.GetModel(context.Background(), "gpt-4o") fmt.Printf("\nModel: %s\nOwned by: %s\n", model.ID, model.OwnedBy) } ``` -------------------------------- ### Fine Tune Model Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This example shows the basic setup for fine-tuning a model using the go-openai library. It includes comments on preparing training data in JSONL format. ```APIDOC ## Fine Tune Model ### Description This example provides a starting point for fine-tuning an OpenAI model using the `go-openai` library. It highlights the need for training data formatted in JSON Lines (JSONL) format. ### Prerequisites - A valid OpenAI API token. - Training data prepared in JSONL format. ### Training Data Format (JSONL) Each line in the `.jsonl` file should be a JSON object representing a training example. For conversational models, the format is typically: ```json {"prompt": "", "completion": ""} {"prompt": "", "completion": ""} {"prompt": "", "completion": ""} ``` ### Code Example ```go package main import ( "context" "fmt" "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your token") ctx := context.Background() // Create a .jsonl file with your training data for conversational model // {"prompt": "", "completion": ""} // {"prompt": "", "completion": ""} // {"prompt": "", "completion": ""} // TODO: Implement file upload and fine-tuning job creation using the client. // Example (conceptual - actual API calls will vary): // file, err := os.Open("path/to/your/training_data.jsonl") // if err != nil { // log.Fatalf("Error opening file: %v", err) // } // defer file.Close() // fileResponse, err := client.CreateFile(ctx, file, openai.FilePurposeFineTune) // if err != nil { // log.Fatalf("Error uploading file: %v", err) // } // fmt.Printf("File uploaded successfully, ID: %s\n", fileResponse.ID) // createFineTuneRequest := openai.FineTuneRequest{ // TrainingFile: fileResponse.ID, // Model: openai.GPT3Dot5Turbo, // } // fineTuneResponse, err := client.CreateFineTune(ctx, createFineTuneRequest) // if err != nil { // log.Fatalf("Error creating fine tune job: %v", err) // } // fmt.Printf("Fine tune job created successfully, ID: %s\n", fineTuneResponse.ID) } ``` ``` -------------------------------- ### Install Go OpenAI Library Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This command installs the go-openai library using the Go package manager. It requires Go version 1.18 or greater. ```bash go get github.com/sashabaranov/go-openai ``` -------------------------------- ### Fine Tune Model with go-openai Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go code snippet shows the initial setup for fine-tuning a model using the go-openai library. It includes creating an OpenAI client with an API key and setting up a background context. The comment indicates the need for a `.jsonl` file containing training data in a specific prompt-completion format. ```Go package main import ( "context" "fmt" "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your token") ctx := context.Background() // create a .jsonl file with your training data for conversational model // {"prompt": "", "completion": ""} // {"prompt": "", "completion": ""} // {"prompt": "", "completion": ""} } ``` -------------------------------- ### Go: Structured Outputs with JSON Schema Source: https://context7.com/sashabaranov/go-openai/llms.txt Shows how to generate responses that conform to a specific JSON schema using the ResponseFormat parameter. This example demonstrates solving math problems and structuring the output with steps and a final answer. ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" "github.com/sashabaranov/go-openai/jsonschema" ) func main() { client := openai.NewClient("your-api-key") type MathSolution struct { Steps []struct { Explanation string `json:"explanation"` Output string `json:"output"` } `json:"steps"` FinalAnswer string `json:"final_answer"` } var result MathSolution schema, _ := jsonschema.GenerateSchemaForType(result) sp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT4oMini, Messages: []openai.ChatCompletionMessage{ {Role: openai.ChatMessageRoleSystem, Content: "Solve math problems step by step."}, {Role: openai.ChatMessageRoleUser, Content: "Solve: 8x + 7 = -23"}, }, ResponseFormat: &openai.ChatCompletionResponseFormat{ Type: openai.ChatCompletionResponseFormatTypeJSONSchema, JSONSchema: &openai.ChatCompletionResponseFormatJSONSchema{ Name: "math_solution", Schema: schema, Strict: true, }, }, }, ) if err != nil { fmt.Printf("Error: %v\n", err) return } _ = schema.Unmarshal(resp.Choices[0].Message.Content, &result) fmt.Printf("Final Answer: %s\n", result.FinalAnswer) } ``` -------------------------------- ### ChatGPT Example Usage in Go Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Demonstrates how to use the go-openai library to send a message to the ChatGPT API and receive a response. It initializes a client with an API key and makes a CreateChatCompletion request. ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your token") resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, Messages: []openai.ChatCompletionMessage{ { Role: openai.ChatMessageRoleUser, Content: "Hello!", }, }, }, ) if err != nil { fmt.Printf("ChatCompletion error: %v\n", err) return } fmt.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### Create, List, and Get Files with Go OpenAI Source: https://context7.com/sashabaranov/go-openai/llms.txt Demonstrates how to upload files to OpenAI for fine-tuning or other purposes, list all uploaded files, and retrieve the content of a specific file using the go-openai library. Requires an API key and a local file named 'training_data.jsonl'. ```Go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") // Upload a file file, err := client.CreateFile( context.Background(), openai.FileRequest{ FilePath: "training_data.jsonl", Purpose: string(openai.PurposeFineTune), }, ) if err != nil { fmt.Printf("Upload error: %v\n", err) return } fmt.Printf("Uploaded file ID: %s\n", file.ID) // List all files files, _ := client.ListFiles(context.Background()) for _, f := range files.Files { fmt.Printf("File: %s (%s) - %d bytes\n", f.FileName, f.Purpose, f.Bytes) } // Get file content content, _ := client.GetFileContent(context.Background(), file.ID) defer content.Close() } ``` -------------------------------- ### GPT-3 Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Demonstrates how to get a standard text completion using GPT-3 models like Babbage. ```APIDOC ## POST /v1/completions ### Description This endpoint generates text completions for a given prompt using various GPT-3 models. ### Method POST ### Endpoint /v1/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for completion (e.g., "text-davinci-003"). - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **prompt** (string) - Required - The prompt that the model will complete. ### Request Example ```json { "model": "gpt-3.5-turbo", "max_tokens": 5, "prompt": "Lorem ipsum" } ``` ### Response #### Success Response (200) - **choices** (array) - A list of completion choices. Each choice contains: - **text** (string) - The generated completion text. #### Response Example ```json { "choices": [ { "text": " This is a completion." } ] } ``` ``` -------------------------------- ### Go: Image Editing with Mask Source: https://context7.com/sashabaranov/go-openai/llms.txt Edits an existing image based on a text prompt and an optional mask. This example demonstrates how to provide image and mask files for the editing process. ```go package main import ( "context" "fmt" "os" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") imageFile, _ := os.Open("original.png") defer imageFile.Close() maskFile, _ := os.Open("mask.png") defer maskFile.Close() sp, err := client.CreateEditImage( context.Background(), openai.ImageEditRequest{ Image: imageFile, Mask: maskFile, Prompt: "Add a red hat to the person", N: 1, Size: openai.CreateImageSize1024x1024, ResponseFormat: openai.CreateImageResponseFormatURL, }, ) if err != nil { fmt.Printf("Image edit error: %v\n", err) return } fmt.Printf("Edited Image URL: %s\n", resp.Data[0].URL) } ``` -------------------------------- ### Create Embeddings Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This example demonstrates how to create embeddings for a given text using the go-openai library. It includes calculating the similarity between two text inputs. ```APIDOC ## POST /v1/embeddings ### Description Creates embeddings for a given text input. This is useful for semantic search, clustering, and other NLP tasks. ### Method POST ### Endpoint /v1/embeddings ### Parameters #### Request Body - **model** (string) - Required - The model to use for embedding. Example: `text-embedding-ada-002` - **input** (array of strings) - Required - The input text(s) to embed. ### Request Example ```json { "model": "text-embedding-ada-002", "input": ["How many chucks would a woodchuck chuck if the woodchuck could chuck wood"] } ``` ### Response #### Success Response (200) - **data** (array of objects) - Contains the embedding data for each input string. - **embedding** (array of floats) - The embedding vector. - **index** (integer) - The index of the input string. - **model** (string) - The model used for embedding. - **object** (string) - The object type, usually "list". - **usage** (object) - Usage statistics for the request. - **prompt_tokens** (integer) - The number of tokens in the prompt. - **total_tokens** (integer) - The total number of tokens. #### Response Example ```json { "data": [ { "embedding": [ 0.0023259135, -0.007711188, -0.0007711188, ... ], "index": 0 } ], "model": "text-embedding-ada-002", "object": "list", "usage": { "prompt_tokens": 1, "total_tokens": 1 } } ``` ``` -------------------------------- ### Go: Image Generation with DALL-E 3 Source: https://context7.com/sashabaranov/go-openai/llms.txt Generates images using the DALL-E 3 model based on a text prompt. This example shows how to specify image size, quality, style, and response format. ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") // DALL-E 3 image generation sp, err := client.CreateImage( context.Background(), openai.ImageRequest{ Prompt: "A serene Japanese garden with cherry blossoms, digital art", Model: openai.CreateImageModelDallE3, N: 1, Size: openai.CreateImageSize1024x1024, Quality: openai.CreateImageQualityHD, Style: openai.CreateImageStyleVivid, ResponseFormat: openai.CreateImageResponseFormatURL, }, ) if err != nil { fmt.Printf("Image creation error: %v\n", err) return } fmt.Printf("Image URL: %s\n", resp.Data[0].URL) fmt.Printf("Revised Prompt: %s\n", resp.Data[0].RevisedPrompt) } ``` -------------------------------- ### Format Code with goimports Source: https://github.com/sashabaranov/go-openai/blob/master/CONTRIBUTING.md Installs and runs the goimports tool to format Go code according to project conventions. This ensures consistency across the codebase. ```bash go install org/golang-tools/cmd/goimports@latest goimports -w . ``` -------------------------------- ### Azure OpenAI Embeddings Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This example shows how to use the go-openai library with Azure OpenAI services for creating embeddings. It includes configuration for Azure endpoints and keys. ```APIDOC ## Azure OpenAI Embeddings ### Description This example demonstrates how to configure and use the go-openai client with Azure OpenAI services to create text embeddings. It covers setting up the Azure configuration, including API key and endpoint, and optionally mapping deployment names. ### Method POST ### Endpoint /openai/deployments/{your-deployment-id}/embeddings?api-version=2023-05-15 ### Parameters #### Request Body - **input** (array of strings) - Required - The input text(s) to embed. - **model** (string) - Required - The model to use for embedding. Example: `text-embedding-ada-002` ### Request Example ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { config := openai.DefaultAzureConfig("your Azure OpenAI Key", "https://your Azure OpenAI Endpoint") config.APIVersion = "2023-05-15" // optional update to latest API version // If you use a deployment name different from the model name, you can customize the AzureModelMapperFunc function // config.AzureModelMapperFunc = func(model string) string { // azureModelMapping := map[string]string{ // "gpt-3.5-turbo":"your gpt-3.5-turbo deployment name", // } // return azureModelMapping[model] // } input := "Text to vectorize" client := openai.NewClientWithConfig(config) resp, err := client.CreateEmbeddings( context.Background(), openai.EmbeddingRequest{ Input: []string{input}, Model: openai.AdaEmbeddingV2, }) if err != nil { fmt.Printf("CreateEmbeddings error: %v\n", err) return } vectors := resp.Data[0].Embedding // []float32 with 1536 dimensions fmt.Println(vectors[:10], "...", vectors[len(vectors)-10:]) } ``` ### Response #### Success Response (200) - **data** (array of objects) - Contains the embedding data for each input string. - **embedding** (array of floats) - The embedding vector. - **index** (integer) - The index of the input string. - **model** (string) - The model used for embedding. - **object** (string) - The object type, usually "list". - **usage** (object) - Usage statistics for the request. - **prompt_tokens** (integer) - The number of tokens in the prompt. - **total_tokens** (integer) - The total number of tokens. #### Response Example ```json { "data": [ { "embedding": [ 0.0023259135, -0.007711188, -0.0007711188, ... ], "index": 0 } ], "model": "text-embedding-ada-002", "object": "list", "usage": { "prompt_tokens": 1, "total_tokens": 1 } } ``` ``` -------------------------------- ### GPT-3 Streaming Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Demonstrates how to get a streaming response for text completions using GPT-3 models. ```APIDOC ## POST /v1/completions (Streaming) ### Description This endpoint allows for streaming text completions, providing responses token by token. ### Method POST ### Endpoint /v1/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for completion (e.g., "text-davinci-003"). - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **prompt** (string) - Required - The prompt that the model will complete. - **stream** (boolean) - Required - Whether to stream back chunks of the generated completion. ### Request Example ```json { "model": "gpt-3.5-turbo", "max_tokens": 5, "prompt": "Lorem ipsum", "stream": true } ``` ### Response #### Success Response (200) - **choices** (array) - A list of completion choices. Each choice contains: - **text** (string) - The generated completion text. #### Response Example ```json { "choices": [ { "text": " This is a streamed completion." } ] } ``` ``` -------------------------------- ### Go GPT-3 Streaming Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go example demonstrates how to receive streaming text completions from the GPT-3 API using the go-openai library. It configures a completion request with the `Stream` option set to true and then processes the response chunks as they arrive, printing each part of the stream. The code includes error handling for both the initial request and stream reception. ```go package main import ( "errors" "context" "fmt" "io" openai "github.com/sashabaranov/go-openai" ) func main() { c := openai.NewClient("your token") ctx := context.Background() req := openai.CompletionRequest{ Model: openai.GPT3Babbage002, MaxTokens: 5, Prompt: "Lorem ipsum", Stream: true, } stream, err := c.CreateCompletionStream(ctx, req) if err != nil { fmt.Printf("CompletionStream error: %v\n", err) return } defer stream.Close() for { response, err := stream.Recv() if errors.Is(err, io.EOF) { fmt.Println("Stream finished") return } if err != nil { fmt.Printf("Stream error: %v\n", err) return } fmt.Printf("Stream response: %v\n", response) } } ``` -------------------------------- ### Lint Code with golangci-lint Source: https://github.com/sashabaranov/go-openai/blob/master/CONTRIBUTING.md Installs and runs the golangci-lint tool to check for syntax, style issues, and potential bugs in the Go code. It helps maintain code quality and adherence to best practices. ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest golangci-lint run --out-format=github-actions ``` -------------------------------- ### Error Handling Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This example demonstrates how to handle API errors returned by the OpenAI API using the go-openai library. It shows how to inspect error types and status codes for appropriate retry logic. ```APIDOC ## Error Handling ### Description OpenAI provides clear documentation on how to handle API errors. The `go-openai` library allows you to inspect the `openai.APIError` type to determine the nature of the error and implement appropriate retry strategies. ### Error Inspection Errors can be checked using `errors.As` to determine if the error is an `openai.APIError`. This allows you to access details like the HTTP status code. ### Example Error Handling Logic ```go import ( "errors" openai "github.com/sashabaranov/go-openai" ) // ... inside your error handling block ... e := &openai.APIError{} if errors.As(err, &e) { switch e.HTTPStatusCode { case 401: // invalid auth or key (do not retry) // Handle authentication or key errors case 429: // rate limiting or engine overload (wait and retry) // Implement exponential backoff or wait before retrying case 500: // openai server error (retry) // Retry the request after a short delay default: // unhandled error status code // Handle other unexpected status codes } } else { // Handle non-API errors } ``` ``` -------------------------------- ### Function Calling JSON Schema Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This example illustrates how to define a JSON schema for function calling in the OpenAI API. It shows the structure for describing function names, descriptions, parameters, and their types. ```APIDOC ## Function Calling JSON Schema ### Description To enable chat completions to call functions for additional information, a JSON schema must be provided. This schema describes the available functions and their parameters. The `go-openai` library provides a `jsonschema` package to help construct these schemas. ### Parameters - **name** (string) - Required - The name of the function to be called. - **description** (string) - Optional - A description of what the function does, used by the model to decide when to call the function. - **parameters** (object) - Required - The parameters the function accepts, described as a JSON Schema object. - **type** (string) - Must be "object". - **properties** (object) - A map of parameter names to their schema definitions. - **param_name** (object) - Schema definition for a specific parameter. - **type** (string) - The data type of the parameter (e.g., "string", "integer", "boolean"). - **description** (string) - A description of the parameter. - **enum** (array of strings) - Optional - A list of allowed values for the parameter. - **required** (array of strings) - Optional - A list of parameter names that are required. ### Example Schema (JSON) ```json { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA" }, "unit": { "type": "string", "enum": [ "celsius", "fahrenheit" ] } }, "required": [ "location" ] } } ``` ### Example Schema (Go Struct using jsonschema package) ```go FunctionDefinition{ Name: "get_current_weather", Parameters: jsonschema.Definition{ Type: jsonschema.Object, Properties: map[string]jsonschema.Definition{ "location": { Type: jsonschema.String, Description: "The city and state, e.g. San Francisco, CA", }, "unit": { Type: jsonschema.String, Enum: []string{"celsius", "fahrenheit"}, }, }, Required: []string{"location"}, }, } ``` ``` -------------------------------- ### Go DALL-E 2 Image Generation Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go code snippet shows how to generate images using DALL-E 2 via the go-openai library. It provides examples for generating images as URLs and as base64 encoded JSON. The code initializes the client, defines image requests with prompts, sizes, and desired response formats, and handles the responses, including decoding base64 images into PNG format. Error handling is implemented for API calls and data processing. ```go package main import ( "bytes" "context" "encoding/base64" "fmt" openai "github.com/sashabaranov/go-openai" "image/png" "os" ) func main() { c := openai.NewClient("your token") ctx := context.Background() // Sample image by link reqUrl := openai.ImageRequest{ Prompt: "Parrot on a skateboard performs a trick, cartoon style, natural light, high detail", Size: openai.CreateImageSize256x256, ResponseFormat: openai.CreateImageResponseFormatURL, N: 1, } respUrl, err := c.CreateImage(ctx, reqUrl) if err != nil { fmt.Printf("Image creation error: %v\n", err) return } fmt.Println(respUrl.Data[0].URL) // Example image as base64 reqBase64 := openai.ImageRequest{ Prompt: "Portrait of a humanoid parrot in a classic costume, high detail, realistic light, unreal engine", Size: openai.CreateImageSize256x256, ResponseFormat: openai.CreateImageResponseFormatB64JSON, N: 1, } respBase64, err := c.CreateImage(ctx, reqBase64) if err != nil { fmt.Printf("Image creation error: %v\n", err) return } imgBytes, err := base64.StdEncoding.DecodeString(respBase64.Data[0].B64JSON) if err != nil { fmt.Printf("Base64 decode error: %v\n", err) return } r := bytes.NewReader(imgBytes) imgData, err := png.Decode(r) if err != nil { fmt.Printf("PNG decode error: %v\n", err) return } file, err := os.Create("example.png") ``` -------------------------------- ### Go ChatGPT Streaming Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go code snippet demonstrates how to get a streaming response for chat completions using the go-openai library. It sets up a client, defines a chat completion request with streaming enabled, and iterates through the stream to print the content chunks as they arrive. It handles potential errors and the end-of-file condition. ```go package main import ( "context" "errors" "fmt" "io" openai "github.com/sashabaranov/go-openai" ) func main() { c := openai.NewClient("your token") ctx := context.Background() req := openai.ChatCompletionRequest{ Model: openai.GPT3Dot5Turbo, MaxTokens: 20, Messages: []openai.ChatCompletionMessage{ { Role: openai.ChatMessageRoleUser, Content: "Lorem ipsum", }, }, Stream: true, } stream, err := c.CreateChatCompletionStream(ctx, req) if err != nil { fmt.Printf("ChatCompletionStream error: %v\n", err) return } defer stream.Close() fmt.Printf("Stream response: ") for { response, err := stream.Recv() if errors.Is(err, io.EOF) { fmt.Println("\nStream finished") return } if err != nil { fmt.Printf("\nStream error: %v\n", err) return } fmt.Printf(response.Choices[0].Delta.Content) } } ``` -------------------------------- ### Initialize OpenAI Client Source: https://context7.com/sashabaranov/go-openai/llms.txt Demonstrates how to instantiate a new OpenAI client using an API key and perform a basic chat completion request. ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") resp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT4oMini, Messages: []openai.ChatCompletionMessage{ {Role: openai.ChatMessageRoleUser, Content: "Hello!"}, }, }, ) if err != nil { fmt.Printf("Error: %v\n", err) return } fmt.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### Create and List Assistants with Go OpenAI Source: https://context7.com/sashabaranov/go-openai/llms.txt This Go snippet demonstrates how to create an AI assistant with specific instructions and tools, and then list available assistants. It utilizes the Assistants API for creating intelligent agents. Requires an API key. ```Go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") name := "Math Tutor" instructions := "You are a helpful math tutor. Guide users through problems step by step." assistant, err := client.CreateAssistant( context.Background(), openai.AssistantRequest{ Model: openai.GPT4o, Name: &name, Instructions: &instructions, Tools: []openai.AssistantTool{ {Type: openai.AssistantToolTypeCodeInterpreter}, }, }, ) if err != nil { fmt.Printf("Create assistant error: %v\n", err) return } fmt.Printf("Assistant ID: %s\n", assistant.ID) fmt.Printf("Name: %s\n", *assistant.Name) // List assistants limit := 10 assistants, _ := client.ListAssistants(context.Background(), &limit, nil, nil, nil) for _, a := range assistants.Assistants { fmt.Printf("Assistant: %s - %s\n", a.ID, *a.Name) } } ``` -------------------------------- ### ChatGPT Streaming Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Demonstrates how to get a streaming response for chat completions using GPT-3.5 Turbo. ```APIDOC ## POST /v1/chat/completions (Streaming) ### Description This endpoint allows for streaming chat completions, providing responses token by token. ### Method POST ### Endpoint /v1/chat/completions ### Parameters #### Request Body - **model** (string) - Required - The model to use for completion (e.g., "gpt-3.5-turbo"). - **max_tokens** (integer) - Optional - The maximum number of tokens to generate. - **messages** (array) - Required - A list of messages comprising the conversation so far. - **role** (string) - Required - The role of the author of the message (e.g., "user", "assistant"). - **content** (string) - Required - The content of the message. - **stream** (boolean) - Required - Whether to stream back chunks of the generated completion so as to be sent more than one chunk for a given request. ### Request Example ```json { "model": "gpt-3.5-turbo", "max_tokens": 20, "messages": [ { "role": "user", "content": "Lorem ipsum" } ], "stream": true } ``` ### Response #### Success Response (200) - **choices** (array) - A list of choices. Each choice contains: - **delta** (object) - The delta content of the message. - **content** (string) - The content of the message. #### Response Example ```json { "choices": [ { "delta": { "content": "This is a streamed response." } } ] } ``` ``` -------------------------------- ### Configure Advanced Client Settings Source: https://context7.com/sashabaranov/go-openai/llms.txt Shows how to use NewClientWithConfig to set up custom HTTP proxies, Azure OpenAI endpoints, or Anthropic configurations. ```go package main import ( "net/http" "net/url" openai "github.com/sashabaranov/go-openai" ) func main() { config := openai.DefaultConfig("your-api-key") proxyURL, _ := url.Parse("http://localhost:8080") config.HTTPClient = &http.Client{ Transport: &http.Transport{Proxy: http.ProxyURL(proxyURL)}, } client := openai.NewClientWithConfig(config) azureConfig := openai.DefaultAzureConfig("azure-api-key", "https://your-resource.openai.azure.com/") azureConfig.APIVersion = "2023-05-15" azureClient := openai.NewClientWithConfig(azureConfig) anthropicConfig := openai.DefaultAnthropicConfig("anthropic-api-key", "") anthropicClient := openai.NewClientWithConfig(anthropicConfig) _, _, _ = client, azureClient, anthropicClient } ``` -------------------------------- ### Go: Tool Calling with JSON Schema Source: https://context7.com/sashabaranov/go-openai/llms.txt Demonstrates how to enable the model to call functions by defining function schemas using the jsonschema package. It shows how to set up tools and process tool calls from the API response. ```go package main import ( "context" "encoding/json" "fmt" openai "github.com/sashabaranov/go-openai" "github.com/sashabaranov/go-openai/jsonschema" ) func main() { client := openai.NewClient("your-api-key") // Define the function schema params := jsonschema.Definition{ Type: jsonschema.Object, Properties: map[string]jsonschema.Definition{ "location": { Type: jsonschema.String, Description: "The city and state, e.g. San Francisco, CA", }, "unit": { Type: jsonschema.String, Enum: []string{"celsius", "fahrenheit"}, }, }, Required: []string{"location"}, } tools := []openai.Tool{ { Type: openai.ToolTypeFunction, Function: &openai.FunctionDefinition{ Name: "get_current_weather", Description: "Get the current weather in a given location", Parameters: params, }, }, } sp, err := client.CreateChatCompletion( context.Background(), openai.ChatCompletionRequest{ Model: openai.GPT4o, Messages: []openai.ChatCompletionMessage{ {Role: openai.ChatMessageRoleUser, Content: "What's the weather in Boston?"}, }, Tools: tools, }, ) if err != nil { fmt.Printf("Error: %v\n", err) return } if len(resp.Choices[0].Message.ToolCalls) > 0 { toolCall := resp.Choices[0].Message.ToolCalls[0] fmt.Printf("Function: %s\n", toolCall.Function.Name) fmt.Printf("Arguments: %s\n", toolCall.Function.Arguments) // Output: Function: get_current_weather // Arguments: {"location":"Boston, MA"} } } ``` -------------------------------- ### Connect to Azure OpenAI Service Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Demonstrates initializing the OpenAI client specifically for Azure endpoints using DefaultAzureConfig. ```go config := openai.DefaultAzureConfig("your Azure OpenAI Key", "https://your Azure OpenAI Endpoint") client := openai.NewClientWithConfig(config) resp, err := client.CreateChatCompletion(context.Background(), openai.ChatCompletionRequest{Model: openai.GPT3Dot5Turbo, Messages: []openai.ChatCompletionMessage{{Role: openai.ChatMessageRoleUser, Content: "Hello Azure OpenAI!"}}}) ``` -------------------------------- ### Create and Manage Fine-Tuning Jobs with Go OpenAI Source: https://context7.com/sashabaranov/go-openai/llms.txt Shows how to create a fine-tuning job for a model using an uploaded training file and then retrieve the status of that job. This process customizes OpenAI models on specific datasets. It requires an API key and a pre-uploaded training file. ```Go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") // First upload training file file, _ := client.CreateFile( context.Background(), openai.FileRequest{ FilePath: "training_data.jsonl", Purpose: string(openai.PurposeFineTune), }, ) // Create fine-tuning job job, err := client.CreateFineTuningJob( context.Background(), openai.FineTuningJobRequest{ TrainingFile: file.ID, Model: "gpt-3.5-turbo", Hyperparameters: &openai.Hyperparameters{ Epochs: 3, }, Suffix: "my-custom-model", }, ) if err != nil { fmt.Printf("Fine-tuning error: %v\n", err) return } fmt.Printf("Job ID: %s\n", job.ID) fmt.Printf("Status: %s\n", job.Status) // Check job status job, _ = client.RetrieveFineTuningJob(context.Background(), job.ID) fmt.Printf("Fine-tuned model: %s\n", job.FineTunedModel) } ``` -------------------------------- ### Upload Training Data and Create Fine-Tuning Job with Go Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go code snippet shows how to upload a JSONL file for fine-tuning and then create a fine-tuning job using the go-openai client. It includes error handling for file upload and job creation, and retrieves the status of the fine-tuning job. ```go file, err := client.CreateFile(ctx, openai.FileRequest{ FilePath: "training_prepared.jsonl", Purpose: "fine-tune", }) if err != nil { fmt.Printf("Upload JSONL file error: %v\n", err) return } // create a fine tuning job fineTuningJob, err := client.CreateFineTuningJob(ctx, openai.FineTuningJobRequest{ TrainingFile: file.ID, Model: "davinci-002", // gpt-3.5-turbo-0613, babbage-002. }) if err != nil { fmt.Printf("Creating new fine tune model error: %v\n", err) return } fineTuningJob, err = client.RetrieveFineTuningJob(ctx, fineTuningJob.ID) if err != nil { fmt.Printf("Getting fine tune model error: %v\n", err) return } fmt.Println(fineTuningJob.FineTunedModel) ``` -------------------------------- ### Create Fine-Tuning Job Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This snippet shows how to initiate a fine-tuning job using a previously uploaded file and a base model. ```APIDOC ## POST /v1/fine_tuning/jobs ### Description Creates a fine-tuning job to train a custom model. ### Method POST ### Endpoint /v1/fine_tuning/jobs ### Parameters #### Request Body - **training_file** (string) - Required - The ID of the file to use for training. - **model** (string) - Required - The base model to fine-tune (e.g., "davinci-002", "gpt-3.5-turbo-0613"). ### Request Example ```go fineTuningJob, err := client.CreateFineTuningJob(ctx, openai.FineTuningJobRequest{ TrainingFile: file.ID, // obtained from file upload Model: "davinci-002", }) if err != nil { fmt.Printf("Creating new fine tune model error: %v\n", err) return } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the fine-tuning job. - **model** (string) - The base model used for fine-tuning. - **status** (string) - The current status of the job (e.g., "validating_files", "queued", "running", "succeeded"). - **training_file** (string) - The ID of the training file. #### Response Example ```json { "id": "ftjob-xxxxxxxxxxxxxxxxx", "object": "fine_tuning.job", "model": "davinci-002", "status": "queued", "training_file": "file-xxxxxxxxxxxxxxxxx" } ``` ``` -------------------------------- ### Create Text Completion Source: https://context7.com/sashabaranov/go-openai/llms.txt Generates text completions for legacy models like GPT-3.5 Turbo Instruct. Takes a prompt and returns a text completion with specified maximum tokens and temperature. ```Go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { client := openai.NewClient("your-api-key") resp, err := client.CreateCompletion( context.Background(), openai.CompletionRequest{ Model: openai.GPT3Dot5TurboInstruct, Prompt: "Write a one-sentence description of Go programming language:", MaxTokens: 50, Temperature: 0.7, }, ) if err != nil { fmt.Printf("Completion error: %v\n", err) return } fmt.Printf("Response: %s\n", resp.Choices[0].Text) } ``` -------------------------------- ### Configure HTTP Proxy for OpenAI Client Source: https://github.com/sashabaranov/go-openai/blob/master/README.md Shows how to customize the underlying HTTP client of the OpenAI library to route requests through a proxy server. ```go config := openai.DefaultConfig("token") proxyUrl, _ := url.Parse("http://localhost:{port}") transport := &http.Transport{Proxy: http.ProxyURL(proxyUrl)} config.HTTPClient = &http.Client{Transport: transport} c := openai.NewClientWithConfig(config) ``` -------------------------------- ### Go GPT-3 Completion Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This Go code snippet shows how to perform a standard text completion using the GPT-3 model via the go-openai library. It initializes an OpenAI client, sets up a completion request with a specified model and prompt, and prints the generated text from the response. Error handling is included for the API call. ```go package main import ( "context" "fmt" openai "github.com/sashabaranov/go-openai" ) func main() { c := openai.NewClient("your token") ctx := context.Background() req := openai.CompletionRequest{ Model: openai.GPT3Babbage002, MaxTokens: 5, Prompt: "Lorem ipsum", } resp, err := c.CreateCompletion(ctx, req) if err != nil { fmt.Printf("Completion error: %v\n", err) return } fmt.Println(resp.Choices[0].Text) } ``` -------------------------------- ### File Upload for Fine-Tuning Source: https://github.com/sashabaranov/go-openai/blob/master/README.md This snippet demonstrates how to upload a JSONL file to be used for fine-tuning an OpenAI model. ```APIDOC ## POST /v1/files ### Description Uploads a file to be used for fine-tuning. ### Method POST ### Endpoint /v1/files ### Parameters #### Form Data - **purpose** (string) - Required - The intended purpose of the file (e.g., "fine-tune"). - **file** (file) - Required - The file to upload. ### Request Example ```go file, err := client.CreateFile(ctx, openai.FileRequest{ FilePath: "training_prepared.jsonl", Purpose: "fine-tune", }) if err != nil { fmt.Printf("Upload JSONL file error: %v\n", err) return } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier for the uploaded file. - **purpose** (string) - The purpose of the file. - **filename** (string) - The name of the file. #### Response Example ```json { "id": "file-xxxxxxxxxxxxxxxxx", "object": "file", "bytes": 12345, "created_at": 1678886400, "filename": "training_prepared.jsonl", "purpose": "fine-tune" } ``` ```