### Set up the development environment Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/CONTRIBUTING_DOCS.md Step 4 of the initial setup: install Go dependencies and verify the documentation scripts. Run from the repo root. The commands validate links and extract examples; an alternative command is provided for compiling snippets. ```bash # Install Go dependencies go mod download # Verify documentation scripts work cd docs/scripts go run validate-links.go -docs=../ -verbose go run extract-examples.go -docs=../ -test-only # or, from the repo root: go run docs/scripts/compile-snippets.go ``` -------------------------------- ### Install Gin and run server Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/gin-server/README.md Installs the Gin dependency and runs the example server. ```bash cd examples/gin-server go get github.com/gin-gonic/gin go run main.go ``` -------------------------------- ### Local development setup Source: https://github.com/digitallysavvy/go-ai/blob/main/website/README.md Installs dependencies and starts the local development server at http://localhost:3000/go-ai/ with hot reload. Most edits, including content in ../docs, show up live without a server restart. ```bash npm ci npm start ``` -------------------------------- ### Run the example with environment setup Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/agents/callbacks/langchain-style/README.md Sets the OpenAI API key and runs the Go program. Requires an API key to be set before execution. ```bash export OPENAI_API_KEY=your_api_key_here go run main.go ``` -------------------------------- ### Complete Example with ai.GenerateText Source: https://github.com/digitallysavvy/go-ai/blob/main/pkg/providers/xai/README.md Complete example showing how to create an xAI provider, obtain a language model, create an MCP server tool, and use it with ai.GenerateText. Demonstrates the full workflow from provider setup to tool invocation. ```go package main import ( "context" "log" "github.com/digitallysavvy/go-ai/pkg/ai" "github.com/digitallysavvy/go-ai/pkg/provider/types" "github.com/digitallysavvy/go-ai/pkg/providers/xai" ) func main() { // Create provider provider := xai.New(xai.Config{ APIKey: "your-api-key", }) model, _ := provider.LanguageModel("grok-beta") // Create MCP Server tool mcpTool := xai.MCPServer(xai.MCPServerConfig{ ServerURL: "https://api.example.com/mcp", AllowedTools: []string{"search", "summarize"}, Authorization: "Bearer token", Headers: map[string]string{ "X-API-Version": "v1", }, }) // Use with GenerateText result, err := ai.GenerateText(context.Background(), model, &ai.GenerateTextOptions{ Prompt: types.Prompt{ Messages: []types.Message{ { Role: "user", Content: []types.ContentPart{ {Type: "text", Text: "Search for Go best practices"}, }, }, }, }, Tools: []types.Tool{mcpTool}, ToolChoice: types.AutoToolChoice(), }) if err != nil { log.Fatal(err) } log.Println(result.Text) } ``` -------------------------------- ### Setup: Set API key and run main.go Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/google/README.md Sets the required API key environment variable and runs the example program. The GOOGLE_FILE_URI environment variable can be set to files/... to run the optional fileData embedding example. ```bash export GOOGLE_GENERATIVE_AI_API_KEY=your-api-key go run main.go ``` -------------------------------- ### Quick Start with [Provider Name] Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/provider-template.mdx Quick start example showing how to create a client with the [Provider Name] provider and generate a text response using the ai.GenerateText function. Replace placeholders like 'your-api-key', '[provider-package]', and '[default-model-name]' with actual values. ```go package main import ( "context" "fmt" "log" "github.com/digitallysavvy/go-ai/pkg/ai" "github.com/digitallysavvy/go-ai/pkg/providers/[provider-package]" ) func main() { // Create client with [Provider Name] client := newExampleClient( "your-api-key", exampleWithProvider([provider-package].NewProvider()), ) // Generate a response response, err := ai.GenerateText(context.Background(), ai.GenerateTextOptions{ Model: "[default-model-name]", Messages: []types.Message{ {Role: "user", Content: "Hello, world!"}, }, }) if err != nil { log.Fatalf("Error: %v", err) } fmt.Println(response.Content) } ``` -------------------------------- ### Run the web search agent Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/agents/web-search-agent/README.md Changes to the example directory and runs the main Go file to start the agent. ```bash cd examples/agents/web-search-agent go run main.go ``` -------------------------------- ### Run image-to-video example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/klingai/README.md Run the image-to-video example. ```bash go run examples/providers/klingai/02-image-to-video.go ``` -------------------------------- ### Complete MCP Tools Example in Go Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-ai-sdk-core/16-mcp-tools.mdx Complete Go example demonstrating MCP client setup with HTTP transport, resource listing, tool conversion, and AI text generation. Requires MCP_SERVER_URL, MCP_API_KEY, and OPENAI_API_KEY environment variables. Uses the gpt-6-astra model and allows up to 5 tool call steps. ```go package main import ( "context" "fmt" "log" "os" "os/signal" "syscall" "github.com/digitallysavvy/go-ai/pkg/ai" "github.com/digitallysavvy/go-ai/pkg/mcp" "github.com/digitallysavvy/go-ai/pkg/providers/openai" ) func main() { ctx := context.Background() // 1. Set up MCP client with HTTP transport transport := mcp.NewHTTPTransport(mcp.HTTPTransportConfig{ URL: os.Getenv("MCP_SERVER_URL"), TimeoutMS: 30000, Config: mcp.TransportConfig{ Headers: map[string]string{ "Authorization": "Bearer " + os.Getenv("MCP_API_KEY"), }, }, }) client := mcp.NewMCPClient(transport, mcp.MCPClientConfig{ ClientName: "go-ai-example", ClientVersion: "1.0.0", }) err := client.Connect(ctx) if err != nil { log.Fatal(err) } // Ensure cleanup defer client.Close() // Handle interrupt signal c := make(chan os.Signal, 1) signal.Notify(c, os.Interrupt, syscall.SIGTERM) go func() { <-c client.Close() os.Exit(0) }() // 2. List available resources resources, err := client.ListResources(ctx) if err != nil { log.Fatal(err) } fmt.Println("Available resources:") for _, r := range resources { fmt.Printf(" - %s: %s\n", r.Name, r.Description) } // 3. Convert MCP tools to AI SDK tools converter := mcp.NewMCPToolConverter(client) tools, err := converter.ConvertToGoAITools(ctx) if err != nil { log.Fatal(err) } fmt.Printf("\nConverted %d MCP tools\n\n", len(tools)) // 4. Use tools with AI model provider := openai.New(openai.Config{ APIKey: os.Getenv("OPENAI_API_KEY"), }) model, err := provider.LanguageModel("gpt-6-astra") if err != nil { log.Fatal(err) } maxSteps := 5 // Allow multiple tool calls result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Prompt: "Use the available tools to get the current weather " + "in Brooklyn, New York and create a chart showing " + "temperature trends", Tools: tools, MaxSteps: &maxSteps, }) if err != nil { log.Fatal(err) } // 5. Display results fmt.Println("AI Response:") fmt.Println(result.Text) // Show tool calls made if len(result.Steps) > 0 { fmt.Println("\nTool Calls:") for i, step := range result.Steps { fmt.Printf(" Step %d:\n", i+1) for _, call := range step.ToolCalls { fmt.Printf(" - %s(%v)\n", call.ToolName, call.Arguments) } } } // Display usage statistics fmt.Printf("\nUsage: %d input tokens, %d output tokens\n", result.Usage.GetInputTokens(), result.Usage.GetOutputTokens()) } ``` -------------------------------- ### Build examples Source: https://github.com/digitallysavvy/go-ai/blob/main/CONTRIBUTING.md Builds example applications. The first part builds a specific example (text-generation) into an executable named text-gen. The second part loops through all example directories and builds each one, naming the output after the directory. ```bash # Build a specific example cd examples/text-generation go build -o text-gen main.go # Build all examples for dir in examples/*/; do cd "$dir" go build -o "$(basename "$dir")" main.go cd ../.. done ``` -------------------------------- ### Test All Examples Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/README.md Run the test script from the examples directory to test all examples. ```bash cd examples ./test-all.sh ``` -------------------------------- ### Documentation directory structure Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/CONTRIBUTING_DOCS.md Shows the folder layout for the docs directory, with numbered sections for getting started, core concepts, providers, guides, examples, troubleshooting, and reference. Use this as a reference when adding new documentation files. ```plaintext docs/ ├── 01-getting-started/ # Installation, quick start, basic setup ├── 02-core-concepts/ # Fundamental concepts and architecture ├── 03-providers/ # Provider-specific documentation ├── 04-guides/ # How-to guides and tutorials ├── 05-examples/ # Complete working examples ├── 06-troubleshooting/ # Common issues and solutions ├── 07-reference/ # API reference documentation │ ├── api/ # API types and functions │ └── types/ # Type definitions ├── _templates/ # Templates for new documentation ├── scripts/ # Validation and testing scripts ├── DOCUMENTATION_STYLE_GUIDE.md └── CONTRIBUTING_DOCS.md # This file ``` -------------------------------- ### Start MLflow Tracking Server Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/06-advanced/12-mlflow-observability.mdx Starts the MLflow Tracking Server with a SQLite backend store on port 5000. For production, use a proper database backend as noted in the MLflow Setup Guide. ```bash mlflow server --backend-store-uri sqlite:///mlruns.db --port 5000 ``` -------------------------------- ### Complete example: create instance, call methods, handle errors Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/api-reference-template.mdx Complete working example demonstrating typical usage of the package. It creates an instance with options, sets up a context with a 30-second timeout, calls the primary method, and processes the result. It also shows using a secondary method. ```go package main import ( "context" "fmt" "log" "time" "github.com/digitallysavvy/go-ai/pkg/[package]" ) func main() { // Create instance with options instance := package.NewTypeName( "configuration-value", package.WithOption1("custom"), package.WithOption2(100), ) // Set up context with timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() // Use primary method result, err := instance.MethodName(ctx, "input") if err != nil { log.Fatalf("Operation failed: %v", err) } // Process result fmt.Printf("Success: %+v\n", result) // Use secondary methods additional := instance.AnotherMethod("value", 42) fmt.Printf("Additional: %+v\n", additional) } ``` -------------------------------- ### Best Practice 1: Do Example Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/guide-template.mdx Recommended approach for Best Practice 1: passes an additional option to newExampleClient, presumably enabling a best practice configuration. ```go // Example of correct approach client := newExampleClient( apiKey, exampleWithBestPracticeOption(), ) ``` -------------------------------- ### Run the Basic Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/generate-object/basic/README.md Navigates to the example directory and runs the Go program. ```bash cd examples/generate-object/basic go run main.go ``` -------------------------------- ### Tool with Input Examples Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/07-reference/ai/tool.mdx This example shows how to create a tool with input examples. The 'calculator' tool includes example inputs to guide the model on how to use the tool. ```APIDOC ## Tool with Input Examples ```go calculatorTool := types.Tool{ Name: "calculator", Description: "Perform mathematical calculations", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "expression": map[string]interface{}{ "type": "string", "description": "Mathematical expression to evaluate", }, }, "required": []string{"expression"}, }, InputExamples: []types.ToolInputExample{ { Input: map[string]interface{}{ "expression": "2 + 2", }, Description: "Simple addition", }, { Input: map[string]interface{}{ "expression": "sqrt(16) * 3", }, Description: "Expression with function", }, }, Execute: func(ctx context.Context, input map[string]interface{}, opts types.ToolExecutionOptions) (interface{}, error) { expr := input["expression"].(string) // Implement calculator logic return fmt.Sprintf("Result: %s", expr), nil }, } ``` ``` -------------------------------- ### Step-by-Step Example in Go Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/DOCUMENTATION_STYLE_GUIDE.md Demonstrates a multi-step workflow: initializing a client, creating a request, generating a response, handling errors, and using the response. Each step is commented for clarity. ```go // Step 1: Initialize the client with your API key client := newExampleClient("your-api-key") // Step 2: Create a request with system and user messages request := ai.GenerateTextOptions{ Model: model, System: "You are a helpful assistant.", Prompt: "What is Go?", } // Step 3: Generate the response response, err := ai.GenerateText(context.Background(), request) // Step 4: Handle any errors if err != nil { log.Fatalf("Error: %v", err) } // Step 5: Use the response fmt.Println(response.Content) ``` -------------------------------- ### GET /health response body Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/echo-server/README.md Example response from GET /health. Includes status, timestamp, model, and requestId. ```json { "status": "healthy", "timestamp": 1703001234, "model": "gpt-4", "requestId": "abc123" } ``` -------------------------------- ### Run Individual Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/README.md Navigate to the example directory and run the Go program. ```bash cd examples/[example-name] go run main.go ``` -------------------------------- ### Run the Complex Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/generate-object/complex/README.md Navigates to the example directory and runs the Go program. ```bash cd examples/generate-object/complex go run main.go ``` -------------------------------- ### Install Go AI SDK v0.2.0 Source: https://github.com/digitallysavvy/go-ai/blob/main/release_notes/RELEASE_NOTES_V6.md Install the Go AI SDK v0.2.0 package using go get. ```bash go get github.com/digitallysavvy/go-ai@v0.2.0 ``` -------------------------------- ### Install the Google Vertex AI provider package Source: https://github.com/digitallysavvy/go-ai/blob/main/pkg/providers/googlevertex/README.md Use `go get` to install the provider package from the go-ai repository. ```bash go get github.com/digitallysavvy/go-ai/pkg/providers/googlevertex ``` -------------------------------- ### Run the Deferrable Tools Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/deferrable-tools/README.md Navigates to the example directory and runs the Go program. ```bash cd examples/deferrable-tools go run main.go ``` -------------------------------- ### Mark non-compilable Go example as pseudo-code Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/DOCUMENTATION_STYLE_GUIDE.md Shows how to mark a Go code example as pseudo-code for illustration only, as required by the documentation style guide. The example is not expected to compile or run. ```markdown ```go // This is pseudo-code for illustration only response := ai.GenerateText(...) process(response) ``` ``` -------------------------------- ### Build Go binaries into builds directory Source: https://github.com/digitallysavvy/go-ai/blob/main/builds/README.md Use these commands to compile example binaries into the builds directory. The first builds a video example, the second builds an Anthropic context test, and the third and fourth build provider-specific binaries. Run them from the project root. ```bash # Build an example go build -o builds/video-example examples/video/text-to-video/main.go ``` ```bash # Build with a descriptive name go build -o builds/anthropic-context-test examples/providers/anthropic/context-management/clear-tool-uses/main.go ``` ```bash # Build multiple examples go build -o builds/fal-video pkg/providers/fal/video_model.go go build -o builds/google-video pkg/providers/google/video_model.go ``` -------------------------------- ### Tool prompt with examples Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-ai-sdk-core/20-prompt-engineering.mdx Shows a prompt that includes example tool calls for weather and flight tools, then passes it to ai.GenerateText with the same stop condition. The prompt demonstrates how to guide the model with examples before asking a combined question. ```go prompt := `You have access to weather and flight tools. Here are examples of how to use them: Example 1: User: "What's the weather in Paris?" Action: Call get_weather({"location": "Paris, France"}) Example 2: User: "Find flights from NYC to LAX" Action: Call search_flights({"from": "JFK", "to": "LAX"}) Now answer: What's the weather like in Tokyo and are there flights from San Francisco?` result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Tools: tools, StopWhen: []ai.StopCondition{ai.IsStepCount(5)}, Prompt: prompt, }) ``` -------------------------------- ### Complete Basic Example Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/guide-template.mdx A complete, runnable example that initializes a client with the anthropic provider, creates a request, and prints the response. ```go package main import ( "context" "fmt" "log" "github.com/digitallysavvy/go-ai/pkg/ai" "github.com/digitallysavvy/go-ai/pkg/providers/anthropic" ) func main() { // Create client client := newExampleClient( "your-api-key", exampleWithProvider(anthropic.NewProvider()), ) // Create request request := ai.GenerateTextOptions{ Model: "claude-sonnet-5-5", Messages: []types.Message{ {Role: "user", Content: "Hello, world!"}, }, } // Generate response response, err := ai.GenerateText(context.Background(), request) if err != nil { log.Fatalf("Error: %v", err) } // Display result fmt.Printf("Response: %s\n", response.Content) } ``` -------------------------------- ### GET /health response Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/gin-server/README.md Example JSON response from the /health endpoint. ```json { "status": "healthy", "timestamp": 1702345678, "model": "gpt-4" } ``` -------------------------------- ### Install go-ai v0.5.0 with go get Source: https://github.com/digitallysavvy/go-ai/blob/main/release_notes/RELEASE_NOTES_V0.5.0.md Use this command to install the go-ai library at version v0.5.0. Run it in your terminal to add the dependency to your Go module. ```bash go get github.com/digitallysavvy/go-ai@v0.5.0 ``` -------------------------------- ### Example: using CreateURLDownload Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/reference/download-api.md Example of using CreateURLDownload(nil) to create a single-URL downloader and then calling it with a context and URL. ```go download := ai.CreateURLDownload(nil) data, err := download(ctx, url) ``` -------------------------------- ### Include Examples (Few-Shot Learning) Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-ai-sdk-core/20-prompt-engineering.mdx Uses few-shot learning by providing examples in the prompt to guide the model. The prompt includes three examples and asks for slogans for a coffee shop with live music. The output is three slogans. ```go prompt := `Create three slogans for a business with unique features. Business: Bookstore with cats Slogans: "Purr-fect Pages", "Books and Whiskers", "Novels and Nuzzles" Business: Gym with rock climbing Slogans: "Peak Performance", "Reach New Heights", "Climb Your Way Fit" Business: Coffee shop with live music Slogans:` result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Prompt: prompt, }) // Output: "Sip, Savor, and Swing", "Beans and Beats", "Melody in Every Cup" ``` -------------------------------- ### Basic Example Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-agents/agent-callbacks.md Demonstrates how to set up an agent with an OnStepFinish callback to print step completion, tool call count, and input token usage. ```APIDOC ## Basic Example ### Description This example shows how to use the OnStepFinish callback to log step completion, tool calls, and token usage. ### Code ```go agent := agent.NewToolLoopAgent(agent.AgentConfig{ Model: model, System: "You are a helpful assistant.", Tools: tools, OnStepFinish: func(step types.StepResult) { fmt.Printf("Step %d complete: %s\n", step.StepNumber, step.Text) if len(step.ToolCalls) > 0 { fmt.Printf("Called %d tools\n", len(step.ToolCalls)) } if step.Usage.InputTokens != nil { fmt.Printf("Used %d input tokens\n", *step.Usage.InputTokens) } }, }) ``` ``` -------------------------------- ### Step 1: Initialize client Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/guide-template.mdx Initializes a client with an API key. This is the first step in the basic usage example. ```go package main import ( "context" "fmt" "log" "github.com/digitallysavvy/go-ai/pkg/ai" ) func main() { // Step 1 code with clear comments client := newExampleClient("your-api-key") // Continue with clear, simple example } ``` -------------------------------- ### Copy guide template to docs directory Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/QUALITY_TOOLS_QUICK_REFERENCE.md Use this command to copy a documentation template from the _templates/ directory to a new guide location. The example copies guide-template.mdx to docs/04-guides/your-guide.mdx. ```bash cp docs/_templates/guide-template.mdx docs/04-guides/your-guide.mdx ``` -------------------------------- ### Run PDF Support Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/anthropic/pdf-support/README.md Navigates to the PDF support example directory, expects PDF files named example.pdf, invoice.pdf, or report.pdf, and runs the main Go program. ```bash cd examples/providers/anthropic/pdf-support # Place PDF files named example.pdf, invoice.pdf, or report.pdf in this directory go run main.go ``` -------------------------------- ### Seed files with SandboxConfig.OnSession Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/10-build-a-chat-app/03-coding-agents-harness.mdx Use SandboxConfig.OnSession to seed the sandbox with project files and create a baseline git commit before the agent starts. The callback runs after the sandbox exists and the work directory is created. Always build paths from sc.SessionWorkDir; the sandbox's own root is not where the agent works. For repeated setup like dependency installation, use SandboxConfig.OnBootstrap with a BootstrapHash instead. ```go SandboxConfig: harness.AgentSandboxConfig{ OnSession: func(ctx context.Context, sc harness.SandboxSessionContext) error { for rel, content := range files { err := sc.Session.WriteTextFile(ctx, providerutils.SandboxWriteTextFileOptions{ Path: path.Join(sc.SessionWorkDir, rel), Content: content, }) if err != nil { return err } } // A baseline commit lets the agent use git status and git diff. res, err := sc.Session.Run(ctx, providerutils.SandboxProcessOptions{ Command: "git init -q && git add -A && git -c user.name=app -c user.email=app@localhost commit -qm baseline", WorkingDirectory: sc.SessionWorkDir, }) if err != nil { return err } if res.ExitCode != 0 { return fmt.Errorf("git init: %s", res.Stderr) } return nil }, }, ``` -------------------------------- ### Clear System Instructions Example Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-agents/02-building-agents.mdx Contrasts a clear, specific system instruction with a vague one. The good example provides detailed rules for a code review assistant, while the bad example is too generic. Use this to guide writing effective system prompts. ```go // Good - Clear and specific agent.AgentConfig{ System: `You are a code review assistant. Focus on security, performance, and maintainability. Rules: - Identify potential bugs and security issues - Suggest specific improvements with code examples - Explain why changes are needed - Be constructive and educational`, } // Bad - Too vague agent.AgentConfig{ System: "You help with code", } ``` -------------------------------- ### Quick Fix: Create client with exampleWithQuickFixOption Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/troubleshooting-template.mdx Use this quick fix to resolve the issue with minimal changes. It creates a client with a single option, exampleWithQuickFixOption(), which is a fast solution. ```go // Quick fix code client := newExampleClient( apiKey, exampleWithQuickFixOption(), ) ``` -------------------------------- ### Configure Option 1 with exampleWithOption1 Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/guide-template.mdx Shows how to configure Option 1 by passing exampleWithOption1 with a custom value to the client constructor. ```go client := newExampleClient( apiKey, exampleWithOption1(customValue), ) ``` -------------------------------- ### Get API Key for Z.AI Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/05-providers/34-zai.mdx Set the `ZAI_API_KEY` environment variable required by the `zai.Config` setup. ```bash export ZAI_API_KEY=... ``` -------------------------------- ### Add a new guide Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/CONTRIBUTING_DOCS.md Steps to create a new guide: copy the template, edit the file, validate with scripts, and commit. ```bash # 1. Copy template cp docs/_templates/guide-template.mdx docs/04-guides/new-feature.mdx # 2. Edit the file # - Fill in all sections # - Add working examples # - Add cross-references # 3. Validate cd docs/scripts go run validate-links.go -docs=../ go run extract-examples.go -docs=../ -compile # 4. Commit and push git add docs/04-guides/new-feature.mdx git commit -m "docs: add guide for new feature" git push origin docs/new-feature ``` -------------------------------- ### Structured Output Prompting with GenerateText Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-ai-sdk-core/20-prompt-engineering.mdx Uses a prompt with a strict format and an example to guide the model to return structured information. The prompt defines exact labels and an example output, then calls GenerateText. ```go prompt := `Create marketing slogans for a vegan restaurant. Return your response in this exact format: PRIMARY SLOGAN: [main slogan] TAGLINE: [supporting tagline] SOCIAL MEDIA: [shorter version for social media] EMOTIONAL APPEAL: [one-word emotion] Example: PRIMARY SLOGAN: "Plant Power, Every Hour" TAGLINE: "Deliciously sustainable dining" SOCIAL MEDIA: "🌱 Power Up Plant-Based" EMOTIONAL APPEAL: Energetic` result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Prompt: prompt, }) ``` -------------------------------- ### Execute with Message History Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-agents/02-building-agents.mdx Use ExecuteWithMessages() for conversations with history. The example builds a message slice with user and assistant turns, then passes it to the agent. It uses the same provider and agent setup as the simple prompt example. ```go package main import ( "context" "fmt" "log" "os" "github.com/digitallysavvy/go-ai/pkg/agent" "github.com/digitallysavvy/go-ai/pkg/provider/types" "github.com/digitallysavvy/go-ai/pkg/providers/openai" ) func main() { ctx := context.Background() provider := openai.New(openai.Config{ APIKey: os.Getenv("OPENAI_API_KEY"), }) model, _ := provider.LanguageModel("gpt-6-astra") myAgent := agent.NewToolLoopAgent(agent.AgentConfig{ Model: model, System: "You are a helpful assistant.", }) // Create conversation history messages := []types.Message{ { Role: types.RoleUser, Content: []types.ContentPart{ types.TextContent{Text: "What is 2+2?"}, }, }, { Role: types.RoleAssistant, Content: []types.ContentPart{ types.TextContent{Text: "2+2 equals 4."}, }, }, { Role: types.RoleUser, Content: []types.ContentPart{ types.TextContent{Text: "What about 3+3?"}, }, }, } result, err := myAgent.ExecuteWithMessages(ctx, messages) if err != nil { log.Fatal(err) } fmt.Println(result.Text) } ``` -------------------------------- ### Initialize Go module and install go-ai Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/02-getting-started/02-golang.mdx Creates a new directory, initializes a Go module, and installs the go-ai SDK. ```bash mkdir my-ai-app cd my-ai-app go mod init my-ai-app go get github.com/digitallysavvy/go-ai ``` -------------------------------- ### Run the OnStepFinish example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/agents/callbacks/onstepfinish/README.md Set the OpenAI API key and run the example from the onstepfinish directory. ```bash export OPENAI_API_KEY=your-api-key cd examples/agents/callbacks/onstepfinish go run main.go ``` -------------------------------- ### Basic setup with context management Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/anthropic/context-management/README.md Basic setup for context management with the Anthropic provider. Creates a provider, then a model with context management edits: clear tool uses after 10K tokens, clear thinking blocks keeping last 2 turns, and compact at 50K tokens. ```go import ( "github.com/digitallysavvy/go-ai/pkg/providers/anthropic" ) // Create provider p := anthropic.New(anthropic.Config{ APIKey: "your-api-key", }) // Create model with context management model, err := p.LanguageModelWithOptions("claude-sonnet-4-5", &anthropic.ModelOptions{ ContextManagement: &anthropic.ContextManagement{ Edits: []anthropic.ContextManagementEdit{ // Clear tool uses after 10K tokens, keep last 3 anthropic.NewClearToolUsesEdit(). WithInputTokensTrigger(10000). WithKeepToolUses(3), // Clear thinking blocks, keep last 2 turns anthropic.NewClearThinkingEdit(). WithKeepRecentTurns(2), // Compact at 50K tokens anthropic.NewCompactEdit(). WithTrigger(50000), }, }, }) ``` -------------------------------- ### Run the Advanced Features Example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/anthropic/advanced-features/README.md Navigates to the example directory and runs the Go program to demonstrate the advanced features. ```bash cd examples/providers/anthropic/advanced-features go run main.go ``` -------------------------------- ### Create a documentation branch Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/CONTRIBUTING_DOCS.md Step 3 of the initial setup: create a new branch for your documentation changes. The branch name should start with docs/. ```bash git checkout -b docs/your-feature-name ``` -------------------------------- ### Transcription with Timestamps Source: https://github.com/digitallysavvy/go-ai/blob/main/pkg/providers/gladia/README.md Transcribe audio with word-level timestamps enabled. The result includes a Timestamps slice, and the example prints each timestamp with start and end times. ```go result, err := model.DoTranscribe(context.Background(), &provider.TranscriptionOptions{ Audio: audioData, MimeType: "audio/mpeg", Language: "en", Timestamps: true, // Request timestamps }) if err != nil { log.Fatal(err) } // Print transcription with timestamps for _, ts := range result.Timestamps { fmt.Printf("[%.2f-%.2f] %s\n", ts.Start, ts.End, ts.Text) } ``` -------------------------------- ### Basic Agent Configuration with Callbacks Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-agents/06-callbacks.mdx Shows how to configure a ToolLoopAgent with both legacy callbacks (OnStepStart, OnStepFinish) and LangChain-style callbacks (OnChainStart, OnChainEnd, OnChainError). Use this as the basic setup for agent execution with logging. ```go import ( "context" "log" "github.com/digitallysavvy/go-ai/pkg/agent" "github.com/digitallysavvy/go-ai/pkg/provider/types" ) myAgent := agent.NewToolLoopAgent(agent.AgentConfig{ Model: model, System: "You are a helpful assistant.", Tools: tools, // Legacy callbacks OnStepStart: func(stepNum int) { log.Printf("Starting step %d", stepNum) }, OnStepFinish: func(step types.StepResult) { log.Printf("Step %d finished: %s", step.StepNumber, step.FinishReason) }, // LangChain-style callbacks OnChainStart: func(input string, messages []types.Message) { log.Printf("Agent starting with input: %s", input) }, OnChainEnd: func(result *agent.AgentResult) { log.Printf("Agent completed in %d steps", len(result.Steps)) }, OnChainError: func(err error) { log.Printf("Agent error: %v", err) }, }) ``` -------------------------------- ### Instruction for three slogans with live music Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/06-advanced/01-prompt-engineering.mdx Requests three slogans for a coffee shop with live music. Uses the same provider setup as the previous examples. ```go result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Prompt: "Create three slogans for a coffee shop with live music.", }) ``` -------------------------------- ### Run text-to-video example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/klingai/README.md Run the text-to-video example. ```bash go run examples/providers/klingai/01-text-to-video.go ``` -------------------------------- ### Monitor performance with timing logs Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/09-troubleshooting/08-performance.mdx Measure and log the duration of operations to monitor performance. The example records the start time and logs the elapsed time after the operation. ```go start := time.Now() // ... operation ... log.Printf("Operation took: %v", time.Since(start)) ``` -------------------------------- ### Example Output Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/cohere/embedding-dimensions/README.md Shows the expected output from running the example, including dimensions and token usage for each configuration. ```text === Example 1: Default Dimensions === Default embedding dimension: 1024 Tokens used: 12 === Example 2: Small Dimension (256) === Small embedding dimension: 256 Tokens used: 10 === Example 3: Medium Dimension (512) === Medium embedding dimension: 512 Tokens used: 9 === Example 4: Large Dimension (1536) === Large embedding dimension: 1536 Tokens used: 14 === Example 5: Batch Embeddings with Custom Dimensions === Text 1: 1024 dimensions Text 2: 1024 dimensions Text 3: 1024 dimensions Total tokens used: 35 ``` -------------------------------- ### Harness Interface Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/07-reference/harness/adapters.mdx The Harness interface is the core contract for adapters. It defines methods to get the specification version, harness ID, built-in tools, and to start a session. ```APIDOC ## Harness Interface ### Description Defines the contract for a coding-agent runtime adapter. It is implemented by adapters and consumed by `harness.Agent`. ### Method `SpecificationVersion() string` ### Endpoint N/A (Go interface method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **string** - Always returns `"harness-v1"`. #### Response Example ```go "harness-v1" ``` ### Method `HarnessID() string` ### Endpoint N/A (Go interface method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **string** - The unique identifier for the harness. #### Response Example ```go "my-harness" ``` ### Method `BuiltinTools() map[string]BuiltinTool` ### Endpoint N/A (Go interface method) ### Parameters None ### Request Example N/A ### Response #### Success Response - **map[string]BuiltinTool** - A map of built-in tools keyed by the runtime-reported name (common name if available, otherwise native name). #### Response Example ```go map[string]BuiltinTool{ "bash": {...}, } ``` ### Method `DoStart(ctx context.Context, opts StartOptions) (Session, error)` ### Endpoint N/A (Go interface method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **ctx** (context.Context) - Required - The context for the operation. - **opts** (StartOptions) - Required - Options for starting the session. ### Request Example ```go session, err := harness.DoStart(ctx, opts) ``` ### Response #### Success Response - **Session** - The started session. - **error** - An error if the start fails. #### Response Example ```go session, nil ``` ``` -------------------------------- ### Create provider with options Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/_templates/provider-template.mdx Shows how to instantiate a provider with options and pass it to a client. ```go provider := [provider-package].NewProvider( [provider-package].WithOption1(value1), [provider-package].WithOption2(value2), ) client := newExampleClient(apiKey, exampleWithProvider(provider)) ``` -------------------------------- ### Replicate Video Model Setup Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/03-ai-sdk-core/38-video-generation.mdx Initialize the Replicate provider and create a video model using the 'minimax/video-01' model. Requires the REPLICATE_API_TOKEN environment variable. ```go prov := replicate.New(replicate.Config{ APIKey: os.Getenv("REPLICATE_API_TOKEN"), }) model := replicate.NewVideoModel(prov, "minimax/video-01") ``` -------------------------------- ### Example: curl requests to /tools and /generate Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/mcp/http/README.md Shows how to list available tools with GET /tools and generate a completion with POST /generate, sending a JSON payload with a prompt. ```bash curl http://localhost:8080/tools curl -X POST http://localhost:8080/generate \ -H "Content-Type: application/json" \ -d '{"prompt": "Calculate 12 * 34"}' ``` -------------------------------- ### Setup Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/05-providers/42-quiverai.mdx Initializes the QuiverAI provider with an API key and optional base URL. ```APIDOC ## Setup ### Description Initializes the QuiverAI provider with an API key and optional base URL. ### Method Constructor ### Endpoint quiverai.New(config quiverai.Config) ### Parameters #### Config - **APIKey** (string) - Optional - API key, defaults to `QUIVERAI_API_KEY`. - **BaseURL** (string) - Optional - Base URL, defaults to `https://api.quiver.ai/v1`, can be overridden with `QUIVERAI_BASE_URL`. ### Request Example ```go import "github.com/digitallysavvy/go-ai/pkg/providers/quiverai" qprovider := quiverai.New(quiverai.Config{ APIKey: "your-api-key", }) ``` ### Response Returns a provider instance. ``` -------------------------------- ### POST /stream SSE response Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/echo-server/README.md Example Server-Sent Events (SSE) response from POST /stream. Shows event types: start, text, and done, with data payloads. ```text event: start data: event: text data: In lines of code event: text data: we weave our dreams event: done data: {"inputTokens":8,"outputTokens":45,"totalTokens":53} ``` -------------------------------- ### Run streaming.go Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/providers/openresponses/README.md Run the streaming example to see tokens appear progressively (like ChatGPT) with token-per-second stats and performance metrics. Demonstrates different streaming scenarios for better UX on long responses. ```bash cd streaming go run main.go ``` -------------------------------- ### Multi-Provider Setup with registry.RegisterProvider Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/07-reference/registry/provider-registry.mdx Shows a setupProviders function that registers multiple providers (OpenAI, Anthropic, Google) from a config map. Includes usage example with environment variables. ```go func setupProviders(config map[string]string) error { providers := map[string]provider.Provider{ "openai": openai.New(openai.Config{ APIKey: config["openai_key"], }), "anthropic": anthropic.New(anthropic.Config{ APIKey: config["anthropic_key"], }), "google": google.New(google.Config{ APIKey: config["google_key"], }), } for name, p := range providers { registry.RegisterProvider(name, p) } return nil } // Usage config := map[string]string{ "openai_key": os.Getenv("OPENAI_API_KEY"), "anthropic_key": os.Getenv("ANTHROPIC_API_KEY"), "google_key": os.Getenv("GOOGLE_GENERATIVE_AI_API_KEY"), } if err := setupProviders(config); err != nil { log.Fatal(err) } ``` -------------------------------- ### More specific instruction for organic coffee shop Source: https://github.com/digitallysavvy/go-ai/blob/main/docs/06-advanced/01-prompt-engineering.mdx Adds a descriptive term to the prompt to influence the output. Uses the same provider setup as the previous example. The output is printed to stdout. ```go result, err := ai.GenerateText(ctx, ai.GenerateTextOptions{ Model: model, Prompt: "Create a slogan for an organic coffee shop.", }) if err != nil { log.Fatal(err) } fmt.Println(result.Text) // Output example: "Naturally Brewed, Ethically Sourced" ``` -------------------------------- ### Run the example Source: https://github.com/digitallysavvy/go-ai/blob/main/examples/middleware/logging/README.md Runs the example program. Expected output includes console logs, an ai-requests.jsonl file with structured logs, and a log preview at the end. ```bash go run main.go ```