### Install Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/README.md This snippet shows how to install the Warp Go SDK using the go get command. This is the first step to include the SDK in your Go project. ```bash go get github.com/blue-context/warp ``` -------------------------------- ### Build All Warp Go SDK Examples Source: https://github.com/blue-context/warp/blob/main/examples/README.md Provides the command to build all example Go programs located within the `examples` directory of the Warp Go SDK repository. This is useful for compiling all examples at once before running them. ```bash # Navigate to the repository root directory # Then run the build command go build ./examples/... ``` -------------------------------- ### Set API Key Environment Variable Source: https://github.com/blue-context/warp/blob/main/examples/README.md Demonstrates how to set API keys for various AI providers as environment variables, which is a prerequisite for running the Warp Go SDK examples. This includes keys for OpenAI, Anthropic, Azure, AWS Bedrock, and Google Vertex AI. ```bash export OPENAI_API_KEY=sk-... # For other providers, use their respective environment variables: # export ANTHROPIC_API_KEY=... # export AZURE_API_KEY=... # export AWS_ACCESS_KEY_ID=... # export AWS_SECRET_ACCESS_KEY=... # export AWS_REGION_NAME=... # export VERTEX_PROJECT=... # export VERTEX_LOCATION=... ``` -------------------------------- ### Troubleshooting: API Key Not Set Source: https://github.com/blue-context/warp/blob/main/examples/README.md Addresses a common troubleshooting issue where the required API key environment variable (e.g., `OPENAI_API_KEY`) is not set. It provides the error message users might encounter and the solution: setting the appropriate environment variable before running the example. ```bash # Error Message: # OPENAI_API_KEY environment variable is required # Solution: # Set the required environment variable before running the example. # Example for OpenAI: export OPENAI_API_KEY=sk-... ``` -------------------------------- ### Resource Cleanup Pattern with defer in Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Demonstrates the recommended pattern for resource cleanup in the Warp Go SDK using the `defer` keyword. This ensures that client and stream resources are properly closed, releasing underlying connections and preventing resource leaks, even if errors occur. ```go client, err := warp.NewClient() if err != nil { log.Fatalf("Failed to create client: %v", err) } // Ensure client is closed when the function exits defer client.Close() stream, err := client.CompletionStream(ctx, req) if err != nil { log.Fatalf("Failed to create stream: %v", err) } // Ensure stream is closed when the function exits defer stream.Close() // ... process stream ... ``` -------------------------------- ### Configure Warp Client with Advanced Options in Go Source: https://context7.com/blue-context/warp/llms.txt Configure the Warp client with advanced settings like timeouts, retries, fallbacks, cost tracking, caching, and custom callbacks. This example demonstrates setting up a client for making completion requests. ```go package main import ( "context" "log" "os" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/cache" "github.com/blue-context/warp/callback" "github.com/blue-context/warp/provider/openai" ) func main() { // Create client with advanced configuration client, err := warp.NewClient( warp.WithTimeout(30*time.Second), warp.WithRetries(5, 2*time.Second, 2.0), // 5 retries, 2s initial delay, 2x multiplier warp.WithFallbacks("anthropic/claude-3-sonnet", "openai/gpt-3.5-turbo"), warp.WithCostTracking(true), warp.WithMaxBudget(10.0), // $10 limit warp.WithCache(cache.NewMemoryCache(100 * 1024 * 1024)), // 100MB cache warp.WithBeforeRequestCallback(func(ctx context.Context, event *callback.BeforeRequestEvent) error { log.Printf("[REQUEST] Provider: %s, Model: %s", event.Provider, event.Model) return nil }), warp.WithSuccessCallback(func(ctx context.Context, event *callback.SuccessEvent) { log.Printf("[SUCCESS] Cost: $%.4f, Tokens: %d, Duration: %v", event.Cost, event.Tokens, event.Duration) }), warp.WithFailureCallback(func(ctx context.Context, event *callback.FailureEvent) { log.Printf("[FAILURE] Error: %v, Duration: %v", event.Error, event.Duration) }), ) if err != nil { log.Fatal(err) } defer client.Close() // Register provider provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Make request (automatically retried on failure, cached on success) resp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4", Messages: []warp.Message{ {Role: "user", Content: "Hello!"}, }, }) if err != nil { log.Fatal(err) } log.Println("Response:", resp.Choices[0].Message.Content) } ``` -------------------------------- ### Quick Start: Call OpenAI API with Warp Source: https://github.com/blue-context/warp/blob/main/README.md This Go code demonstrates how to initialize the Warp client with an OpenAI API key and make a simple text completion request. It highlights the unified interface for LLM providers and basic error handling. Ensure the OPENAI_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" ) func main() { client, err := warp.NewClient( warp.WithAPIKey("openai", os.Getenv("OPENAI_API_KEY")), ) if err != nil { log.Fatal(err) } defer client.Close() resp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4", Messages: []warp.Message{ {Role: "user", Content: "Hello, world!"}, }, }) if err != nil { log.Fatal(err) } fmt.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### Load Warp Client Configuration from Environment Variables in Go Source: https://context7.com/blue-context/warp/llms.txt Load API keys and configuration for the Warp client directly from environment variables. This simplifies setup by automatically detecting and applying credentials for various providers. ```go package main import ( "context" "log" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" "github.com/blue-context/warp/provider/anthropic" ) func main() { // Load configuration from environment variables // Supports: OPENAI_API_KEY, ANTHROPIC_API_KEY, AZURE_API_KEY, etc. envOptions, err := warp.LoadConfigFromEnv() if err != nil { log.Fatal(err) } // Create client with environment config client, err := warp.NewClient(envOptions...) if err != nil { log.Fatal(err) } defer client.Close() // Register providers (API keys loaded from environment) openaiProvider, _ := openai.NewProvider(openai.WithAPIKey("")) anthropicProvider, _ := anthropic.NewProvider(anthropic.WithAPIKey("")) client.RegisterProvider(openaiProvider) client.RegisterProvider(anthropicProvider) // Use any registered provider resp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4", Messages: []warp.Message{ {Role: "user", Content: "Hello!"}, }, }) if err != nil { log.Fatal(err) } log.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### Troubleshooting: Go Module Import Errors Source: https://github.com/blue-context/warp/blob/main/examples/README.md Provides a solution for common Go module-related errors, such as "package ... cannot find package". This typically occurs when dependencies are missing or the go.mod file is not up-to-date. Running `go mod tidy` is the standard fix. ```bash # Error Message: # package github.com/blue-context/warp: cannot find package # Solution: # Run `go mod tidy` in your project's root directory to download and manage dependencies. ``` -------------------------------- ### Basic Completion Request with Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Illustrates the fundamental usage of the Warp Go SDK for sending a simple text completion request. It covers creating a provider and client, registering the provider, sending the request, and handling potential errors. The output includes the generated response and token usage. ```go package main import ( "context" "fmt" "log" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { // Create a new client instance client, err := warp.NewClient() if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() // Register an OpenAI provider with the client provider := openai.NewProvider() client.RegisterProvider(provider) // Create a context with a timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Define the completion request req := warp.CompletionRequest{ Prompt: "The capital of France is", } // Send the completion request resp, err := client.Completion(ctx, req) if err != nil { log.Fatalf("Completion request failed: %v", err) } // Print the response and token usage fmt.Printf("Response: %s\n", resp.Completion) fmt.Printf("Tokens used: %d (prompt: %d, completion: %d)\n", resp.TokensTotal, resp.TokensPrompt, resp.TokensCompletion) } ``` -------------------------------- ### Streaming Completion Request with Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Demonstrates how to perform streaming completion requests using the Warp Go SDK. It shows how to process response chunks as they arrive, display real-time output, handle the end of the stream (io.EOF), and ensure proper cleanup of stream resources using defer. ```go package main import ( "context" "fmt" "io" "log" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { client, err := warp.NewClient() if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() provider := openai.NewProvider() client.RegisterProvider(provider) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() req := warp.CompletionRequest{ Prompt: "Write a short poem about code, in three lines", } stream, err := client.CompletionStream(ctx, req) if err != nil { log.Fatalf("Completion stream request failed: %v", err) } defer stream.Close() fmt.Println("Streaming response:") fmt.Println("---") for { chunk, err := stream.Recv() // Use Recv() for streaming if err != nil { if err == io.EOF { break // Stream finished } log.Fatalf("Error receiving stream chunk: %v", err) } fmt.Printf("%s", chunk.Completion) } fmt.Println("---") fmt.Println("Stream completed") } ``` -------------------------------- ### Troubleshooting: Provider Not Registered Source: https://github.com/blue-context/warp/blob/main/examples/README.md Resolves the error indicating that a requested provider (e.g., 'openai') was not found or registered with the Warp client. The solution involves ensuring that the `client.RegisterProvider()` method is called with the desired provider instance before making client requests. ```bash # Error Message: # provider "openai" not found # Solution: # Ensure you call `client.RegisterProvider(provider)` before using the client. # Example: # provider := openai.NewProvider() # client.RegisterProvider(provider) ``` -------------------------------- ### Context Usage for Timeouts and Cancellation in Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Explains and demonstrates the use of Go's `context` package for managing request lifecycles within the Warp Go SDK. It shows how to create a context with a timeout and use `defer cancel()` to ensure the context is cleaned up properly. ```go // Create a background context and set a 10-second timeout ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) // Ensure the cancel function is called to release resources associated with the context defer cancel() // Use the context when making a request to the Warp client resp, err := client.Completion(ctx, req) if err != nil { // Handle error, potentially including context cancellation errors log.Fatalf("Request failed: %v", err) } // Process the response fmt.Printf("Response: %s\n", resp.Completion) ``` -------------------------------- ### Common Error Handling Pattern in Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Illustrates a common pattern for handling errors returned by the Warp Go SDK. It shows how to use `errors.As` to check for specific error types, such as `RateLimitError`, and extract detailed information like the retry-after duration. ```go resp, err := client.Completion(ctx, req) if err != nil { var rateLimitErr *warp.RateLimitError if errors.As(err, &rateLimitErr) { // Handle rate limit error specifically fmt.Printf("Rate limited! Retry after: %v\n", rateLimitErr.RetryAfter) } else { // Handle other error types or log the generic error fmt.Printf("An error occurred: %v\n", err) } // Potentially return or exit if an error occurred return } // Process the response if no error occurred fmt.Printf("Success: %s\n", resp.Completion) ``` -------------------------------- ### Send Chat Completions with Warp Go SDK Source: https://context7.com/blue-context/warp/llms.txt Demonstrates how to send a chat completion request to an LLM provider using the Warp Go SDK. It initializes a provider (OpenAI example), creates a Warp client, registers the provider, and sends a completion request. The response includes the generated text and token usage, along with an optional cost calculation. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { // Create provider provider, err := openai.NewProvider( openai.WithAPIKey(os.Getenv("OPENAI_API_KEY")), ) if err != nil { log.Fatal(err) } // Create client client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() // Register provider if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Send completion request resp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4", Messages: []warp.Message{ {Role: "system", Content: "You are a helpful assistant."}, {Role: "user", Content: "What is the capital of France?"}, }, Temperature: warp.Float64Ptr(0.7), MaxTokens: warp.IntPtr(100), }) if err != nil { log.Fatal(err) } fmt.Println("Response:", resp.Choices[0].Message.Content) if resp.Usage != nil { fmt.Printf("Tokens: %d (prompt: %d, completion: %d)\n", resp.Usage.TotalTokens, resp.Usage.PromptTokens, resp.Usage.CompletionTokens) } // Calculate cost cost, err := client.CompletionCost(resp) if err == nil { fmt.Printf("Cost: $%.4f\n", cost) } } ``` -------------------------------- ### Generate Embeddings with Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Shows how to generate text embeddings using the Warp Go SDK. It covers generating embeddings for a single text string, batch embedding multiple texts, accessing embedding dimensions, and processing the resulting embedding vectors. Token usage for embedding generation is also detailed. ```go package main import ( "context" "fmt" "log" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { client, err := warp.NewClient() if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() provider := openai.NewProvider() client.RegisterProvider(provider) ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() // Example 1: Single text embedding fmt.Println("Example 1: Single text embedding") embReq1 := warp.EmbeddingRequest{ Input: "The quick brown fox", } embResp1, err := client.Embedding(ctx, embReq1) if err != nil { log.Fatalf("Single embedding request failed: %v", err) } fmt.Printf("---\nEmbedding dimensions: %d\n", len(embResp1.Embeddings[0].Vector)) if len(embResp1.Embeddings[0].Vector) > 5 { fmt.Printf("First 5 values: %.4f, %.4f, %.4f, %.4f, %.4f\n", empResp1.Embeddings[0].Vector[0], empResp1.Embeddings[0].Vector[1], empResp1.Embeddings[0].Vector[2], empResp1.Embeddings[0].Vector[3], empResp1.Embeddings[0].Vector[4]) } fmt.Printf("Tokens used: %d\n\n", embResp1.TokensTotal) // Example 2: Batch embeddings fmt.Println("Example 2: Batch embeddings") embReq2 := warp.EmbeddingRequest{ Input: []string{ "Hello world", "Warp Go SDK", "Embeddings example", }, } embResp2, err := client.Embedding(ctx, embReq2) if err != nil { log.Fatalf("Batch embedding request failed: %v", err) } fmt.Printf("---\nGenerated %d embeddings\n", len(embResp2.Embeddings)) for i, emb := range embResp2.Embeddings { fmt.Printf("Embedding %d: %d dimensions\n", i+1, len(emb.Vector)) } fmt.Printf("Total tokens used: %d\n\n", embResp2.TokensTotal) fmt.Println("Embeddings completed successfully") } ``` -------------------------------- ### Advanced Features with Warp Go SDK Source: https://github.com/blue-context/warp/blob/main/examples/README.md Explores advanced capabilities of the Warp Go SDK, including client configuration options like timeouts, retries, and debug mode. It covers context-based and request-level timeouts, detailed error type handling (RateLimitError, AuthenticationError, TimeoutError, etc.), and constructing multimodal messages with text and images. ```go package main import ( "context" "errors" "fmt" "log" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { // Example: Client configuration with timeout and retries config := warp.ClientConfig{ Timeout: 30 * time.Second, Retries: 3, } client, err := warp.NewClientWithConfig(config) if err != nil { log.Fatalf("Failed to create client: %v", err) } defer client.Close() provider := openai.NewProvider() client.RegisterProvider(provider) // Example: Context-based timeout control ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() req := warp.CompletionRequest{ Prompt: "Explain the concept of context cancellation in Go.", } // Example: Request-level timeout configuration (overrides client timeout for this request) ctx = warp.WithRequestTimeout(ctx, 2*time.Second) resp, err := client.Completion(ctx, req) if err != nil { // Example: Error type handling and differentiation var rateLimitErr *warp.RateLimitError var authErr *warp.AuthenticationError var timeoutErr *warp.TimeoutError var contextWindowErr *warp.ContextWindowExceededError var apiErr *warp.APIError if errors.As(err, &rateLimitErr) { fmt.Printf("Rate limited! Retry after: %v\n", rateLimitErr.RetryAfter) } else if errors.As(err, &authErr) { fmt.Printf("Authentication error: %v\n", authErr.Message) } else if errors.As(err, &timeoutErr) { fmt.Printf("Request timed out: %v\n", timeoutErr.Err) } else if errors.As(err, &contextWindowErr) { fmt.Printf("Context window exceeded: %v\n", contextWindowErr.Message) } else if errors.As(err, &apiErr) { fmt.Printf("Generic API error: %v (Status: %d)\n", apiErr.Message, apiErr.StatusCode) } else { log.Fatalf("An unexpected error occurred: %v", err) } return // Exit if error occurred } fmt.Printf("Response: %s\n", resp.Completion) // Example: Multimodal message structure (conceptual, actual implementation depends on provider) // multimodalReq := warp.ChatCompletionRequest{ // Messages: []warp.Message{ // {Role: "user", Content: "Describe this image.", Type: warp.ContentTypeText}, // {Role: "user", Content: "data:image/png;base64,iVBORw0KGgo...", Type: warp.ContentTypeImageURL}, // }, // } // _, err = client.ChatCompletion(ctx, multimodalReq) // ... handle error ... } ``` -------------------------------- ### Response Caching with Warp Memory Cache Source: https://context7.com/blue-context/warp/llms.txt This Go code snippet illustrates how to implement response caching for AI model requests using the warp library's memory cache. It initializes a warp client with a memory cache, registers an OpenAI provider, and then makes two identical completion requests. The first request is served directly from the provider, while the second is served from the cache, demonstrating a significant reduction in latency and potential cost savings. The output shows the duration of both requests and the speedup factor. ```go package main import ( "context" "log" "os" "time" "github.com/blue-context/warp" "github.com/blue-context/warp/cache" "github.com/blue-context/warp/provider/openai" ) func main() { // Create memory cache with 100MB limit memCache := cache.NewMemoryCache(100 * 1024 * 1024) client, err := warp.NewClient( warp.WithCache(memCache), ) if err != nil { log.Fatal(err) } defer client.Close() provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } req := &warp.CompletionRequest{ Model: "openai/gpt-3.5-turbo", Messages: []warp.Message{ {Role: "user", Content: "What is 2+2?"}, }, } // First request - hits API start := time.Now() resp1, err := client.Completion(context.Background(), req) if err != nil { log.Fatal(err) } duration1 := time.Since(start) log.Printf("First request: %v - %s", duration1, resp1.Choices[0].Message.Content) // Second identical request - served from cache start = time.Now() resp2, err := client.Completion(context.Background(), req) if err != nil { log.Fatal(err) } duration2 := time.Since(start) log.Printf("Second request: %v - %s", duration2, resp2.Choices[0].Message.Content) log.Printf("Cache speedup: %.2fx faster", float64(duration1)/float64(duration2)) } ``` -------------------------------- ### Image Generation with OpenAI DALL-E in Go Source: https://context7.com/blue-context/warp/llms.txt Generates images from text prompts using OpenAI's DALL-E models via the warp library. Requires an OpenAI API key. Supports various image sizes, qualities, and numbers of images. Outputs URLs and saves generated images to PNG files. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Generate image resp, err := client.ImageGeneration(context.Background(), &warp.ImageGenerationRequest{ Model: "openai/dall-e-3", Prompt: "A cute baby sea otter floating in a kelp forest", Size: "1024x1024", // Options: 256x256, 512x512, 1024x1024, 1792x1024, 1024x1792 Quality: "standard", // Options: standard, hd N: warp.IntPtr(1), }) if err != nil { log.Fatal(err) } for i, img := range resp.Data { fmt.Printf("Image %d URL: %s\n", i, img.URL) // Save to file if err := img.SaveToFile(context.Background(), fmt.Sprintf("image_%d.png", i)); err != nil { log.Printf("Failed to save image %d: %v", i, err) } else { fmt.Printf("Image %d saved to image_%d.png\n", i, i) } } } ``` -------------------------------- ### Stream LLM Responses with Warp Go SDK Source: https://context7.com/blue-context/warp/llms.txt Illustrates how to receive streaming responses from an LLM provider using the Warp Go SDK. This code sets up an OpenAI provider and Warp client, then initiates a streaming completion request. It iterates through the stream chunks, printing the content as it arrives until the stream ends. ```go package main import ( "context" "fmt" "io" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Create streaming request stream, err := client.CompletionStream(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-3.5-turbo", Messages: []warp.Message{ {Role: "user", Content: "Write a haiku about Go programming."}, }, }) if err != nil { log.Fatal(err) } defer stream.Close() // Process stream chunks fmt.Println("Streaming response:") for { chunk, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Fatal(err) } if len(chunk.Choices) > 0 && chunk.Choices[0].Delta.Content != "" { fmt.Print(chunk.Choices[0].Delta.Content) } } fmt.Println() } ``` -------------------------------- ### Text-to-Speech with OpenAI TTS in Go Source: https://context7.com/blue-context/warp/llms.txt Converts input text into speech audio using OpenAI's TTS models and the warp library. Requires an OpenAI API key. Accepts various voice and response format options. Saves the generated audio to an MP3 file. ```go package main import ( "context" "io" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Generate speech audio, err := client.Speech(context.Background(), &warp.SpeechRequest{ Model: "openai/tts-1", Input: "Hello! This is a test of the text-to-speech functionality.", Voice: "alloy", // Options: alloy, echo, fable, onyx, nova, shimmer ResponseFormat: "mp3", // Options: mp3, opus, aac, flac Speed: warp.Float64Ptr(1.0), // 0.25 to 4.0 }) if err != nil { log.Fatal(err) } defer audio.Close() // Save to file outFile, err := os.Create("output.mp3") if err != nil { log.Fatal(err) } defer outFile.Close() written, err := io.Copy(outFile, audio) if err != nil { log.Fatal(err) } log.Printf("Audio saved: %d bytes written to output.mp3", written) } ``` -------------------------------- ### Audio Transcription with OpenAI Whisper in Go Source: https://context7.com/blue-context/warp/llms.txt Transcribes an audio file to text using the OpenAI Whisper model via the warp library. Requires an OpenAI API key set as an environment variable and an audio file (e.g., meeting.mp3). Outputs the transcribed text and audio duration. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Open audio file audioFile, err := os.Open("meeting.mp3") if err != nil { log.Fatal(err) } defer audioFile.Close() // Transcribe audio resp, err := client.Transcription(context.Background(), &warp.TranscriptionRequest{ Model: "openai/whisper-1", File: audioFile, Filename: "meeting.mp3", Language: "en", Prompt: "Meeting transcription", }) if err != nil { log.Fatal(err) } fmt.Println("Transcription:") fmt.Println(resp.Text) fmt.Printf("Duration: %.2f seconds\n", resp.Duration) } ``` -------------------------------- ### Document Reranking for RAG with Warp Source: https://context7.com/blue-context/warp/llms.txt This Go code snippet demonstrates how to rerank documents based on their relevance to a given query using the warp library. It sets up multiple providers (Cohere and OpenAI), registers them with the warp client, reranks a list of documents, and then uses the top-ranked documents to generate a completion with OpenAI. The context is built from the reranked documents to ensure the completion is grounded in the most relevant information. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/cohere" "github.com/blue-context/warp/provider/openai" ) func main() { // Setup providers cohereProvider, err := cohere.NewProvider(cohere.WithAPIKey(os.Getenv("COHERE_API_KEY"))) if err != nil { log.Fatal(err) } openaiProvider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() client.RegisterProvider(cohereProvider) client.RegisterProvider(openaiProvider) query := "What is the capital of France?" // Documents from vector store search documents := []string{ "Paris is the capital and most populous city of France.", "London is the capital of England and the United Kingdom.", "Berlin is the capital and largest city of Germany.", "France is a country in Western Europe.", "The Eiffel Tower is located in Paris, France.", "Rome is the capital city of Italy.", } // Rerank documents by relevance rerankResp, err := client.Rerank(context.Background(), &warp.RerankRequest{ Model: "cohere/rerank-english-v3.0", Query: query, Documents: documents, TopN: warp.IntPtr(3), }) if err != nil { log.Fatal(err) } // Build context from top results context := "" fmt.Println("Top ranked documents:") for _, result := range rerankResp.Results { fmt.Printf(" [%d] Score: %.3f - %s\n", result.Index, result.RelevanceScore, documents[result.Index]) context += documents[result.Index] + "\n\n" } // Use top results in completion completionResp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4", Messages: []warp.Message{ { Role: "system", Content: "Answer the question based only on this context:\n\n" + context, }, { Role: "user", Content: query, }, }, }) if err != nil { log.Fatal(err) } fmt.Println("\nFinal answer:") fmt.Println(completionResp.Choices[0].Message.Content) } ``` -------------------------------- ### Send Multimodal Request with Go Vision Model Source: https://context7.com/blue-context/warp/llms.txt This Go program utilizes the Warp SDK to interact with vision models. It reads an image, encodes it into a data URI, and sends it as part of a completion request containing both text and image data. Dependencies include the Warp SDK and an OpenAI provider. The input is an image file and a text prompt, and the output is the model's textual analysis of the image. ```go package main import ( "context" "encoding/base64" "io" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Read image file imageFile, err := os.Open("diagram.png") if err != nil { log.Fatal(err) } defer imageFile.Close() imageData, err := io.ReadAll(imageFile) if err != nil { log.Fatal(err) } // Encode to base64 base64Image := base64.StdEncoding.EncodeToString(imageData) dataURI := "data:image/png;base64," + base64Image // Send multimodal request resp, err := client.Completion(context.Background(), &warp.CompletionRequest{ Model: "openai/gpt-4-vision-preview", Messages: []warp.Message{ { Role: "user", Content: []warp.ContentPart{ { Type: "text", Text: "What's in this image? Describe it in detail.", }, { Type: "image_url", ImageURL: &warp.ImageURL{ URL: dataURI, Detail: "high", // Options: auto, low, high }, }, }, }, }, MaxTokens: warp.IntPtr(300), }) if err != nil { log.Fatal(err) } log.Println("Vision analysis:") log.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### Edit Image with AI Source: https://context7.com/blue-context/warp/llms.txt Edits an existing image using AI models, such as DALL-E 2. It requires an image file, a prompt describing the desired edits, and optionally specifies the model, size, and number of images to generate. The edited image can be saved to a file. ```go package main import ( "context" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Open image file imageFile, err := os.Open("cat.png") if err != nil { log.Fatal(err) } defer imageFile.Close() // Edit image resp, err := client.ImageEdit(context.Background(), &warp.ImageEditRequest{ Model: "openai/dall-e-2", Image: imageFile, ImageFilename: "cat.png", Prompt: "Add a party hat to the cat", Size: "512x512", N: warp.IntPtr(1), }) if err != nil { log.Fatal(err) } if len(resp.Data) > 0 { log.Println("Edited image URL:", resp.Data[0].URL) if err := resp.Data[0].SaveToFile(context.Background(), "edited_cat.png"); err != nil { log.Fatal(err) } log.Println("Saved to edited_cat.png") } } ``` -------------------------------- ### Generate Text Embeddings using Warp Client in Go Source: https://context7.com/blue-context/warp/llms.txt Generate vector embeddings for text using the Warp client. This is useful for semantic search, similarity comparisons, and other natural language processing tasks. Requires an OpenAI API key set in the environment. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Generate embeddings resp, err := client.Embedding(context.Background(), &warp.EmbeddingRequest{ Model: "openai/text-embedding-ada-002", Input: []string{ "The quick brown fox jumps over the lazy dog", "Machine learning is a subset of artificial intelligence", }, }) if err != nil { log.Fatal(err) } for i, embedding := range resp.Data { fmt.Printf("Embedding %d: %d dimensions\n", i, len(embedding.Embedding)) fmt.Printf("First 5 values: %v\n", embedding.Embedding[:5]) } if resp.Usage != nil { fmt.Printf("Tokens used: %d\n", resp.Usage.TotalTokens) } } ``` -------------------------------- ### Generate Image Variations Source: https://context7.com/blue-context/warp/llms.txt Creates variations of an existing image using AI models like DALL-E 2. This function takes an image file as input and generates a specified number of different versions. The generated variations can be saved to local files. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Open image file imageFile, err := os.Open("original.png") if err != nil { log.Fatal(err) } defer imageFile.Close() // Create variations resp, err := client.ImageVariation(context.Background(), &warp.ImageVariationRequest{ Model: "openai/dall-e-2", Image: imageFile, ImageFilename: "original.png", N: warp.IntPtr(3), Size: "512x512", }) if err != nil { log.Fatal(err) } for i, img := range resp.Data { fmt.Printf("Variation %d URL: %s\n", i, img.URL) filename := fmt.Sprintf("variation_%d.png", i) if err := img.SaveToFile(context.Background(), filename); err != nil { log.Printf("Failed to save variation %d: %v", i, err) } else { fmt.Printf("Saved to %s\n", filename) } } } ``` -------------------------------- ### Moderate Content with AI Source: https://context7.com/blue-context/warp/llms.txt Checks text content for policy violations using AI moderation models. It can process single text inputs or batches of texts, returning information about whether the content is flagged and category-specific scores. ```go package main import ( "context" "fmt" "log" "os" "github.com/blue-context/warp" "github.com/blue-context/warp/provider/openai" ) func main() { provider, err := openai.NewProvider(openai.WithAPIKey(os.Getenv("OPENAI_API_KEY"))) if err != nil { log.Fatal(err) } client, err := warp.NewClient() if err != nil { log.Fatal(err) } defer client.Close() if err := client.RegisterProvider(provider); err != nil { log.Fatal(err) } // Check single text resp, err := client.Moderation(context.Background(), &warp.ModerationRequest{ Model: "openai/text-moderation-latest", Input: "I want to hurt someone", }) if err != nil { log.Fatal(err) } if len(resp.Results) > 0 { result := resp.Results[0] if result.Flagged { fmt.Println("Content flagged!") fmt.Printf("Categories: %+v\n", result.Categories) fmt.Printf("Category scores: %+v\n", result.CategoryScores) } else { fmt.Println("Content is safe") } } // Check multiple texts batchResp, err := client.Moderation(context.Background(), &warp.ModerationRequest{ Model: "openai/text-moderation-stable", Input: []string{ "This is a normal message", "I want to hurt someone", "Have a great day!", }, }) if err != nil { log.Fatal(err) } for i, result := range batchResp.Results { if result.Flagged { fmt.Printf("Text %d flagged\n", i) } else { fmt.Printf("Text %d is safe\n", i) } } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.