### Prerequisites and Setup Source: https://docs.agenticgokit.com/api/examples/memory-rag Commands for installing dependencies, starting the database, and setting environment variables. ```bash # Install v1beta go get github.com/agenticgokit/agenticgokit/v1beta # Setup PostgreSQL with pgvector docker run -d -p 5432:5432 -e POSTGRES_PASSWORD=password ankane/pgvector # Set environment export OPENAI_API_KEY="sk-..." export PG_CONNECTION_STRING="postgres://postgres:password@localhost/postgres" ``` -------------------------------- ### Install v1beta and Set API Key Source: https://docs.agenticgokit.com/api/examples/basic-agent Prerequisites for running the example. Installs the v1beta package using `go get` and sets the OpenAI API key as an environment variable. ```bash # Install v1beta go get github.com/agenticgokit/agenticgokit/v1beta # Set your API key export OPENAI_API_KEY="sk-..." ``` -------------------------------- ### Setup and Run Application Source: https://docs.agenticgokit.com/guides/development/best-practices Commands for installing dependencies, configuring environment variables, and executing the application. ```bash go mod download ``` ```bash export OPENAI_API_KEY="your-key-here" ``` ```bash go run cmd/main.go ``` -------------------------------- ### Development Setup Example Source: https://docs.agenticgokit.com/cli/quick-reference Quickly set up a development project using the basic template and specifying OpenAI as the LLM provider. ```bash agentcli create dev-project --template basic --provider openai ``` -------------------------------- ### Production Setup Example Source: https://docs.agenticgokit.com/cli/quick-reference Create a production-ready RAG system with advanced MCP integration and visualization enabled. ```bash agentcli create prod-kb --template rag-system --mcp advanced --visualize ``` -------------------------------- ### Test System Setup Source: https://docs.agenticgokit.com/guides/setup/vector-databases Install dependencies, pull the embedding model, and run a test query. ```bash # Install dependencies go mod tidy # Set up Ollama (if using local embeddings) ollama pull nomic-embed-text:latest # Test the system go run . -m "Tell me about vector databases" ``` -------------------------------- ### Interactive Project Setup Source: https://docs.agenticgokit.com/cli Launches the CLI in interactive mode, guiding the user through the project setup process step-by-step. ```bash agentcli create --interactive ``` -------------------------------- ### Creating and Executing Chains Source: https://docs.agenticgokit.com/contributors/AddingFeatures Simplified examples for creating and executing chains as documented in the user guide. ```go chain := core.NewAgentChainBuilder("my-workflow"). Step("search", searchAgent). Step("analyze", analysisAgent). Step("summarize", summaryAgent). Build() ``` ```go result, err := chain.Execute(ctx, core.ChainInput{ Event: event, State: state, }) ``` -------------------------------- ### Install Shell Completion Scripts Source: https://docs.agenticgokit.com/cli Provides examples of how to install generated shell completion scripts for different shells. ```bash agentcli completion bash > /etc/bash_completion.d/agentcli ``` ```bash agentcli completion zsh > "${fpath[1]}/_agentcli" ``` ```bash agentcli completion fish > ~/.config/fish/completions/agentcli.fish ``` -------------------------------- ### Verify Installation with Test Script Source: https://docs.agenticgokit.com/api/installation Create and run a test script to verify the agent setup and connectivity. ```go package main import ( "context" "fmt" "log" "os" "github.com/agenticgokit/agenticgokit/v1beta" ) func main() { // Set your API key os.Setenv("OPENAI_API_KEY", "your-key-here") // Create a simple agent agent, err := v1beta.PresetChatAgentBuilder(). WithName("TestAgent"). WithModel("openai", "gpt-3.5-turbo"). Build() if err != nil { log.Fatal("Build failed:", err) } // Test the agent result, err := agent.Run(context.Background(), "Say 'Installation successful!'") if err != nil { log.Fatal("Run failed:", err) } fmt.Printf("✓ Installation verified!\n") fmt.Printf("Response: %s\n", result.Content) } ``` ```bash go run test.go ``` ```text ✓ Installation verified! Response: Installation successful! ``` -------------------------------- ### Install Agentic GoKit and Set API Key Source: https://docs.agenticgokit.com/api/examples/streaming-agent Before running examples, install the Agentic GoKit library and set your OpenAI API key as an environment variable. ```bash go get github.com/agenticgokit/agenticgokit/v1beta export OPENAI_API_KEY="sk-..." ``` -------------------------------- ### Manage Development and Build Lifecycle Source: https://docs.agenticgokit.com/README Standard commands for installing dependencies, starting the development server, and building the project. ```bash # Install dependencies npm install # Start development server npm run dev # Build for production npm run build # Preview production build npm run preview ``` -------------------------------- ### Compare Traditional vs AgenticGoKit Setup Source: https://docs.agenticgokit.com/tutorials/getting-started/your-first-agent Comparison of manual project setup versus using the agentcli tool. ```bash mkdir my-agent cd my-agent go mod init my-agent # Write main.go (100+ lines) # Write agent.go (50+ lines) # Write config.toml # Write tests # Write README # Debug imports and interfaces # Handle errors and edge cases ``` ```bash agentcli create my-agent cd my-agent go run main.go # It just works! ``` -------------------------------- ### Run Example with Dependencies Source: https://docs.agenticgokit.com/api/examples/subworkflow-composition Installs the Agentic GoKit library and sets the OpenAI API key environment variable before running the main Go program. Ensure you replace 'sk-...' with your actual API key. ```bash go get github.com/agenticgokit/agenticgokit/v1beta export OPENAI_API_KEY="sk-..." go run main.go ``` -------------------------------- ### Install AgenticGoKit via go get Source: https://docs.agenticgokit.com/api/installation Use this command to fetch the latest beta version of the library. ```bash go get github.com/agenticgokit/agenticgokit/v1beta ``` -------------------------------- ### Install AgenticGoKit Source: https://docs.agenticgokit.com/api/getting-started Commands to install the library and initialize a Go module. ```bash go get github.com/agenticgokit/agenticgokit ``` ```bash go mod init myagent go mod tidy ``` -------------------------------- ### Initialize and Run AgenticGoKit Runner Source: https://docs.agenticgokit.com/guides/framework-comparison Example of initializing a runner from a configuration file and starting its execution. Use this to set up the core agent flow. ```go // AgenticGoKit: Leverages Go's concurrency model (public API example) runner, _ := core.NewRunnerFromConfig("agentflow.toml") _ = runner.Start(context.Background()) deferrunner.Stop() for _, e := range events { _ = runner.Emit(e) } ``` -------------------------------- ### Clone and Explore AgenticGoKit Examples Source: https://docs.agenticgokit.com/tutorials/getting-started/next-steps Use these commands to download the repository and list the available example patterns for study. ```bash git clone https://github.com/kunalkushwaha/agenticgokit.git cd agenticgokit/examples # Study different patterns ls -la # 01-basic-agent/ # 02-multi-agent-collaboration/ # 03-memory-enabled-agents/ # 04-rag-knowledge-base/ # 05-tool-integration/ # 06-production-workflow/ ``` -------------------------------- ### Template Management Examples Source: https://docs.agenticgokit.com/cli Provides examples for managing project templates, including listing, creating, validating, and showing search paths. ```bash agentcli template list ``` ```bash agentcli template create my-company-standard ``` ```bash agentcli template validate my-template.yaml ``` ```bash agentcli template paths ``` -------------------------------- ### Run Performance Profiling Example Source: https://docs.agenticgokit.com/tutorials/debugging/practical-examples Commands to run the performance profiling example and enable memory profiling with GODEBUG. ```bash # Run the performance profiling example go run performance_example.go profiler.go # Enable memory profiling for detailed analysis GODEBUG=gctrace=1 go run performance_example.go profiler.go ``` -------------------------------- ### Package Documentation Example Source: https://docs.agenticgokit.com/contributors/CodeStyle Demonstrates the standard format for package-level comments and configuration-driven initialization. ```go // Package core provides the public API for AgenticGoKit. // Define interfaces in core and keep implementations in internal/ and plugins/. // // Example usage (config-driven): // runner, err := core.NewRunnerFromConfig("agentflow.toml") // if err != nil { log.Fatal(err) } // _ = runner.RegisterAgent("my-agent", handler) package core ``` -------------------------------- ### Run Tests and Install Development Tools Source: https://docs.agenticgokit.com/contributors/ContributorGuide Execute all project tests to ensure a working setup and install the golangci-lint tool for code linting. ```bash go test ./... go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` -------------------------------- ### Get Version Information Source: https://docs.agenticgokit.com/cli/quick-reference Check the installed version of the AgenticGoKit CLI. ```bash agentcli version ``` -------------------------------- ### Configure Memory Backends Source: https://docs.agenticgokit.com/api/core-concepts Examples for setting up In-Memory, PostgreSQL, and Weaviate memory providers. ```go import "github.com/agenticgokit/agenticgokit/v1beta/memory" memProvider := memory.NewInMemory() agent, err := v1beta.NewBuilder("MemoryAgent"). WithPreset(v1beta.ChatAgent). WithMemory(&v1beta.MemoryOptions{ Type: "simple", Provider: memProvider, }). Build() ``` ```go import "github.com/agenticgokit/agenticgokit/plugins/memory/postgres" memProvider, err := postgres.New( "postgresql://user:pass@localhost/db", postgres.WithTableName("agent_memory"), postgres.WithEmbeddingDim(1536), ) agent, err := v1beta.NewBuilder("PostgresAgent"). WithPreset(v1beta.ChatAgent). WithMemory(&v1beta.MemoryOptions{ Type: "postgres", Provider: memProvider, }). Build() ``` ```go import "github.com/agenticgokit/agenticgokit/plugins/memory/weaviate" memProvider, err := weaviate.New( "http://localhost:8080", weaviate.WithClassName("AgentMemory"), ) agent, err := v1beta.NewBuilder("WeaviateAgent"). WithPreset(v1beta.ChatAgent). WithMemory(&v1beta.MemoryOptions{ Type: "weaviate", Provider: memProvider, }). Build() ``` -------------------------------- ### Initialize Project and Get Dependencies (Code-First) Source: https://docs.agenticgokit.com/tutorials/getting-started/quickstart Sets up a new project directory, initializes Go modules, and fetches the AgenticGoKit dependency for a code-first approach. ```bash mkdir my-agents && cd my-agents go mod init my-agents go get github.com/kunalkushwaha/agenticgokit ``` -------------------------------- ### Verify PostgreSQL Setup Source: https://docs.agenticgokit.com/guides/setup/vector-databases Commands to verify database connectivity, extension installation, and vector operations. ```bash # Test database connection psql -h localhost -U agentflow -d agentflow -c "SELECT version();" # Check pgvector extension psql -h localhost -U agentflow -d agentflow -c "SELECT * FROM pg_extension WHERE extname = 'vector';" # Test vector operations psql -h localhost -U agentflow -d agentflow -c "SELECT '[1,2,3]'::vector <-> '[4,5,6]'::vector;" ``` -------------------------------- ### Initialize and Run an Agent Source: https://docs.agenticgokit.com/contributors/DocsStandards Complete example demonstrating MCP initialization, agent creation with Azure OpenAI, and state execution. ```go package main import ( "context" "fmt" "log" "github.com/kunalkushwaha/agenticgokit/core" ) func main() { // Initialize MCP for tool discovery core.QuickStartMCP() // Create agent with Azure OpenAI config := core.LLMConfig{ Provider: "azure-openai", APIKey: "your-api-key", BaseURL: "https://your-resource.openai.azure.com", } llm := core.NewAzureOpenAIAdapter(config) agent, err := core.NewMCPAgent("helper", llm) if err != nil { log.Fatal(err) } // Create state and run agent state := core.NewState() state.Set("query", "What is the capital of France?") result, err := agent.Run(context.Background(), state) if err != nil { log.Fatal(err) } fmt.Println("Response:", result.GetResult()) } // Expected output: // Response: The capital of France is Paris. ``` -------------------------------- ### Implement Basic Usage Pattern Source: https://docs.agenticgokit.com/guides/setup/llm-providers Example of loading a provider from configuration and performing a simple text generation. ```go package main import ( "context" "fmt" "github.com/kunalkushwaha/agenticgokit/core" ) func main() { // Load provider from configuration cfg, err := core.LoadConfigFromWorkingDir() if err != nil { panic(err) } provider, err := cfg.InitializeProvider() if err != nil { panic(err) } ctx := context.Background() // Simple generation response, err := provider.Generate(ctx, "Explain Go interfaces in simple terms") if err != nil { panic(err) } fmt.Println("Response:", response) fmt.Println("Provider:", provider.Name()) } ``` -------------------------------- ### Create Project with Custom Configuration Source: https://docs.agenticgokit.com/cli/quick-reference Create projects with custom configurations by specifying memory providers, embedding providers, RAG chunk sizes, and MCP setups. Use the interactive mode for a guided setup. ```bash agentcli create my-kb --memory pgvector --embedding openai --rag 1500 ``` ```bash agentcli create my-bot --mcp standard --visualize ``` ```bash agentcli create --interactive ``` -------------------------------- ### Initialize Development Tools Source: https://docs.agenticgokit.com/contributors Commands to verify Go version, install the linter, run tests, and generate documentation. ```bash # Go (1.21+) go version # Linting go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest # Testing go test ./... # Documentation generation (if applicable) go run tools/docgen/main.go ``` -------------------------------- ### Main Application Setup and Execution Source: https://docs.agenticgokit.com/guides/development/research-assistant Sets up LLM provider, MCP manager, agents, and a runner to process a research query. Displays the final report and agent statistics. ```go package main import ( "context" "fmt" "log" "os" "github.com/kunalkushwaha/agenticgokit/core" "./agents" ) func main() { ctx := context.Background() // Initialize LLM provider llmProvider, err := core.NewOpenAIProvider(core.OpenAIConfig{ APIKey: os.Getenv("OPENAI_API_KEY"), Model: "gpt-4", }) if err != nil { log.Fatal("Failed to create LLM provider:", err) } // Initialize MCP manager // Optional: Initialize MCP tools if needed _ = core.QuickStartMCP() if err != nil { log.Fatal("Failed to initialize MCP:", err) } defer mcpManager.Close() // Create agents agentHandlers := map[string]core.AgentHandler{ "researcher": agents.NewResearcherAgent("researcher", llmProvider, mcpManager), "analyzer": agents.NewAnalyzerAgent("analyzer", llmProvider), "synthesizer": agents.NewSynthesizerAgent("synthesizer", llmProvider), } // Create collaborative runner runner, _ := core.NewRunnerFromConfig("agentflow.toml") // Get query from command line if len(os.Args) < 3 || os.Args[1] != "-m" { log.Fatal("Usage: go run . -m \"your research query\"") } query := os.Args[2] // Create research event event := core.NewEvent("", core.EventData{ "query": query, }, nil) // Process research request _ = runner.Start(ctx) defer runner.Stop() err := runner.Emit(event) if err != nil { log.Fatal("Research failed:", err) } // Display results fmt.Println("\n=== RESEARCH REPORT ===") if synthResult, ok := results["synthesizer"]; ok && synthResult.Error == "" { if report, exists := synthResult.OutputState.Get("final_report"); exists { fmt.Println(report) } } // Display statistics fmt.Println("\n=== RESEARCH STATISTICS ===") for agentName, result := range results { if result.Error != "" { fmt.Printf("%s: Error - %s\n", agentName, result.Error) } else { fmt.Printf("%s: Success\n", agentName) } } } ``` -------------------------------- ### Configuration Validation Example Source: https://docs.agenticgokit.com/contributors/CodeStyle Demonstrates validation logic performed at startup to catch configuration errors early. ```go // validateConfig checks the configuration for common errors and // provides helpful suggestions for fixes. // // This validation is performed at startup to catch configuration // issues early, before attempting to connect to external services. // Some validations (like network connectivity) are performed lazily. func validateConfig(config *Config) error { // Check required fields first to provide clear error messages if config.LLM.Provider == "" { return fmt.Errorf("llm.provider is required") } // Validate provider-specific configuration switch config.LLM.Provider { case "azure": return validateAzureConfig(&config.LLM.Azure) case "openai": return validateOpenAIConfig(&config.LLM.OpenAI) default: return fmt.Errorf("unsupported llm provider: %s", config.LLM.Provider) } } ``` -------------------------------- ### Quick Project Creation with Templates Source: https://docs.agenticgokit.com/cli Demonstrates how to quickly create new projects using predefined templates like 'research-assistant' or 'rag-system'. ```bash agentcli create research-bot --template research-assistant ``` ```bash agentcli create knowledge-base --template rag-system ``` ```bash agentcli create data-flow --template data-pipeline ``` -------------------------------- ### Initialize Database Source: https://docs.agenticgokit.com/guides/troubleshooting Run setup scripts or manual SQL initialization for the database. ```bash # Run setup script ./setup.sh # Or manually psql -h localhost -U agentflow -d agentflow -f init-db.sql ``` -------------------------------- ### Create a Basic Agent Source: https://docs.agenticgokit.com/api/getting-started A complete example of setting up and running a basic chat agent in main.go. ```go package main import ( "context" "fmt" "log" "os" agenticgokit "github.com/agenticgokit/agenticgokit/v1beta" ) func main() { // Set your OpenAI API key os.Setenv("OPENAI_API_KEY", "your-api-key-here") // Create an agent with preset configuration agent, err := agenticgokit.NewBuilder("Assistant"). WithPreset(agenticgokit.ChatAgent). WithLLM("openai", "gpt-4"). Build() if err != nil { log.Fatal(err) } // Run a simple query result, err := agent.Run(context.Background(), "What is Go programming language?") if err != nil { log.Fatal(err) } // Print the response fmt.Printf("Response: %s\n", result.Content) fmt.Printf("Success: %t\n", result.Success) } ``` -------------------------------- ### Basic Agent Configuration Source: https://docs.agenticgokit.com/tutorials/getting-started/agent-configuration Start with a simple agent configuration, defining its role and a basic system prompt. This serves as a foundation for more complex setups. ```toml # Start with this [agents.assistant] role = "assistant" system_prompt = "You are a helpful assistant." ``` -------------------------------- ### Initialize Database Source: https://docs.agenticgokit.com/guides/setup/vector-databases Execute the generated setup script to prepare the database environment. ```bash # Run the setup script (generated with your project) ./setup.sh # On Linux/Mac # or setup.bat # On Windows ``` -------------------------------- ### Testing Weaviate Setup and Application Source: https://docs.agenticgokit.com/guides/setup/vector-databases Commands to start Weaviate, check its health, and run your Go application. Remember to set your API key. ```bash # Start Weaviate docker compose up -d # Check Weaviate health curl http://localhost:8080/v1/meta # Test with your application export OPENAI_API_KEY=your-key-here go run . -m "What can you remember?" ``` -------------------------------- ### Use Configuration-First Development Source: https://docs.agenticgokit.com/tutorials/core-concepts/agent-lifecycle Demonstrates loading agent configurations from external files rather than hard-coding agent creation. ```go // Good: Configuration-driven approach config, err := core.LoadConfigFromWorkingDir() factory := core.NewConfigurableAgentFactory(config) agent, err := factory.CreateAgentFromConfig("my_agent", config) // Avoid: Hard-coded agent creation // agent := &MyAgent{name: "hardcoded", ...} ``` -------------------------------- ### PostgreSQL pgvector Database Setup Source: https://docs.agenticgokit.com/api/memory-and-rag SQL commands to set up the PostgreSQL database for the pgvector memory provider. Ensures the necessary extension is installed. ```sql -- Install pgvector extension CREATE EXTENSION IF NOT EXISTS vector; -- Tables are automatically created by the provider: -- - personal_memory (conversation context) -- - key_value_store (structured data) -- - chat_history (message history) -- - documents (document metadata) -- - knowledge_base (RAG embeddings) ``` -------------------------------- ### Implement Logging Middleware Source: https://docs.agenticgokit.com/api/core-concepts An example implementation of the Middleware interface for logging agent execution start and end times. It also demonstrates how to add values to the context. ```go type LoggingMiddleware struct{} func (m *LoggingMiddleware) BeforeRun(ctx context.Context, input string) (context.Context, string, error) { log.Printf("Agent executing: %s", input) ctx = context.WithValue(ctx, "start_time", time.Now()) return ctx, input, nil } func (m *LoggingMiddleware) AfterRun(ctx context.Context, input string, result *v1beta.Result, err error) (*v1beta.Result, error) { startTime := ctx.Value("start_time").(time.Time) duration := time.Since(startTime) log.Printf("Agent completed in %v: success=%t", duration, result.Success) return result, err } agent, err := v1beta.NewBuilder("LogAgent"). WithPreset(v1beta.ChatAgent). WithMiddleware(&LoggingMiddleware{}). Build() ``` -------------------------------- ### Basic Agent Configuration with LLM and Tools Source: https://docs.agenticgokit.com/api/tool-integration Shows how to initialize a new agent with a specified LLM and configure tool-related settings like MCP (Message Communication Protocol) servers, tool timeouts, and maximum concurrent tools. ```go agent, _ := v1beta.NewBuilder("ConfiguredAgent"). WithLLM("openai", "gpt-4"). WithTools( v1beta.WithMCP(servers...), v1beta.WithToolTimeout(30 * time.Second), v1beta.WithMaxConcurrentTools(5), ). Build() ``` -------------------------------- ### Ollama Provider Configuration Source: https://docs.agenticgokit.com/guides/Configuration Configure the Ollama provider for local model inference, specifying the host, model name, and other parameters. Setup involves installing Ollama and pulling models. ```toml [provider] type = "ollama" host = "http://localhost:11434" model = "llama3.2:3b" temperature = 0.7 context_window = 4096 timeout = "60s" ``` ```bash # Install Ollama curl -fsSL https://ollama.ai/install.sh | sh # Pull your preferred model ollama pull llama3.2:3b ollama pull codellama:7b ollama pull mistral:7b # Start server (usually automatic) ollama serve ``` -------------------------------- ### Basic TOML Configuration File Source: https://docs.agenticgokit.com/api/configuration Example of a TOML configuration file for agent setup, covering agent name, system prompt, LLM parameters, execution settings, streaming, and memory options. ```toml # config.toml name = "MyAgent" system_prompt = "You are a helpful assistant" [llm] provider = "openai" model = "gpt-4" temperature = 0.7 max_tokens = 2000 top_p = 0.9 [execution] timeout = "60s" max_retries = 3 retry_delay = "1s" [streaming] buffer_size = 100 [memory] enabled = true provider = "postgres" connection = "postgresql://localhost/agentdb" [memory.rag] enabled = true top_k = 5 threshold = 0.7 ``` -------------------------------- ### Initialize Production Memory Source: https://docs.agenticgokit.com/tutorials/memory-systems/README A complete example of initializing the memory system with production-ready settings. ```go // Production-ready configuration with pgvector config := core.AgentMemoryConfig{ // Core settings Provider: "pgvector", Connection: "postgres://agent_user:secure_pass@localhost:5432/agentdb?sslmode=require", MaxResults: 10, Dimensions: 1536, AutoEmbed: true, // RAG settings EnableRAG: true, EnableKnowledgeBase: true, KnowledgeMaxResults: 20, KnowledgeScoreThreshold: 0.75, ChunkSize: 1000, ChunkOverlap: 200, RAGMaxContextTokens: 4000, RAGPersonalWeight: 0.3, RAGKnowledgeWeight: 0.7, RAGIncludeSources: true, // Embedding configuration Embedding: core.EmbeddingConfig{ Provider: "openai", Model: "text-embedding-3-small", APIKey: os.Getenv("OPENAI_API_KEY"), CacheEmbeddings: true, MaxBatchSize: 100, TimeoutSeconds: 30, }, // Document processing Documents: core.DocumentConfig{ AutoChunk: true, SupportedTypes: []string{"pdf", "txt", "md", "web", "code"}, MaxFileSize: "50MB", EnableMetadataExtraction: true, EnableURLScraping: true, }, // Search optimization Search: core.SearchConfigToml{ HybridSearch: true, KeywordWeight: 0.3, SemanticWeight: 0.7, EnableReranking: true, RerankingModel: "cross-encoder/ms-marco-MiniLM-L-6-v2", EnableQueryExpansion: false, }, } memory, err := core.NewMemory(config) if err != nil { log.Fatalf("Failed to create memory: %v", err) } ``` -------------------------------- ### Setup Global Dead Letter Queue and Processor Source: https://docs.agenticgokit.com/tutorials/core-concepts/error-handling Initializes a global dead letter queue and registers a callback for agent errors to add events to the DLQ if they exceed maximum retries. It also starts a background goroutine to periodically process the DLQ. ```go // Global dead letter queue var globalDLQ = NewDeadLetterQueue(1000) func setupDeadLetterQueue(runner core.Runner) { // Register DLQ callback runner.RegisterCallback(core.HookAgentError, "dead-letter-queue", func(ctx context.Context, args core.CallbackArgs) (core.State, error) { // Check if event should go to DLQ retryCount := getRetryCount(args.Event) maxRetries := getMaxRetries(ClassifyError(args.Error)) if retryCount >= maxRetries { globalDLQ.AddEvent(args.Event, args.AgentID, args.Error, retryCount) dlqState := args.State.Clone() dlqState.SetMeta("dead_letter_queued", "true") dlqState.SetMeta("dlq_timestamp", time.Now().Format(time.RFC3339)) return dlqState, nil } return args.State, nil }) // Start DLQ processor go func() { ticker := time.NewTicker(5 * time.Minute) defer ticker.Stop() for range ticker.C { globalDLQ.ProcessDeadLetters(runner) } }() } ``` -------------------------------- ### GitHub Actions CI Workflow for Testing Source: https://docs.agenticgokit.com/guides/development/testing-agents Configures a GitHub Actions workflow to run tests on push and pull requests. It sets up Go, installs dependencies, and runs unit, integration, and performance tests, including database setup for integration tests. ```yaml # .github/workflows/test.yml name: Test on: push: branches: [ main, develop ] pull_request: branches: [ main ] jobs: test: runs-on: ubuntu-latest services: postgres: image: pgvector/pgvector:pg15 env: POSTGRES_PASSWORD: password POSTGRES_DB: agentflow_test options: >- --health-cmd pg_isready --health-interval 10s --health-timeout 5s --health-retries 5 ports: - 5432:5432 steps: - uses: actions/checkout@v3 - name: Set up Go uses: actions/setup-go@v3 with: go-version: 1.21 - name: Install dependencies run: go mod download - name: Run unit tests run: go test -v -short ./... - name: Run integration tests run: go test -v ./... env: TEST_DB_URL: postgres://postgres:password@localhost:5432/agentflow_test?sslmode=disable - name: Run performance tests run: go test -v -run TestPerformance ./... - name: Generate coverage report run: go test -coverprofile=coverage.out ./... - name: Upload coverage to Codecov uses: codecov/codecov-action@v3 with: file: ./coverage.out ``` -------------------------------- ### Start PostgreSQL Database Source: https://docs.agenticgokit.com/tutorials/getting-started/memory-and-rag Launch the database container and monitor logs for readiness. ```bash # Start PostgreSQL with pgvector extension docker-compose up -d # Wait for database to be ready (about 30 seconds) docker-compose logs -f postgres ``` -------------------------------- ### Run Health Monitoring Example Source: https://docs.agenticgokit.com/tutorials/debugging/practical-examples Executes the health monitoring demonstration using the Go toolchain. ```bash # Run the health monitoring example go run main.go health_checker.go # Expected output: # Health check 1: HEALTHY # Health check 2: HEALTHY # Health check 3: HEALTHY # Health check 4: HEALTHY # Health check 5: HEALTHY ``` -------------------------------- ### Install Ollama on Linux Source: https://docs.agenticgokit.com/tutorials/getting-started/installation Installs Ollama on Linux systems using a curl script. Ensure you have curl installed. ```bash curl -fsSL https://ollama.ai/install.sh | sh ``` -------------------------------- ### Start Agent Configuration with Presets Source: https://docs.agenticgokit.com/api/configuration Begin agent configuration with presets for good defaults, then override specific settings as needed. This simplifies customization. ```go // ✅ Start with preset, customize as needed agent, _ := v1beta.NewBuilder("Agent"). WithPreset(v1beta.ChatAgent). // Good defaults WithConfig(&v1beta.Config{ Temperature: 0.8, // Override only what you need }). Build() ``` -------------------------------- ### Install Go on macOS using Homebrew Source: https://docs.agenticgokit.com/tutorials/getting-started/installation Recommended method for installing Go on macOS. Ensure Homebrew is installed first. ```bash # Using Homebrew (recommended) brew install go # Or download from golang.org/dl ``` -------------------------------- ### Install AgenticGoKit CLI Source: https://docs.agenticgokit.com/guides/troubleshooting Install the AgenticGoKit CLI using Go or by building from source. Verify the installation with `agentcli version`. ```bash # Using Go go install github.com/kunalkushwaha/agenticgokit/cmd/agentcli@latest ``` ```bash # Verify installation agentcli version ``` ```bash # Clone and build git clone https://github.com/kunalkushwaha/agenticgokit.git cd agenticgokit go build -o agentcli ./cmd/agentcli sudo mv agentcli /usr/local/bin/ ``` -------------------------------- ### Install uv Package Manager Source: https://docs.agenticgokit.com/tutorials/getting-started/tool-integration Install the `uv` package manager, which is used by MCP tools. Choose the installation method appropriate for your operating system or use pip. ```bash # macOS/Linux curl -LsSf https://astral.sh/uv/install.sh | sh # Windows (PowerShell) powershell -c "irm https://astral.sh/uv/install.ps1 | iex" # Or using pip pip install uv ``` -------------------------------- ### Create a Web Search Tool Source: https://docs.agenticgokit.com/api/core-concepts Example of creating a 'web_search' tool with parameters for query and max_results, and a handler function that implements the search logic. ```go searchTool := v1beta.Tool{ Name: "web_search", Description: "Search the web for information", Parameters: map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "query": map[string]interface{}{ "type": "string", "description": "Search query", }, "max_results": map[string]interface{}{ "type": "integer", "description": "Maximum number of results", "default": 5, }, }, "required": []string{"query"}, }, Handler: func(ctx context.Context, args map[string]interface{}) (interface{}, error) { query := args["query"].(string) maxResults := 5 if mr, ok := args["max_results"].(int); ok { maxResults = mr } // Implement search logic results := performSearch(query, maxResults) return results, nil }, } ``` -------------------------------- ### Main Application Entry Point Source: https://docs.agenticgokit.com/tutorials/getting-started/first-agent The main.go file initializes the agent runner from configuration and starts the agent system. Ensure LLM provider plugins are imported. ```go package main import ( "context" "log" "github.com/kunalkushwaha/agenticgokit/core" // Plugin imports for LLM providers, orchestration, etc. ) func main() { // Creates a runner from your configuration runner, err := core.NewRunnerFromConfig("agentflow.toml") if err != nil { log.Fatal(err) } // Starts the agent system ctx := context.Background() err = runner.Start(ctx) if err != nil { log.Fatal(err) } defer runner.Stop() // Your agent is now ready to handle requests! } ``` -------------------------------- ### Configure Basic MCP Server Source: https://docs.agenticgokit.com/api/tool-integration Set up MCP servers for agent communication. This example configures filesystem and web-api servers. ```go package main import ( "context" "log" "github.com/agenticgokit/agenticgokit/v1beta" ) func main() { // Define MCP servers mcpServers := []v1beta.MCPServer{ { Name: "filesystem", Type: "stdio", Command: "mcp-server-filesystem", Enabled: true, }, { Name: "web-api", Type: "http_sse", Address: "localhost", Port: 8080, Enabled: true, }, } // Create agent with MCP tools agent, err := v1beta.NewBuilder("ToolAgent"). WithPreset(v1beta.ChatAgent). WithLLM("openai", "gpt-4"). WithTools( v1beta.WithMCP(mcpServers...), ). Build() if err != nil { log.Fatal(err) } // Agent can now use MCP tools result, _ := agent.Run(context.Background(), "List files in current directory") } ``` -------------------------------- ### Install Zsh Completion Source: https://docs.agenticgokit.com/cli/quick-reference Install AgenticGoKit shell completion for Zsh. ```bash agentcli completion zsh > "${fpath[1]}/_agentcli" ``` -------------------------------- ### Install Memory Backends Source: https://docs.agenticgokit.com/api/installation Commands to install memory plugin dependencies. ```bash go get github.com/agenticgokit/agenticgokit/plugins/memory/postgres ``` ```bash go get github.com/agenticgokit/agenticgokit/plugins/memory/weaviate ``` -------------------------------- ### Mock Agent Setup (Core) Source: https://docs.agenticgokit.com/api/migration-from-core Sets up a mock agent using the core library. This is useful for testing agent interactions without making actual calls. ```go mockAgent := &core.MockAgent{ RunFunc: func(ctx context.Context, input string) (*core.Result, error) { return &core.Result{Content: "mock response"}, nil }, } ```