### LangChainGo: Getting Started with Ollama Source: https://tmc.github.io/langchaingo/docs/index This guide provides instructions on how to get started with LangChainGo by setting up and integrating with Ollama, a local LLM runner. It's a quick setup for beginners to start building applications. ```Go package main import ( "context" "fmt" "log" "github.com/langchain-ai/langchain-go/llms/ollama" ) func main() { ctx := context.Background() // Initialize Ollama with a model (e.g., "llama2") llm, err := ollama.New( ollama.WithModel("llama2"), ) if err != nil { log.Fatalf("Failed to create Ollama client: %v", err) } // Generate content resp, err := llm.GenerateContent(ctx, "What is LangChainGo?") if err != nil { log.Fatalf("Failed to generate content: %v", err) } fmt.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### LangChainGo: Getting Started with OpenAI Source: https://tmc.github.io/langchaingo/docs/index This guide explains how to set up and begin using LangChainGo with OpenAI's language models. It covers the initial configuration for integrating with the OpenAI API. ```Go package main import ( "context" "fmt" "log" "github.com/langchain-ai/langchain-go/llms/openai" ) func main() { ctx := context.Background() // Initialize OpenAI with an API key and model (e.g., "gpt-3.5-turbo") // Ensure OPENAI_API_KEY environment variable is set llm, err := openai.New( openai.WithModel("gpt-3.5-turbo"), ) if err != nil { log.Fatalf("Failed to create OpenAI client: %v", err) } // Generate content resp, err := llm.GenerateContent(ctx, "What is LangChainGo?") if err != nil { log.Fatalf("Failed to generate content: %v", err) } fmt.Println(resp.Choices[0].Message.Content) } ``` -------------------------------- ### LangChainGo How-to Guide Template Source: https://tmc.github.io/langchaingo/docs/contributing/documentation This is a template for writing how-to guides in LangChainGo, focusing on solving specific problems. It includes sections for the problem statement, solution overview, implementation with focused code examples, and considerations for performance, security, and alternatives. ```Go # How to [Specific Task] ## Problem [Clear description of the problem being solved] ## Solution [Brief overview of the approach] ## Implementation ```go // Focused code example ``` ## Considerations​ * [Performance implications] * [Security considerations] * [Alternative approaches] ## Related guides​ * [Link to related how-tos] ``` -------------------------------- ### LangChainGo Runnable Code Example Source: https://tmc.github.io/langchaingo/docs/contributing/documentation This Go code demonstrates how to initialize an LLM client using the LangChainGo library, specifically for OpenAI. It includes proper error handling and is a complete, runnable example as required for tutorials. ```Go package main import ( "context" "fmt" "log" "github.com/tmc/langchaingo/llms/openai" ) func main() { llm, err := openai.New() if err != nil { log.Fatal(err) } // ... rest of example } ``` -------------------------------- ### Generate Package Documentation Example (Go) Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Generates a realistic Go code example for a given package, demonstrating import, basic usage, error handling, and a realistic use case. It uses a prompt template to guide the LLM. ```go func(dg *DocGenerator)generatePackageExample(ctx context.Context, pkg *PackageInfo)(string,error){ template := prompts.NewPromptTemplate(` Create a realistic Go code example showing how to use this package: Package: {{.name}} Description: {{.description}} Key Functions: {{range .functions}}{{if .is_exported}}{{.name}}, {{end}}{{end}} Key Types: {{range .types}}{{if .is_exported}}{{.name}}, {{end}}{{end}} Write a complete, runnable example that shows: 1. Import statement 2. Basic usage 3. Error handling 4. Realistic use case Return only the Go code, no explanations.`, []string{"name","description","functions","types"}) prompt, err := template.Format(map[string]any{ "name": pkg.Name, "description": pkg.Description, "functions": pkg.Functions, "types": pkg.Types, }) if err !=nil{ return"", err } response, err := dg.llm.GenerateContent(ctx,[]llms.MessageContent{ llms.TextParts(llms.ChatMessageTypeHuman, prompt), }) if err !=nil{ return"", err } return strings.TrimSpace(response.Choices[0].Content),nil } ``` -------------------------------- ### LangChainGo Tutorial Template Source: https://tmc.github.io/langchaingo/docs/contributing/documentation This is a template for creating tutorials in LangChainGo. It includes sections for the title, a brief description, what the user will build, prerequisites, and step-by-step implementation guidance with runnable code examples. ```Go # Building [What You're Building] [One sentence description of what the reader will build] ## What you'll build A [type of application] that: - [Feature 1] - [Feature 2] - [Feature 3] ## Prerequisites - Go 1.21+ - [Required API keys] - [Other requirements] ## Step 1: [First Task] [Brief explanation of what this step accomplishes] ```go // Complete, runnable code ``` ## Step 2: [next task]​ [Continue with progressive steps...]## Running the application​ ``` # Clear commands to run ``` ## Next steps​ * [Potential improvements] * [Related tutorials] ``` -------------------------------- ### Run LangChainGo OpenAI Completion Example Source: https://tmc.github.io/langchaingo/docs/getting-started/guide-openai Executes a Go program that uses LangChainGo to get a text completion from OpenAI's models. This requires the OpenAI API key to be set as an environment variable. ```go package main import( "context" "fmt" "log" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/openai" ) funcmain(){ llm, err := openai.New() if err !=nil{ log.Fatal(err) } ctx := context.Background() completion, err := llms.GenerateFromSinglePrompt(ctx, llm, "The first man to walk on the moon", llms.WithTemperature(0.8), llms.WithStopWords([]string{"Armstrong"}), ) if err !=nil{ log.Fatal(err) } fmt.Println("The first man to walk on the moon:") fmt.Println(completion) } ``` -------------------------------- ### Extract Code Examples from Documentation Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Parses a documentation string to extract code examples. It identifies blocks starting with 'Example:', 'Usage:', or '```go' and captures indented lines until a closing '```' or an empty line is encountered. ```go func(ca *CodeAnalyzer) extractExamples(doc string) []string { // Extract code examples from documentation var examples []string lines := strings.Split(doc, "\n") var inExample bool var currentExample strings.Builder for _, line := range lines { rimmed := strings.TrimSpace(line) if strings.HasPrefix(trimmed, "Example:") || strings.HasPrefix(trimmed, "Usage:") || strings.Contains(trimmed, "```go") { inExample = true currentExample.Reset() continue } if inExample { if strings.Contains(trimmed, "```") || (trimmed == "" && currentExample.Len() > 0) { if currentExample.Len() > 0 { examples = append(examples, currentExample.String()) currentExample.Reset() } inExample = false continue } if strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") { currentExample.WriteString(strings.TrimPrefix(strings.TrimPrefix(line, " "), "\t")) currentExample.WriteString("\n") } } } return examples } ``` -------------------------------- ### Create and Run LangChainGo Agent Executor Source: https://tmc.github.io/langchaingo/docs/modules/agents/executor/getting-started This Go code demonstrates how to create and run an agent executor using LangChainGo. It initializes an OpenAI LLM, a SerpAPI tool, and a Calculator tool. It then creates a one-shot agent and an executor, and runs a question through the executor. ```go package main import( "context" "fmt" "os" "github.com/tmc/langchaingo/agents" "github.com/tmc/langchaingo/chains" "github.com/tmc/langchaingo/llms/openai" "github.com/tmc/langchaingo/tools" "github.com/tmc/langchaingo/tools/serpapi" ) funcmain(){ if err :=run(); err !=nil{ fmt.Fprintln(os.Stderr, err) os.Exit(1) } } funcrun()error{ llm, err := openai.New() if err !=nil{ return err } search, err := serpapi.New() if err !=nil{ return err } agentTools :=[]tools.Tool{ tools.Calculator{}, search, } agent := agents.NewOneShotAgent(llm, agentTools, agents.WithMaxIterations(3)) executor := agents.NewExecutor(agent) question :="Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?" answer, err := chains.Run(context.Background(), executor, question) fmt.Println(answer) return err } ``` -------------------------------- ### Build Documentation Locally Source: https://tmc.github.io/langchaingo/docs/contributing/documentation Commands to build and start a local development server for the documentation using npm. This allows for live previewing of changes. ```shell cd docs npminstall npm run start ``` -------------------------------- ### Manage Package Examples (Go) Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Manages the generation and appending of examples for Go packages. If no examples exist, it calls `generatePackageExample`. It also iterates through functions to generate examples for exported functions that lack them. ```go func(dg *DocGenerator)generateExamples(pkg *PackageInfo)error{ ctx := context.Background() // Generate package-level usage example iflen(pkg.Examples)==0{ example, err := dg.generatePackageExample(ctx, pkg) if err ==nil&& example !=""{ pkg.Examples =append(pkg.Examples, ExampleInfo{ Name:"Basic Usage", Code: example, Doc:"Basic usage example", }) } } // Generate function examples for i :=range pkg.Functions { iflen(pkg.Functions[i].Examples)==0&& pkg.Functions[i].IsExported { example, err := dg.generateFunctionExample(ctx,&pkg.Functions[i], pkg) if err ==nil&& example !=""{ pkg.Functions[i].Examples = append(pkg.Functions[i].Examples, example) } } } returnnil } ``` -------------------------------- ### Run LangChainGo Ollama completion example Source: https://tmc.github.io/langchaingo/docs/getting-started/guide-ollama This command executes a Go program that uses LangChainGo to interact with a locally running Ollama instance for text completion. ```Shell go run github.com/tmc/langchaingo/examples/ollama-completion-example@main ``` -------------------------------- ### Configure LLM Providers in LangChainGo Source: https://tmc.github.io/langchaingo/docs/how-to This guide explains how to configure different Language Model (LLM) providers within your LangChainGo projects. It covers the basic setup required to connect to various LLM services. ```Go package main import ( "context" "fmt" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/openai" ) func main() { ctx := context.Background() llm, err := openai.New( openai.WithModel("gpt-3.5-turbo"), ) if err != nil { panic(err) } content, err := llm.Call(ctx, "What is LangChainGo?", nil) if err != nil { panic(err) } fmt.Println(content) } ``` -------------------------------- ### Load Documentation Templates Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Loads various documentation templates, including a package documentation template with sections for name, description, installation, usage (with examples), and API reference (functions). ```go func (dg *DocGenerator) loadTemplates() error { // Package documentation template packageTmpl := `# {{.Name}} {{.Description}} ## Installation '''bash go get {{.Path}} ''' ## Usage {{if .Examples}} {{range .Examples}} '''go {{.Code}} ''' {{end}} {{end}} ## API Reference {{if .Functions}} ### Functions {{range .Functions}} {{if .IsExported}} ``` -------------------------------- ### LangChainGo Project Setup Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation This snippet demonstrates the initial setup for a Go project using LangChainGo to build a smart documentation generator. It includes creating a project directory, initializing Go modules, and fetching necessary dependencies like LangChainGo and Go analysis tools. ```Go mkdir smart-docs cd smart-docs go mod init smart-docs go get github.com/tmc/langchaingo go get golang.org/x/tools/go/packages go get golang.org/x/tools/go/ast/astutil ``` -------------------------------- ### Go Function Examples Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Illustrates the usage of Go functions with practical code examples. This section is rendered only if examples are provided for the function. ```go {{if .Examples}} **Example:** {{range .Examples}} '''go {{.}} ''' {{end}} {{end}} ``` -------------------------------- ### Configure SerpAPI Key Source: https://tmc.github.io/langchaingo/docs/modules/agents/executor/getting-started This snippet shows how to set the SerpAPI environment variable in a .env file, which is required for using the SerpAPI tool within LangChainGo. ```shell SERPAPI_API_KEY="..." ``` -------------------------------- ### Run LangChainGo Mistral Completion Example Source: https://tmc.github.io/langchaingo/docs/getting-started/guide-mistral Executes a Go program that uses LangChainGo to interact with the Mistral API for text completion. This command assumes the Go environment is set up and the Mistral API key is configured. ```bash go run github.com/tmc/langchaingo/examples/mistral-completion-example@main ``` -------------------------------- ### Generate Function Documentation Example (Go) Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Generates a Go code example for a specific function, including its signature and parameters. The example demonstrates how to call the function realistically and includes error handling if necessary. It relies on a prompt template for LLM guidance. ```go func(dg *DocGenerator)generateFunctionExample(ctx context.Context, fn *FunctionInfo, pkg *PackageInfo)(string,error){ template := prompts.NewPromptTemplate(` Create a Go code example for this function: Function: {{.name}} Signature: {{.signature}} Package: {{.package}} {{if .parameters}}Parameters: {{range .parameters}}{{.name}} {{.type}}, {{end}}{{end}} Write a realistic example showing how to call this function. Include proper error handling if needed. Return only the Go code snippet.`, []string{"name","signature","package","parameters"}) prompt, err := template.Format(map[string]any{ "name": fn.Name, "signature": fn.Signature, "package": pkg.Name, "parameters": fn.Parameters, }) if err !=nil{ return"", err } response, err := dg.llm.GenerateContent(ctx,[]llms.MessageContent{ llms.TextParts(llms.ChatMessageTypeHuman, prompt), }) if err !=nil{ return"", err } return strings.TrimSpace(response.Choices[0].Content),nil } ``` -------------------------------- ### Implement Few-Shot Prompting in LangChainGo Source: https://tmc.github.io/langchaingo/docs/how-to Learn how to implement few-shot prompting techniques in LangChainGo to improve LLM performance by providing examples within the prompt. ```Go package main import ( "fmt" "github.com/tmc/langchaingo/prompts" ) func main() { // Define a template with examples (few-shot) template := """ Convert the following movie titles into emoji. Back to the Future: 👨‍🚀🚗💨 Batman: The Dark Knight: 🦇🌃 {{.movie_title}}: "" " // Create a PromptTemplate object promptTemplate, err := prompts.NewPromptTemplate(template, []string{"movie_title"}) if err != nil { panic(err) } // Format the prompt with a new movie title formattedPrompt, err := promptTemplate.Format(map[string]interface{}{"movie_title": "The Matrix"}) if err != nil { panic(err) } fmt.Println(formattedPrompt) } ``` -------------------------------- ### LangChainGo Ollama completion example in Go Source: https://tmc.github.io/langchaingo/docs/getting-started/guide-ollama This Go program demonstrates how to use LangChainGo with Ollama to generate text completions. It initializes the Ollama LLM with a specified model and uses a streaming function to print the output. ```Go package main import( "context" "fmt" "log" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/ollama" ) funcmain(){ llm, err := ollama.New(ollama.WithModel("llama2")) if err !=nil{ log.Fatal(err) } ctx := context.Background() completion, err := llms.GenerateFromSinglePrompt( ctx, llm, "Human: Who was the first man to walk on the moon?\nAssistant:", llms.WithTemperature(0.8), llms.WithStreamingFunc(func(ctx context.Context, chunk []byte)error{ fmt.Print(string(chunk)) returnnil }), ) if err !=nil{ log.Fatal(err) } _= completion } ``` -------------------------------- ### Project Setup for AI Code Reviewer in Go Source: https://tmc.github.io/langchaingo/docs/tutorials/code-reviewer This snippet demonstrates the initial project setup for building an AI code reviewer using Go and LangChainGo. It includes creating a project directory, initializing Go modules, and fetching the LangChainGo library. ```Go mkdir ai-code-reviewer cd ai-code-reviewer go mod init code-reviewer go get github.com/tmc/langchaingo ``` -------------------------------- ### LangChainGo Project Setup Source: https://tmc.github.io/langchaingo/docs/tutorials/basic-chat-app Commands to set up a new Go project and add LangChainGo as a dependency for building a chat application. ```bash mkdir langchain-chat-app cd langchain-chat-app go mod init chat-app go get github.com/tmc/langchaingo ``` -------------------------------- ### Install LangChainGo Source: https://tmc.github.io/langchaingo/docs/modules/model_io/models/llms/Integrations/groq Command to install the LangChainGo library into your Go project. This is the first step to using LangChainGo functionalities. ```bash go get github.com/tmc/langchaingo ``` -------------------------------- ### LangChainGo Agents Conceptual Guide and How-to Source: https://tmc.github.io/langchaingo/docs/modules/agents/agents This entry covers the conceptual aspects of Agents in LangChainGo, along with practical guidance on their implementation, as found in the How-to Guides. ```Go ## 📄️ Agents Conceptual Guide • How-to Guides ``` -------------------------------- ### Go Text Splitting Example Source: https://tmc.github.io/langchaingo/docs/modules/data_connection/text_splitters/examples Demonstrates how to use LangChainGo's text splitting capabilities. This example loads a text file, configures a RecursiveCharacter splitter with specified chunk size and overlap, and then splits the document accordingly. It handles file opening and potential errors during loading and splitting. ```Go func main() { func textToSplit() []schema.Document { f, err := os.Open("./splitters/docs/transcript.txt") if err != nil { fmt.Println("Error opening file: ", err) } p := documentloaders.NewText(f) split := textsplitter.NewRecursiveCharacter() split.ChunkSize = 300 // size of the chunk is number of characters split.ChunkOverlap = 30 // overlap is the number of characters that the chunks overlap docs, err := p.LoadAndSplit(context.Background(), split) if err != nil { fmt.Println("Error loading document: ", err) } log.Println("Document loaded: ", len(docs)) } } ``` -------------------------------- ### Create Dynamic Prompt Templates in LangChainGo Source: https://tmc.github.io/langchaingo/docs/how-to This guide explains how to create dynamic prompt templates in LangChainGo, allowing for flexible and context-aware prompt generation for LLM interactions. ```Go package main import ( "fmt" "github.com/tmc/langchaingo/prompts" ) func main() { // Define a template string with variables template := "Translate the following text from {{.source_lang}} to {{.target_lang}}: {{.text_to_translate}}" // Create a PromptTemplate object promptTemplate, err := prompts.NewPromptTemplate(template, []string{"source_lang", "target_lang", "text_to_translate"}) if err != nil { panic(err) } // Define the variables to fill the template sinputVariables := map[string]interface{}{ "source_lang": "English", "target_lang": "French", "text_to_translate": "Hello, how are you?", } // Format the prompt using the variables formattedPrompt, err := promptTemplate.Format(**inputVariables) if err != nil { panic(err) } fmt.Println(formattedPrompt) } ``` -------------------------------- ### LangChainGo Text Splitter Examples Source: https://tmc.github.io/langchaingo/docs/modules/data_connection/text_splitters This section provides examples of how to use Text Splitters in LangChainGo. Text Splitters are essential for dividing large texts into smaller, manageable chunks, which is crucial for processing with language models and enhancing vector store search performance. The examples demonstrate practical applications of these utilities. ```Go # This section is intended to contain code examples for Text Splitters. # Actual code snippets would be provided here to demonstrate usage. # For instance, initializing a splitter and splitting a document: # import ( # "github.com/tmc/langchaingo/textsplitter" # ) # # func main() { # ssplitter := textsplitter.NewRecursiveCharacterTextSplitter( # textsplitter.WithChunkSize(1000), # textsplitter.WithChunkOverlap(200), # ) # text := "Your long document text here..." # chunks := splitter.SplitText(text) # // Process the chunks... # } ``` -------------------------------- ### Basic Agent Setup in LangChainGo Source: https://tmc.github.io/langchaingo/docs/modules/agents Demonstrates how to set up a basic agent in LangChainGo. This involves creating a slice of tools (e.g., Calculator, WebSearch), initializing a one-shot agent with an LLM and the tools, and then creating an executor to call the agent with a sample input. ```Go package main import ( "context" "fmt" "github.com/langchain-ai/langchain-go/agents" "github.com/langchain-ai/langchain-go/llms" "github.com/langchain-ai/langchain-go/tools" ) func main() { ctx := context.Background() // Initialize LLM (replace with your actual LLM initialization) llm := llms.NewOpenAI(llms.WithAPIKey("YOUR_OPENAI_API_KEY")) // Create tools tools := []tools.Tool{ t tools.Calculator{}, tools.WebSearch{APIKey: "your-api-key"}, } // Create agent agent := agents.NewOneShotAgent(llm, tools) // Create executor executor := agents.NewExecutor(agent) // Execute result, err := executor.Call(ctx, map[string]any{ "input": "What is 25 * 4 and what's the weather like today?", }) if err != nil { fmt.Printf("Error executing agent: %v\n", err) return } fmt.Printf("Agent result: %v\n", result["output"]) } ``` -------------------------------- ### Install LangChainGo Fake LLM Source: https://tmc.github.io/langchaingo/docs/modules/model_io/models/llms/Integrations/fake This snippet shows how to install the LangChainGo fake LLM package using the go get command. It's a prerequisite for using the fake LLM in your Go projects. ```bash go get "github.com/tmc/langchaingo" ``` -------------------------------- ### Pull llama2 model with Ollama Source: https://tmc.github.io/langchaingo/docs/getting-started/guide-ollama This command downloads the llama2 model from Ollama, which is required for the LangChainGo example. ```Shell ollama pull llama2 ``` -------------------------------- ### LangChainGo Project Setup for Log Analyzer Source: https://tmc.github.io/langchaingo/docs/tutorials/log-analyzer Sets up a new Go project for a log analyzer using LangChainGo. It initializes the Go module and fetches necessary dependencies, including LangChainGo and a logging library. ```Go mkdir log-analyzer cd log-analyzer go mod init log-analyzer go get github.com/tmc/langchaingo go get github.com/sirupsen/logrus # For structured logging examples ``` -------------------------------- ### Create Sample Go Package for Documentation Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation This Go code defines a User struct and a UserService with methods to create and retrieve users. It's used as an example package to be documented by the generator. ```Go // Package user provides user management functionality. package user import ( "errors" "time" ) // User represents a system user. type User struct { ID int `json:"id"` Name string `json:"name"` Email string `json:"email"` Created time.Time `json:"created"` } // UserService handles user operations. type UserService struct { users map[int]*User } // NewUserService creates a new user service. func NewUserService() *UserService { return &UserService{ users: make(map[int]*User), } } // CreateUser creates a new user. func (s *UserService) CreateUser(name, email string) (*User, error) { if name == "" { return nil, errors.New("name cannot be empty") } user := &User{ ID: len(s.users) + 1, Name: name, Email: email, Created: time.Now(), } s.users[user.ID] = user return user, nil } // GetUser retrieves a user by ID. func (s *UserService) GetUser(id int) (*User, error) { user, exists := s.users[id] if !exists { return nil, errors.New("user not found") } return user, nil } ``` -------------------------------- ### Run Vale Linting for Documentation Source: https://tmc.github.io/langchaingo/docs/contributing/documentation Commands to install Vale dependencies, lint all documentation, or run Vale directly on specific files. Vale is used to check documentation style and consistency. ```shell # Install Vale (on macOS) make lint-deps # Lint all documentation make lint-docs # Or run Vale directly vale docs ``` -------------------------------- ### Generate Go Project Documentation Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation The main function parses command-line arguments for project directory, output directory, configuration file, watch mode, and package name. It then initializes the code analyzer and documentation generator. Based on the 'watch' flag, it either generates documentation once or enters a loop to watch for changes and regenerate. ```go package main import ( "encoding/json" "flag" "fmt" "log" "os" "path/filepath" ) func main() { var ( projectDir = flag.String("dir", ".", "Project directory to analyze") outputDir = flag.String("output", "./docs", "Output directory for documentation") configFile = flag.String("config", "", "Configuration file") watch = flag.Bool("watch", false, "Watch for changes and regenerate") packageName = flag.String("package", "", "Specific package to document") ) flag.Parse() // Load configuration config := DocConfig{ OutputDir: *outputDir, IncludePrivate: false, GenerateExamples: true, Style: "markdown", } if *configFile != "" { if err := loadConfig(*configFile, &config); err != nil { log.Printf("Warning: Could not load config file: %v", err) } } // Initialize components analyzer := NewCodeAnalyzer() generator, err := NewDocGenerator() if err != nil { log.Fatal(err) } if *watch { if err := watchAndGenerate(analyzer, generator, *projectDir, config); err != nil { log.Fatal(err) } } else { if err := generateDocs(analyzer, generator, *projectDir, config, *packageName); err != nil { log.Fatal(err) } } } func generateDocs(analyzer *CodeAnalyzer, generator *DocGenerator, projectDir string, config DocConfig, packageName string) error { if packageName != "" { // Document specific package return generatePackageDocs(analyzer, generator, filepath.Join(projectDir, packageName), config) } // Document all packages return filepath.Walk(projectDir, func(path string, info os.FileInfo, err error) error { if err != nil { return err } if !info.IsDir() { return nil } // Skip vendor, .git, and test directories if shouldSkipDir(path) { return filepath.SkipDir } // Check if directory contains Go files hasGoFiles, err := hasGoSourceFiles(path) if err != nil { return err } if hasGoFiles { if err := generatePackageDocs(analyzer, generator, path, config); err != nil { log.Printf("Error documenting package %s: %v", path, err) } } return nil }) } func generatePackageDocs(analyzer *CodeAnalyzer, generator *DocGenerator, packageDir string, config DocConfig) error { fmt.Printf("Analyzing package: %s\n", packageDir) // Analyze package pkg, err := analyzer.AnalyzePackage(packageDir) if err != nil { return fmt.Errorf("analyzing package: %w", err) } // Generate documentation doc, err := generator.GeneratePackageDoc(pkg, config) if err != nil { return fmt.Errorf("generating documentation: %w", err) } // Write to file outputPath := filepath.Join(config.OutputDir, pkg.Name+".md") if err := os.MkdirAll(filepath.Dir(outputPath), 0755); err != nil { return fmt.Errorf("creating output directory: %w", err) } if err := os.WriteFile(outputPath, []byte(doc), 0644); err != nil { return fmt.Errorf("writing documentation: %w", err) } fmt.Printf("Generated documentation: %s\n", outputPath) return nil } func watchAndGenerate(analyzer *CodeAnalyzer, generator *DocGenerator, projectDir string, config DocConfig) error { // Simplified file watching - you'd want to use fsnotify for production fmt.Printf("Watching %s for changes...\n", projectDir) for { if err := generateDocs(analyzer, generator, projectDir, config, ""); err != nil { log.Printf("Error generating docs: %v", err) } time.Sleep(30 * time.Second) } } func shouldSkipDir(path string) bool { base := filepath.Base(path) return base == "vendor" || base == ".git" || base == "testdata" || strings.HasSuffix(base, "_test") } func hasGoSourceFiles(dir string) (bool, error) { files, err := os.ReadDir(dir) if err != nil { return false, err } for _, file := range files { if !file.IsDir() && strings.HasSuffix(file.Name(), ".go") && !strings.HasSuffix(file.Name(), "_test.go") { return true, nil } } return false, nil } func loadConfig(filename string, config *DocConfig) error { data, err := os.ReadFile(filename) if err != nil { return err } return json.Unmarshal(data, config) } ``` -------------------------------- ### Mistral Streaming and Non-Streaming Completions (Go) Source: https://tmc.github.io/langchaingo/docs/modules/model_io/models/llms/Integrations/mistral Provides a complete Go example using LangChainGo to interact with Mistral models. It shows how to get both streaming and non-streaming text completions from the Mistral API, including setting temperature and model parameters. ```Go package main import( "context" "fmt" "log" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/mistral" ) funcmain(){ llm, err := mistral.New(mistral.WithModel("open-mistral-7b")) if err !=nil{ log.Fatal(err) } ctx := context.Background() completionWithStreaming, err := llms.GenerateFromSinglePrompt(ctx, llm,"Who was the first man to walk on the moon?", llms.WithTemperature(0.8), llms.WithStreamingFunc(func(ctx context.Context, chunk []byte)error{ fmt.Print(string(chunk)) returnnil }), ) if err !=nil{ log.Fatal(err) } // The full string response will be available in completionWithStreaming after the streaming is complete. // (The Go compiler mandates declared variables be used at least once, hence the `_` assignment. https://go.dev/ref/spec#Blank_identifier) _ = completionWithStreaming completionWithoutStreaming, err := llms.GenerateFromSinglePrompt(ctx, llm,"Who was the first man to go to space?", llms.WithTemperature(0.2), llms.WithModel("mistral-small-latest"), ) if err !=nil{ log.Fatal(err) } fmt.Println("\n"+ completionWithoutStreaming) } ``` -------------------------------- ### Go Code Analysis Engine Setup Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Defines the `CodeAnalyzer` struct and related data structures for capturing Go code information. It includes types for `PackageInfo`, `FunctionInfo`, `TypeInfo`, `FieldInfo`, `ParamInfo`, `ReturnInfo`, `ConstantInfo`, `VariableInfo`, and `ExampleInfo`. The `NewCodeAnalyzer` function initializes the analyzer with a file set. ```go package main import ( "fmt" "go/ast" "go/doc" "go/parser" "go/token" "path/filepath" "strings" "unicode" ) type CodeAnalyzer struct{ fset *token.FileSet } type PackageInfo struct{ Name string`json:"name"` Path string`json:"path"` Description string`json:"description"` Functions []FunctionInfo `json:"functions"` Types []TypeInfo `json:"types"` Constants []ConstantInfo `json:"constants"` Variables []VariableInfo `json:"variables"` Examples []ExampleInfo `json:"examples"` Imports []string`json:"imports"` } type FunctionInfo struct{ Name string`json:"name"` Signature string`json:"signature"` Description string`json:"description"` Parameters []ParamInfo `json:"parameters"` Returns []ReturnInfo `json:"returns"` Examples []string`json:"examples"` IsExported bool`json:"is_exported"` IsMethod bool`json:"is_method"` Receiver string`json:"receiver,omitempty"` } type TypeInfo struct{ Name string`json:"name"` Kind string`json:"kind"`// struct, interface, alias, etc. Description string`json:"description"` Fields []FieldInfo `json:"fields,omitempty"` Methods []string`json:"methods,omitempty"` IsExported bool`json:"is_exported"` } type FieldInfo struct{ Name string`json:"name"` Type string`json:"type"` Tag string`json:"tag,omitempty"` Description string`json:"description"` } type ParamInfo struct{ Name string`json:"name"` Type string`json:"type"` } type ReturnInfo struct{ Type string`json:"type"` Description string`json:"description"` } type ConstantInfo struct{ Name string`json:"name"` Type string`json:"type"` Value string`json:"value"` Description string`json:"description"` IsExported bool`json:"is_exported"` } type VariableInfo struct{ Name string`json:"name"` Type string`json:"type"` Description string`json:"description"` IsExported bool`json:"is_exported"` } type ExampleInfo struct{ Name string`json:"name"` Code string`json:"code"` Doc string`json:"doc"` } funcNewCodeAnalyzer()*CodeAnalyzer { return&CodeAnalyzer{ fset: token.NewFileSet(), } } ``` -------------------------------- ### Basic PromptTemplate Usage Source: https://tmc.github.io/langchaingo/docs/modules/model_io/prompts/prompt_templates Provides an example of creating a `PromptTemplate` and rendering it with specific input variables. It includes error handling for the rendering process. ```Go import"github.com/tmc/langchaingo/prompts" import"log" import"fmt" funcmain(){ // Create a prompt template prompt := prompts.NewPromptTemplate( "What is a good name for a company that makes {{.product}}?", []string{"product"}, ) // Render the template with data result, err := prompt.Format(map[string]any{ "product":"colorful socks", }) if err !=nil{ log.Fatal(err) } fmt.Println(result) // Output: What is a good name for a company that makes colorful socks? } ``` -------------------------------- ### Generate Package Documentation Go Source: https://tmc.github.io/langchaingo/docs/tutorials/smart-documentation Generates documentation for a Go package, optionally enhancing descriptions with AI and generating usage examples. It executes the 'package' template to produce the final documentation string. ```go func(dg *DocGenerator)GeneratePackageDoc(pkg *PackageInfo, config DocConfig)(string,error){ // Enhance descriptions with AI if err := dg.enhanceDescriptions(pkg); err !=nil{ return "", fmt.Errorf("enhancing descriptions: %w", err) } // Generate usage examples if config.GenerateExamples { if err := dg.generateExamples(pkg); err !=nil{ return "", fmt.Errorf("generating examples: %w", err) } } // Apply template var result strings.Builder if err := dg.templates["package"].Execute(&result, pkg); err !=nil{ return "", fmt.Errorf("executing template: %w", err) } return result.String(),nil } ``` -------------------------------- ### F-string Template Syntax Example Source: https://tmc.github.io/langchaingo/docs/modules/model_io/prompts Provides an example of using Python-style f-strings for simple variable substitution within prompts. ```Go template :="Process {document} using {method} with {params}" ``` -------------------------------- ### Example Go Commit Messages Source: https://tmc.github.io/langchaingo/docs/contributing Provides examples of well-formatted commit messages for Go projects, emphasizing clarity and adherence to package-prefixed conventions. ```Go llms/anthropic: implement function calling support memory: fix buffer overflow in conversation memory tools: add calculator tool with error handling all: update dependencies and organize go.mod file ``` -------------------------------- ### Sequential Chain Orchestration in Go Source: https://tmc.github.io/langchaingo/docs/concepts/architecture Illustrates setting up sequential chains in LangChainGo. It covers both simple sequential chains where the output of one directly feeds into the next, and more complex ones with defined input and output keys. ```Go // Sequential chain example chain1 := chains.NewLLMChain(llm, template1) chain2 := chains.NewLLMChain(llm, template2) // For simple sequential chains where output of one feeds to next sequential := chains.NewSimpleSequentialChain([]chains.Chain{chain1, chain2}) // Or for complex sequential chains with specific input/output keys sequential, err := chains.NewSequentialChain( []chains.Chain{chain1, chain2}, []string{"input"},// input keys []string{"final_output"},// output keys ) ``` -------------------------------- ### Install LangChainGo Source: https://tmc.github.io/langchaingo/docs/modules/model_io/models/llms/Integrations/huggingface Command to install the LangChainGo library using the Go package manager. This is a prerequisite for using LangChainGo functionalities. ```bash go get github.com/tmc/langchaingo ``` -------------------------------- ### Jinja2 Template Syntax Example Source: https://tmc.github.io/langchaingo/docs/modules/model_io/prompts Shows an example of using Jinja2 templating syntax, which supports filters, conditionals, and loops, for constructing prompts. ```Go template :=` Dear {{ customer_name | title }}, {% if order_status == "shipped" %} Your order has been shipped! {% else %} Your order is being processed. {% endif %} ` ``` -------------------------------- ### Groq LLM Integration Example in Go Source: https://tmc.github.io/langchaingo/docs/modules/model_io/models/llms/Integrations/groq A Go program demonstrating how to initialize and use Groq's LLM models via LangChainGo. It includes loading the API key from environment variables, setting model parameters, and generating text from a prompt with streaming output. ```Go package main import( "context" "fmt" "log" "os" "github.com/joho/godotenv" "github.com/tmc/langchaingo/llms" "github.com/tmc/langchaingo/llms/openai" ) func main(){ err := godotenv.Load() if err != nil{ log.Fatalf("Error loading .env file") } apiKey := os.Getenv("GROQ_API_KEY") llm, err := openai.New( openai.WithModel("llama3-8b-8192"), openai.WithBaseURL("https://api.groq.com/openai/v1"), openai.WithToken(apiKey), ) if err != nil{ log.Fatal(err) } ctx := context.Background() _, err = llms.GenerateFromSinglePrompt(ctx, llm, "Write a long poem about how golang is a fantastic language.", llms.WithTemperature(0.8), llms.WithMaxTokens(4096), llms.WithStreamingFunc(func(ctx context.Context, chunk []byte)error{ fmt.Print(string(chunk)) return nil }), ) fmt.Println() if err != nil{ log.Fatal(err) } } ``` -------------------------------- ### Create and Format a Go Prompt Template Source: https://tmc.github.io/langchaingo/docs/modules/model_io/prompts Demonstrates how to create a prompt template using Go's text/template syntax and format it with provided values. This is the recommended approach for Go applications. ```Go import"github.com/tmc/langchaingo/prompts" // Create a prompt template template := prompts.NewPromptTemplate( "Write a {{.style}} summary of: {{.content}}", []string{"style","content"}, ) // Format with values result, err := template.Format(map[string]any{ "style":"technical", "content":"recent AI advances", }) // Result: "Write a technical summary of: recent AI advances" ```