### Complex Pipeline Example Setup Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/data-pipelines.md Demonstrates setting up an agent and stream configuration for an advanced data pipeline. ```go func ComplexPipelineExample() { fmt.Println("🌊 Streaming Pipeline - Advanced Patterns") fmt.Println("========================================") // Create agent for enrichment agent, err := core.NewAgentFromString("enricher", "openai/gpt-4o-mini") if err != nil { log.Fatalf("Failed to create agent: %v", err) } // Create streaming pipeline config := StreamConfig{ BufferSize: 1000, MaxConcurrency: 10, FlushInterval: 5 * time.Second, ``` -------------------------------- ### Main Application Setup and Server Start Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/web-applications.md Configures and starts the AI web service. Includes loading configuration, setting up Gin, applying middleware, defining routes, and starting the HTTP server. ```go // Load configuration config := &Config{ Port: 8080, MaxConcurrency: 10, RequestTimeout: 30 * time.Second, RateLimit: 60, // 60 requests per minute MaxTokens: 1000, EnableMetrics: true, EnableEvents: true, RedisAddr: "localhost:6379", } // Create service service, err := NewAIWebService(config) if err != nil { log.Fatal("Failed to create AI web service:", err) } // Setup Gin gin.SetMode(gin.ReleaseMode) r := gin.New() // Middleware r.Use(gin.Logger()) r.Use(gin.Recovery()) r.Use(func(c *gin.Context) { c.Header("X-Service", "ai-web-service") c.Next() }) // Routes api := r.Group("/api/v1") { api.POST("/chat", service.chatHandler) api.GET("/health", service.healthHandler) if config.EnableMetrics { api.GET("/metrics", service.metricsHandler()) } } // Start server log.Printf("AI Web Service starting on port %d", config.Port) log.Fatal(r.Run(fmt.Sprintf(":%d", config.Port))) ``` -------------------------------- ### Go Quick Start Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/README.md This Go code demonstrates how to initialize an LLM agent, set a system prompt, and run a query using an OpenAI provider. Ensure the OPENAI_API_KEY environment variable is set. ```go package main import ( "context" "fmt" "log" "os" "github.com/lexlapax/go-llms/pkg/llm/provider" "github.com/lexlapax/go-llms/pkg/agent/core" "github.com/lexlapax/go-llms/pkg/llm/domain" ) func main() { // Get API key from environment apiKey := os.Getenv("OPENAI_API_KEY") if apiKey == "" { log.Fatal("Please set OPENAI_API_KEY environment variable") } // Create a provider openaiProvider := provider.NewOpenAIProvider(apiKey, "gpt-4") // Create an agent agent := core.NewLLMAgent("assistant", "gpt-4", core.LLMDeps{ Provider: openaiProvider, } // Set system prompt agent.SetSystemPrompt("You are a helpful assistant that responds concisely.") // Create state with user input state := domain.NewState() state.Set("user_input", "What is the capital of France?") // Run the agent result, err := agent.Run(context.Background(), state) if err != nil { log.Fatal("Error running agent:", err) } // Get and print the response if response, exists := result.Get("response"); exists { fmt.Println("AI:", response) } } ``` -------------------------------- ### Run Go LLMs Quickstart Source: https://github.com/lexlapax/go-llms/blob/main/README.md Set your OpenAI API key and run the quickstart Go program to get started with the project. ```bash export OPENAI_API_KEY="your-key-here" go run docs/user-guide/getting-started/quickstart.go ``` -------------------------------- ### OpenAI Provider Setup and Usage Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/provider-setup.md Demonstrates how to set up an agent using OpenAI's GPT-4o-mini model, either through a simple string-based creation or explicit provider configuration with options like Organization ID. Includes a basic test to confirm the setup. ```go package main import ( "context" "fmt" "log" "os" "github.com/lexlapax/go-llms/pkg/agent/core" "github.com/lexlapax/go-llms/pkg/agent/domain" "github.com/lexlapax/go-llms/pkg/llm/provider" llmDomain "github.com/lexlapax/go-llms/pkg/llm/domain" ) func main() { // Method 1: Simple string-based creation agent, err := core.NewAgentFromString("assistant", "openai/gpt-4o-mini") if err != nil { log.Fatalf("Failed to create agent: %v", err) } // Method 2: Explicit provider creation with options apiKey := os.Getenv("OPENAI_API_KEY") orgID := os.Getenv("OPENAI_ORGANIZATION") var options []llmDomain.ProviderOption if orgID != "" { options = append(options, llmDomain.NewOpenAIOrganizationOption(orgID)) } openaiProvider := provider.NewOpenAIProvider(apiKey, "gpt-4o-mini", options...) explicitAgent := core.NewLLMAgent("explicit-assistant", "gpt-4o-mini", core.LLMDeps{ Provider: openaiProvider, } // Test the setup state := domain.NewState() state.Set("user_input", "Hello! Can you confirm that OpenAI is working?") result, err := agent.Run(context.Background(), state) if err != nil { log.Fatalf("OpenAI test failed: %v", err) } if response, exists := result.Get("response"); exists { fmt.Printf("āœ… OpenAI setup successful!\nResponse: %v\n", response) } } ``` -------------------------------- ### Run Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/workflow-hooks/README.md Execute the Go example from the command line. ```bash # Run the example go run main.go ``` -------------------------------- ### Run Utils Profiling Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/README.md Navigate to the utils-profiling directory and run the main Go program to start performance profiling. ```bash cd utils-profiling && go run main.go ``` -------------------------------- ### Build All Examples Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/README.md Use the Makefile to build all examples at once. Alternatively, build a specific example by providing its name. ```bash # Build all examples make build-examples # Build a specific example make build-example EXAMPLE=agent-simple-llm # Clean all built examples make clean-examples ``` -------------------------------- ### Go Package README Structure and Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/technical/development/contributing.md Provides a template for README.md documentation for Go packages, including sections for features, installation, quick start, and configuration. Shows a basic usage example for a package. ```markdown # Package Name Brief description of the package purpose and functionality. ## Features - Feature 1 with brief description - Feature 2 with brief description - Feature 3 with brief description ## Installation ```go import "github.com/lexlapax/go-llms/pkg/package/name" ``` ## Quick Start ```go // Basic usage example package main import ( "context" "fmt" "log" "github.com/lexlapax/go-llms/pkg/package/name" ) func main() { // Create instance instance := name.New(name.Config{ // Configuration options }) // Use the instance result, err := instance.DoSomething(context.Background()) if err != nil { log.Fatal(err) } fmt.Println(result) } ``` ## Configuration ### Required Options - `option1`: Description of required option - `option2`: Description of required option ### Optional Options - `option3`: Description with default value - `option4`: Description with default value ## Examples ### Example 1: Basic Usage [Detailed example with explanation] ### Example 2: Advanced Configuration [Advanced example with explanation] ``` -------------------------------- ### Full Application Example - Go Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/getting-started/key-concepts.md A complete example demonstrating the integration of providers, agents, schemas, and state to process user input and get structured analysis. ```go func main() { // 1. Create a provider provider := provider.NewOpenAIProvider(apiKey, "gpt-4") // 2. Create an agent agent := core.NewLLMAgent("analyzer", "gpt-4", core.LLMDeps{ Provider: provider, } // 3. Define what you want (schema) analysisSchema := &schema.Schema{ Type: "object", Properties: map[string]*schema.Schema{ "sentiment": {Type: "string", Enum: []interface{}{"positive", "negative", "neutral"}}, "confidence": {Type: "number"}, "key_points": {Type: "array", Items: &schema.Schema{Type: "string"}}, }, } // 4. Configure the agent agent.SetSystemPrompt("Analyze text and return structured data") agent.SetSchema(analysisSchema) // 5. Process data through state state := domain.NewState() state.Set("user_input", "I love this new product! It's amazing and works perfectly.") // 6. Run and get structured results result, err := agent.Run(context.Background(), state) if err != nil { log.Fatal(err) } // 7. Use the structured output analysis, _ := result.Get("structured_output") fmt.Printf("Analysis: %+v\n", analysis) // Output: Analysis: {sentiment: "positive", confidence: 0.95, key_points: ["loves product", "works perfectly"]} } ``` -------------------------------- ### Run Go-LLMs Example Projects Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/getting-started/installation.md Execute example projects to test your Go-LLMs setup. This includes testing with a mock provider, OpenAI, and Ollama. ```bash # Clone the repository (optional, for examples) git clone https://github.com/lexlapax/go-llms.git cd go-llms # Test with mock provider (no API key needed) go run cmd/examples/simple/main.go # Test with OpenAI (requires API key) export OPENAI_API_KEY="your-key" go run cmd/examples/provider-openai/main.go # Test with Ollama (requires local Ollama) go run cmd/examples/provider-ollama/main.go ``` -------------------------------- ### Run Go-LLM Examples Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/README.md Navigate to an example directory and run it using `go run` or build a binary first. ```bash cd cmd/examples/ go run main.go [args...] go build -o example . ./example [args...] ``` -------------------------------- ### Running the Provider Options Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/provider-options/README.md Set API keys as environment variables and build/run the example using make. ```bash # Set your API keys as environment variables export OPENAI_API_KEY=your_openai_key export ANTHROPIC_API_KEY=your_anthropic_key export GEMINI_API_KEY=your_gemini_key # Build and run make example EXAMPLE=provider-options ./bin/provider-options ``` -------------------------------- ### API Server Setup Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/local-providers.md Sets up and starts the API server for the LocalAIPlatform. It listens on a configured port and handles incoming HTTP requests. ```go server := &http.Server{ Addr: fmt.Sprintf(":%d", lap.config.APIServerPort), Handler: mux, } fmt.Printf("🌐 API server starting on port %d\n", lap.config.APIServerPort) log.Fatal(server.ListenAndServe()) } ``` -------------------------------- ### Running the OpenAPI Discovery Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/builtins-openapi-discovery/README.md Execute the example from the project root using 'go run'. Alternatively, build the example first and then run the binary. Debug logging can be enabled by setting the DEBUG environment variable. ```bash # From the root of the project go run cmd/examples/builtins-openapi-discovery/main.go # Or build and run make build-example EXAMPLE=builtins-openapi-discovery ./bin/builtins-openapi-discovery # Enable debug logging to see agent operations DEBUG=1 go run cmd/examples/builtins-openapi-discovery/main.go ``` -------------------------------- ### Run Provider Convenience Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/README.md Navigate to the provider-convenience directory and run the example. This demonstrates provider-level utility functions. ```bash cd provider-convenience && go run main.go ``` -------------------------------- ### Run the Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/agent-sub-agents/README.md Execute the multi-agent example from the command line. This command assumes you are in the root directory of the project. ```bash go run cmd/examples/agent-sub-agents/main.go ``` -------------------------------- ### Legacy System Configuration Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/existing-systems.md This Go code snippet demonstrates the configuration for a legacy system, including its base URL, authentication type, credentials, and endpoint mappings. This setup is typically used to initialize a wrapper or client for interacting with the legacy system. ```go // Configuration for legacy system config := &SystemConfig{ BaseURL: "https://legacy-api.company.com/api/v1", AuthType: "api_key", Credentials: map[string]string{ "api_key": "legacy_api_key_123", }, Endpoints: map[string]EndpointConfig{ "customers": {}, }, } ``` -------------------------------- ### Build and Run Profiling Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/utils-profiling/README.md Builds and runs the profiling example using make. Ensure the EXAMPLE environment variable is set correctly. ```bash make build-example EXAMPLE=utils-profiling ./bin/utils-profiling ``` -------------------------------- ### Run Authenticated Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/builtins-web-api-client/README.md Run the example with GitHub authentication by providing a personal access token. ```bash GITHUB_API_KEY="your-github-token" go run cmd/examples/builtins-web-api-client/main.go ``` -------------------------------- ### Build the Example (Bash) Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/provider-multimodal/README.md Build the multimodal provider example from the project root or directly using the go build command. ```bash # From the project root make build-example EXAMPLE=provider-multimodal # Or directly go build -o provider-multimodal cmd/examples/provider-multimodal/main.go ``` -------------------------------- ### Install and Run Ollama Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/local-providers.md Installs Ollama on macOS/Linux via curl and starts the Ollama serve command. Verify installation with `ollama --version`. ```bash # Install Ollama # macOS/Linux curl -fsSL https://ollama.ai/install.sh | sh # Or download from https://ollama.ai/download # Verify installation ollama --version # Start Ollama service (if not auto-started) ollama serve ``` -------------------------------- ### Run Provider Metadata Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/provider-metadata/README.md Navigate to the example directory and run the main Go program to execute the provider metadata demonstration. ```bash cd cmd/examples/provider-metadata go run main.go ``` -------------------------------- ### Install and Run Delve for Debugging Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/getting-started/installation.md Instructions to install the Delve debugger and start a debugging session for a Go application's main entry point. ```bash go install github.com/go-delve/delve/cmd/dlv@latest dlv debug cmd/main.go ``` -------------------------------- ### Install and Run Air for Hot Reloading Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/getting-started/installation.md Commands to install the Air tool for automatic Go application reloading during development, initialize its configuration, and start the server. ```bash go install github.com/air-verse/air@latest air init # Creates .air.toml config air # Run with hot reload ``` -------------------------------- ### Build and Run Example with Providers Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/provider-openai-compatible/README.md Build the example application and run it with different LLM providers by setting specific environment variables for each provider. This allows testing integration with OpenRouter, Ollama, and Groq, or running them simultaneously. ```bash # Build the example make example EXAMPLE=openai_api_compatible_providers # Run with OpenRouter export OPENROUTER_API_KEY="your-api-key" ./bin/openai_api_compatible_providers # Run with Ollama export OLLAMA_HOST="http://localhost:11434" ./bin/openai_api_compatible_providers # Run with Groq export GROQ_API_KEY="your-api-key" export GROQ_MODEL="llama3-8b-8192" ./bin/openai_api_compatible_providers # Run with multiple providers simultaneously export OPENROUTER_API_KEY="your-api-key" export OLLAMA_HOST="http://localhost:11434" export GROQ_API_KEY="your-api-key" ./bin/openai_api_compatible_providers ``` -------------------------------- ### Get Date Info with Custom Week Start Source: https://github.com/lexlapax/go-llms/blob/main/docs/api/builtins.md Retrieves date details, including week boundaries, with a specified day for the start of the week. Monday is represented by `1`. ```json { "date": "2024-12-25", "week_start_day": 1 } ``` ```json { "date": "2024-12-25T00:00:00Z", "day_of_week": 3, "end_of_week": "2024-12-29T23:59:59.999999999Z", "start_of_week": "2024-12-23T00:00:00Z", "week_number": 52 } ``` -------------------------------- ### Install Go-LLMs Library Source: https://github.com/lexlapax/go-llms/blob/main/README.md Use 'go get' to add the Go-LLMs library to your project dependencies. ```bash go get github.com/lexlapax/go-llms ``` -------------------------------- ### Production Provider Setup in Go Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/provider-setup.md Demonstrates loading production configuration, creating a production agent, and running a test with state management. Includes output for successful setup, response, and duration. ```go func main() { fmt.Println("šŸ­ Production Provider Setup") fmt.Println("============================") // Load production configuration config := LoadProductionConfig() fmt.Printf("Environment: %s\n", config.Environment) fmt.Printf("Primary Provider: %s\n", config.PrimaryProvider) fmt.Printf("Fallback Provider: %s\n", config.FallbackProvider) // Create production agent prodAgent, err := NewProductionAgent("production-assistant", config) if err != nil { log.Fatalf("Failed to create production agent: %v", err) } // Test production features state := domain.NewState() state.Set("user_input", "Test production setup with timeout and retry logic") startTime := time.Now() result, err := prodAgent.Run(context.Background(), state) duration := time.Since(startTime) if err != nil { fmt.Printf("āŒ Production test failed: %v\n", err) return } if response, exists := result.Get("response"); exists { fmt.Printf("āœ… Production setup successful!\n") fmt.Printf("Response: %v\n", response) fmt.Printf("Duration: %v\n", duration) } fmt.Println("\nšŸ“Š Production Features Enabled:") fmt.Printf(" ā±ļø Timeout: %v\n", config.Timeout) fmt.Printf(" šŸ”„ Retry Attempts: %d\n", config.RetryAttempts) fmt.Printf(" šŸ“ˆ Monitoring: %t\n", config.Monitoring) fmt.Printf(" šŸ” Debug: %t\n", config.Debug) } ``` -------------------------------- ### Run the Example Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/builtins-discovery/README.md Set the OPENAI_API_KEY environment variable if needed, then run the main Go program. ```bash # Optional: Set API key for agent demonstration export OPENAI_API_KEY="your-api-key" # Run the example go run main.go ``` -------------------------------- ### LLMAgentImpl Usage Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/technical/api-reference/agents.md Shows how to initialize and configure an LLMAgentImpl, including setting up the provider, system prompt, history, and tools. It also demonstrates tool registration and execution. ```go llmAgent := agent.NewLLMAgent(agent.LLMAgentConfig{ AgentConfig: agent.AgentConfig{ Name: "assistant", Description: "AI-powered assistant", }, Provider: openaiProvider, SystemPrompt: "You are a helpful AI assistant.", MaxHistory: 10, Temperature: 0.7, Model: "gpt-4", Tools: []string{"http_request", "file_reader"}, } // Register tools for _, toolName := range config.Tools { tool := tools.GetTool(toolName) llmAgent.RegisterTool(tool) } // Execute result, err := llmAgent.Execute(ctx, "Find information about Go programming") ``` -------------------------------- ### Example: Setup Complex Analysis Orchestrator Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/advanced/workflow-orchestration.md Demonstrates how to instantiate a `HierarchicalWorkflow` for a complex analysis task, configuring its coordinator, sub-workflows, and orchestration strategy. ```go // Example: Complex analysis workflow analysisOrchestrator := &HierarchicalWorkflow{ name: "comprehensive_analysis", coordinator: core.NewLLMAgent("orchestrator", provider, core.WithSystemPrompt("Coordinate complex multi-stage analysis workflows"), ), subWorkflows: map[string]Workflow{ "data_extraction": dataExtractionWorkflow, "statistical_analysis": statisticalWorkflow, "ml_prediction": mlPredictionWorkflow, "report_generation": reportingWorkflow, }, strategy: &AdaptiveOrchestrationStrategy{ requirementsAnalyzer: requirementsAgent, dependencyResolver: dependencyAgent, resultAggregator: aggregatorAgent, }, } ``` -------------------------------- ### Main Application Setup with Gin (Go) Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/examples/research-synthesis.md Sets up the research synthesis system configuration, initializes the system, and configures a Gin web server with API routes for research management and metrics. Ensure necessary imports like 'log', 'net/http', and 'github.com/gin-gonic/gin' are present. ```go func main() { config := &ResearchConfig{ DatabaseURL: "postgres://user:pass@localhost/research_db?sslmode=disable", MaxSources: 50, MinSourceCredibility: 0.6, FactCheckEnabled: true, BiasDetectionEnabled: true, MaxReportLength: 5000, CitationStyle: "APA", QualityThresholds: QualityThresholds{ MinSourceCount: 3, MinCredibilityScore: 0.6, MinFactualAccuracy: 0.7, MaxBiasScore: 0.4, MinSynthesisQuality: 0.7, }, } system, err := NewResearchSynthesisSystem(config) if err != nil { log.Fatal("Failed to create research system:", err) } // Setup HTTP server r := gin.Default() // API routes api := r.Group("/api/v1") { api.POST("/research", system.StartResearchHandler) api.GET("/projects/:id", system.GetProjectHandler) api.GET("/projects/:id/report", system.GetReportHandler) api.GET("/metrics", gin.WrapH(promhttp.Handler())) } // Health check r.GET("/health", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{ "status": "healthy", "max_sources": config.MaxSources, "citation_style": config.CitationStyle, } } log.Println("Research Synthesis System starting on :8080") log.Fatal(r.Run(":8080")) } ``` -------------------------------- ### Run Example Script Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/tools-script-dynamic/README.md Navigates to the example directory and runs the main Go program. This command executes the dynamic tool registration and discovery logic. ```bash cd cmd/examples/tools-script-dynamic go run main.go ``` -------------------------------- ### Setup Agent Communication Channel Source: https://github.com/lexlapax/go-llms/blob/main/docs/technical/agents/multi-agent-systems.md Configures the communication channel for a given agent by creating a receive channel and starting a goroutine to handle incoming messages. ```go func (s *DefaultMultiAgentSystem) setupAgentCommunication(agent Agent) error { agentID := agent.ID() // Create communication channel msgChan, err := s.communicator.Receive(agentID) if err != nil { return err } // Start message handling for agent go s.handleAgentMessages(agentID, msgChan) return nil } ``` -------------------------------- ### Initialize and Run Persistent Memory Agent Example Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/agent-memory.md Demonstrates the initialization of a PersistentMemoryAgent, starting a new session, engaging in a conversation, generating a summary, saving the session, and listing user sessions. ```go func main() { fmt.Println("🧠 Agent Memory - Persistent Memory and Sessions") fmt.Println("=============================================") // Create persistent memory agent agent, err := NewPersistentMemoryAgent("persistent-assistant", "anthropic/claude-3-5-haiku", "./sessions") if err != nil { log.Fatalf("Failed to create agent: %v", err) } ctx := context.Background() userID := "user123" // Start new session sessionMetadata := map[string]interface{}{ "user_name": "Alice", "topic": "Go programming help", "session_type": "learning", } session, err := agent.StartSession(userID, sessionMetadata) if err != nil { log.Fatalf("Failed to start session: %v", err) } fmt.Printf("šŸ“ Session %s started for user %s\n", session.ID, userID) // Have a conversation conversations := []string{ "Hi, I'm learning Go programming. Can you help me understand interfaces?", "Can you show me a simple interface example?", "How do I implement that interface?", "Thank you! This is very helpful.", } for i, input := range conversations { fmt.Printf("\n--- Turn %d ---\n", i+1) fmt.Printf("šŸ‘¤ User: %s\n", input) response, err := agent.ProcessInput(ctx, input) if err != nil { log.Printf("Error: %v", err) continue } fmt.Printf("šŸ¤– Assistant: %s\n", response) } // Generate session summary summary, err := agent.GetSessionSummary(ctx) if err != nil { log.Printf("Failed to generate summary: %v", err) } else { fmt.Printf("\nšŸ“„ Session Summary: %s\n", summary) } // Save session explicitly if err := agent.SaveSession(); err != nil { log.Printf("Failed to save session: %v", err) } // List all sessions for user sessions, err := agent.ListUserSessions(userID) if err != nil { log.Printf("Failed to list sessions: %v", err) } else { fmt.Printf("\nšŸ“š User Sessions:\n") for i, s := range sessions { fmt.Printf("%d. %s - %s (%d messages)\n", i+1, s.ID, s.Summary, s.MessageCount) } } // Demonstrate session reload fmt.Printf("\nšŸ”„ Reloading session...\n") newAgent, _ := NewPersistentMemoryAgent("reloaded-assistant", "anthropic/claude-3-5-haiku", "./sessions") if err := newAgent.LoadSession(session.ID); err != nil { log.Printf("Failed to reload session: %v", err) } else { fmt.Printf("āœ… Session reloaded successfully\n") // Continue conversation from memory ``` -------------------------------- ### Legacy Manual Mock Setup Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/advanced/testing-strategies.md Illustrates a legacy approach to manual mock setup for providers, highlighting its verbosity and potential for errors compared to modern mocking utilities. ```go // Legacy approach - verbose and error-prone type OldMockProvider struct { generateFunc func(ctx context.Context, prompt string) (string, error) } func (p *OldMockProvider) Generate(ctx context.Context, prompt string) (string, error) { if strings.Contains(prompt, "error") { return "", errors.New("simulated error") } return "manual mock response", nil } ``` -------------------------------- ### Example Pipeline Creation and Execution Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/data-pipelines.md Demonstrates how to create a data pipeline platform, build a complex pipeline with multiple stages, and then list and run pipelines. ```go func main() { fmt.Println("šŸ­ Enterprise Data Pipeline Platform") fmt.Println("===================================") // Create platform platform := NewDataPipelinePlatform() // Build a pipeline builder := NewPipelineBuilder("customer-insights-pipeline"). WithOwner("data-team"). WithTags("production", "customer", "analytics"). AddStage("file_source", "customer_data_source", map[string]interface{}{ "directory": "./customer_data", "pattern": "*.json", }). AddStage("llm_processor", "insight_extractor", map[string]interface{}{ "provider": "openai/gpt-4o", "prompt_template": "Extract customer insights from: {{.data}}", "max_tokens": 500, }). AddStage("validator", "insight_validator", map[string]interface{}{ "schema": map[string]interface{}{ "type": "object", "properties": map[string]interface{}{ "customer_id": map[string]interface{}{"type": "string"}, "insights": map[string]interface{}{"type": "array"}, "sentiment": map[string]interface{}{"type": "string"}, }, "required": []string{"customer_id", "insights"}, }, }). AddStage("database_sink", "postgres_writer", map[string]interface{}{ "connection_string": "postgres://localhost/insights", "table": "customer_insights", "batch_size": 50, }). WithSchedule(&Schedule{ Type: "interval", Interval: 1 * time.Hour, MaxRuns: 24, // Run for 24 hours // Create pipeline pipeline, err := platform.CreatePipeline(builder) if err != nil { log.Fatalf("Failed to create pipeline: %v", err) } fmt.Printf("āœ… Created pipeline: %s\n", pipeline.ID) // List pipelines pipelines := platform.ListPipelines(PipelineFilter{ Tags: []string{"production"}, fmt.Printf("\nšŸ“‹ Production Pipelines:\n") for _, p := range pipelines { fmt.Printf(" - %s (%s): %s\n", p.Name, p.ID, p.Status) } // Run pipeline manually fmt.Printf("\nšŸš€ Running pipeline...\n") run, err := platform.RunPipeline(pipeline.ID, nil) if err != nil { log.Printf("Failed to run pipeline: %v", err) } else { fmt.Printf("Pipeline run started: %s\n", run.ID) } // Wait for completion (in practice, use proper synchronization) } ``` -------------------------------- ### Implement Response Caching in Go Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/advanced/troubleshooting.md Use an LRU cache to store responses and reduce latency. This example shows a basic `Get` method that checks cache validity based on TTL. ```go type ResponseCache struct { cache *lru.Cache ttl time.Duration } func (c *ResponseCache) Get(key string) (interface{}, bool) { if val, ok := c.cache.Get(key); ok { entry := val.(*CacheEntry) if time.Since(entry.Time) < c.ttl { return entry.Data, true } c.cache.Remove(key) } return nil, false } ``` -------------------------------- ### Example Usage: Registering and Discovering Tools Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/advanced/custom-tools.md Demonstrates how to initialize a tool registry, register a tool with its metadata, and then discover tools using category and tag filters. ```go registry := NewDiscoverableTools() // Register tools registry.Register(weatherTool, ToolMetadata{ Name: "weather_get", Category: "external_api", Description: "Fetches weather information", Version: "1.0.0", Tags: []string{"weather", "api", "location"}, RequiredAuth: []string{"WEATHER_API_KEY"}, Examples: []ToolExample{ { Description: "Get weather for a city", Input: map[string]interface{}{"location": "London"}, Output: map[string]interface{}{"temperature": 20, "conditions": "Cloudy"}, }, }, }) // Discover tools apiTools := registry.Discover(WithCategory("external_api")) weatherTools := registry.Discover(WithTags("weather")) ``` -------------------------------- ### Filter by Date Range (Last Week) Source: https://github.com/lexlapax/go-llms/blob/main/docs/api/builtins.md Get items published within a specific date range. Ensure the 'after' field is set to the desired start date in ISO 8601 format. ```json { "after": "2024-03-15T00:00:00Z", "feed": { "items": [ { "published": "2024-03-20T10:00:00Z", "title": "Today's News" }, { "published": "2024-03-10T10:00:00Z", "title": "Last Week's Update" }, { "published": "2024-01-01T10:00:00Z", "title": "Old Article" } ] } } ``` ```json { "filtered_out": 2, "items": [ { "published": "2024-03-20T10:00:00Z", "title": "Today's News" } ], "total_items": 3 } ``` -------------------------------- ### Package Documentation Structure Source: https://github.com/lexlapax/go-llms/blob/main/CONTRIBUTING-DOCS.md Document packages with a clear purpose statement, detailed description, key features, usage examples, and architectural notes using markdown headers. Start with the package name and its purpose. ```go // Package name provides brief description of the package purpose. // // Detailed description explaining the package's role, key features, // and primary use cases. Include architectural notes if relevant. // // # Key Features // // - Feature 1: Description // - Feature 2: Description // - Feature 3: Description // // # Usage Example // // provider := provider.NewOpenAIProvider(apiKey, model) // result, err := provider.Generate(ctx, prompt) // if err != nil { // // handle error // } // // # Architecture Notes // // Additional context about design decisions, patterns used, // or integration points with other packages. package name ``` ```go // Package provider implements LLM provider interfaces and implementations. // // This package provides a unified interface for interacting with various // LLM providers including OpenAI, Anthropic, Google, and others. It handles // authentication, request formatting, response parsing, and error handling // for each provider while maintaining a consistent API. // // # Supported Providers // // - OpenAI: GPT models, embeddings, function calling // - Anthropic: Claude models with streaming support // - Google: Gemini models via Vertex AI and direct API // - Ollama: Local model inference // - OpenRouter: Access to multiple models via single API // // # Usage Example // // provider := provider.NewOpenAIProvider(apiKey, "gpt-4") // result, err := provider.Generate(ctx, prompt) // if err != nil { // log.Fatal(err) // } // fmt.Println(result) package provider ``` -------------------------------- ### Define and Use Schemas for Data Extraction Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/getting-started/key-concepts.md Define a JSON schema to specify the desired structure for AI responses and use it to get validated, structured data. This example shows how to extract weather information. ```go // Define what you want weatherSchema := &schema.Schema{ Type: "object", Properties: map[string]*schema.Schema{ "condition": {Type: "string"}, "temperature": {Type: "number"}, "wind_speed": {Type: "number"}, }, Required: []string{"condition", "temperature"}, } // Get structured data result, err := provider.GenerateWithSchema(ctx, "What's the weather in NYC?", weatherSchema) // result is guaranteed to match your schema weatherData := result.(*WeatherData) fmt.Printf("It's %s and %v°F", weatherData.Condition, weatherData.Temperature) ``` -------------------------------- ### Initiate and Conduct Distributed Research Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/examples/advanced-projects.md Initiates a distributed research project with specified parameters and then starts the collaborative research process. This example demonstrates setting up a project, handling potential errors during initiation, and running the research concurrently. ```go package main import ( "context" "fmt" "log" "time" "lexlapax/go-llms/collective" ) func main() { ctx := context.Background() researchProposal := collective.ResearchProposal{ Title: "Advanced AI Model Research", Duration: 90 * 24 * time.Hour, // 90 days Milestones: []string{"literature_review", "methodology", "experimentation", "analysis", "publication"}, }, RequiredExpertise: []string{"ai_theory", "distributed_systems", "complexity_science"}, } fmt.Println("Initiating distributed research project...") project, err := collective.InitiateDistributedResearch(ctx, researchProposal) if err != nil { log.Printf("Failed to initiate research: %v", err) } else { fmt.Printf("Research project initiated: %s\n", project.Title) fmt.Printf("Participating nodes: %d\n", len(project.ParticipatingNodes)) // Start collaborative research go func() { if err := collective.ConductCollaborativeResearch(ctx, project); err != nil { log.Printf("Research project error: %v", err) } else { fmt.Printf("Research project completed: %s\n", project.Title) } }() } // Keep the collective running select {} } ``` -------------------------------- ### datetime_info Tool Source: https://github.com/lexlapax/go-llms/blob/main/docs/api/builtins.md Get comprehensive information about a specific date including day/week/month/year info and period boundaries. The tool accepts dates in various formats but prefers RFC3339. It can work with different timezones and allows customizing the week start day. ```APIDOC ## datetime_info ### Description Get comprehensive information about a specific date including day/week/month/year info and period boundaries. ### Input Schema - **Type**: object - **date** (string) - Required - The date to analyze. Prefers RFC3339 format. - **timezone** (string) - Optional - The timezone to use for the analysis (e.g., "America/New_York"). - **week_start_day** (integer) - Optional - The day of the week to consider as the start (1 for Monday, 7 for Sunday). ### Output Schema - **Type**: object - **date** (string) - The input date, potentially adjusted for timezone. - **day_of_month** (integer) - The day of the month. - **day_of_week** (integer) - The day of the week (0 for Sunday, 6 for Saturday). - **day_of_week_iso** (integer) - The ISO 8601 day of the week (1 for Monday, 7 for Sunday). - **day_of_week_name** (string) - The name of the day of the week (e.g., "Friday"). - **day_of_year** (integer) - The day of the year. - **is_leap_year** (boolean) - Indicates if the year is a leap year. - **month** (integer) - The month number (1 for January, 12 for December). - **month_name** (string) - The name of the month (e.g., "March"). - **year** (integer) - The year. - **week_number** (integer) - The ISO 8601 week number of the year. - **week_year** (integer) - The ISO 8601 week year. - **days_in_month** (integer) - The total number of days in the month. - **quarter** (integer) - The quarter of the year (1-4). - **start_of_week** (string) - The start of the week for the given date. - **end_of_week** (string) - The end of the week for the given date. - **start_of_month** (string) - The start of the month for the given date. - **end_of_month** (string) - The end of the month for the given date. - **start_of_quarter** (string) - The start of the quarter for the given date. - **end_of_quarter** (string) - The end of the quarter for the given date. - **start_of_year** (string) - The start of the year for the given date. - **end_of_year** (string) - The end of the year for the given date. ### Examples ##### Example 1: Basic date info **Input:** ```json { "date": "2024-03-15T10:30:00Z" } ``` ##### Example 2: Date info with timezone **Input:** ```json { "date": "2024-07-04", "timezone": "America/New_York" } ``` ##### Example 3: Monday week start **Input:** ```json { "date": "2024-12-25", "week_start_day": 1 } ``` ##### Example 4: Leap year check **Input:** ```json { "date": "2024-02-29" } ``` ##### Example 5: Quarter boundaries **Input:** ```json { "date": "2024-05-15" } ``` ##### Example 6: ISO week numbering **Input:** ```json { "date": "2024-01-01" } ``` ##### Example 7: Component extraction **Input:** ```json { "date": "2024-09-30T14:45:30Z" } ``` ``` -------------------------------- ### Main Application Entry Point with Database Setup in Go Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/guides/databases.md Initializes the logger, database configuration, and database manager. It then creates a conversation repository and demonstrates creating a conversation and performing a database health check. ```go func main() { // Initialize logger logger, _ := zap.NewProduction() defer logger.Sync() // Database configuration config := &DatabaseConfig{ PrimaryURL: "postgres://user:pass@localhost:5432/llm_db?sslmode=disable", ReplicaURL: "postgres://user:pass@replica:5432/llm_db?sslmode=disable", MaxConnections: 25, MaxIdle: 5, ConnLifetime: 30 * time.Minute, QueryTimeout: 30 * time.Second, RetryAttempts: 3, EnableMetrics: true, } // Create database manager dbManager, err := NewDatabaseManager(config, logger) if err != nil { log.Fatal("Failed to create database manager:", err) } // Create repositories conversationRepo := NewConversationRepository(dbManager, nil, logger) // Example usage ctx := context.Background() conv := &EnhancedConversation{ ID: "conv-123", UserID: "user-456", Title: "Test Conversation", Summary: "A test conversation", State: make(map[string]interface{}), Tags: []string{"test", "example"}, Metadata: make(map[string]interface{}), CreatedAt: time.Now(), UpdatedAt: time.Now(), LastActivity: time.Now(), } if err := conversationRepo.Create(ctx, conv); err != nil { logger.Error("Failed to create conversation", zap.Error(err)) } // Health check if err := dbManager.HealthCheck(ctx); err != nil { logger.Error("Database health check failed", zap.Error(err)) } else { logger.Info("Database health check passed") } } ``` -------------------------------- ### Run Example Tests Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/README.md Navigate to an example's directory and run Go tests to verify its functionality. The './...' flag ensures all tests within the directory are executed. ```bash cd go test ./... ``` -------------------------------- ### Start Data Analysis with Detailed Configuration Source: https://github.com/lexlapax/go-llms/blob/main/docs/user-guide/examples/data-analysis.md Initiate a data analysis job by sending a POST request to the /api/v1/analyze endpoint. This example shows how to specify analysis objectives, data sources, types, visualization preferences, statistical methods, and advanced options for data cleaning and anomaly detection. ```bash curl -X POST http://localhost:8080/api/v1/analyze \ -H "Content-Type: application/json" \ -d '{ "name": "Sales Performance Analysis", "description": "Comprehensive analysis of sales data to identify trends and opportunities", "data_sources": ["sales_data.csv", "customer_data.json"], "analysis_type": "descriptive", "objectives": [ "Identify sales trends and patterns", "Analyze customer behavior", "Detect performance anomalies", "Generate actionable insights" ], "requested_by": "analyst@company.com", "priority": "high", "include_predictions": true, "visualization_types": ["bar", "line", "heatmap"], "statistical_methods": ["descriptive", "correlation", "regression"], "options": { "clean_data": true, "detect_anomalies": true, "include_correlations": true, "generate_insights": true, "create_dashboard": true, "confidence_level": 0.95 } }' ``` -------------------------------- ### Run Example: Tool Information Display Source: https://github.com/lexlapax/go-llms/blob/main/cmd/examples/builtins-system-tools/README.md Execute the main program with -llm info to display detailed information about the available system tools. ```bash go run main.go -llm info ```