Documentation
ΒΆ
Overview ΒΆ
Package langchaingo provides a Go implementation of LangChain, a framework for building applications with Large Language Models (LLMs) through composability.
LangchainGo enables developers to create powerful AI-driven applications by providing a unified interface to various LLM providers, vector databases, and other AI services. The framework emphasizes modularity, extensibility, and ease of use.
Core Components ΒΆ
The framework is organized around several key packages:
- github.com/tmc/langchaingo/llms: Interfaces and implementations for various language models (OpenAI, Anthropic, Google, etc.)
- github.com/tmc/langchaingo/chains: Composable operations that can be linked together to create complex workflows
- github.com/tmc/langchaingo/agents: Autonomous entities that can use tools to accomplish tasks
- github.com/tmc/langchaingo/embeddings: Text embedding functionality for semantic search and similarity
- github.com/tmc/langchaingo/vectorstores: Interfaces to vector databases for storing and querying embeddings
- github.com/tmc/langchaingo/memory: Conversation history and context management
- github.com/tmc/langchaingo/tools: External tool integrations (web search, calculators, databases, etc.)
Quick Start ΒΆ
Basic text generation with OpenAI:
import (
"context"
"log"
"github.com/tmc/langchaingo/llms"
"github.com/tmc/langchaingo/llms/openai"
)
ctx := context.Background()
llm, err := openai.New()
if err != nil {
log.Fatal(err)
}
completion, err := llm.GenerateContent(ctx, []llms.MessageContent{
llms.TextParts(llms.ChatMessageTypeHuman, "What is the capital of France?"),
})
Creating embeddings and using vector search:
import (
"github.com/tmc/langchaingo/embeddings"
"github.com/tmc/langchaingo/schema"
"github.com/tmc/langchaingo/vectorstores/chroma"
)
// Create an embedder
embedder, err := embeddings.NewEmbedder(llm)
if err != nil {
log.Fatal(err)
}
// Create a vector store
store, err := chroma.New(
chroma.WithChromaURL("http://localhost:8000"),
chroma.WithEmbedder(embedder),
)
// Add documents
docs := []schema.Document{
{PageContent: "Paris is the capital of France"},
{PageContent: "London is the capital of England"},
}
store.AddDocuments(ctx, docs)
// Search for similar documents
results, err := store.SimilaritySearch(ctx, "French capital", 1)
Building a chain for question answering:
import ( "github.com/tmc/langchaingo/chains" "github.com/tmc/langchaingo/vectorstores" ) chain := chains.NewRetrievalQAFromLLM( llm, vectorstores.ToRetriever(store, 3), ) answer, err := chains.Run(ctx, chain, "What is the capital of France?")
Provider Support ΒΆ
LangchainGo supports numerous providers:
LLM Providers:
- OpenAI (GPT-3.5, GPT-4, GPT-4 Turbo)
- Anthropic (Claude family)
- Google AI (Gemini, PaLM)
- AWS Bedrock (Claude, Llama, Titan)
- Cohere
- Mistral AI
- Ollama (local models)
- Hugging Face Inference
- And many more...
Embedding Providers:
- OpenAI
- Hugging Face
- Jina AI
- Voyage AI
- Google Vertex AI
- AWS Bedrock
Vector Stores:
- Chroma
- Pinecone
- Weaviate
- Qdrant
- PostgreSQL with pgvector
- Redis
- Milvus
- MongoDB Atlas Vector Search
- OpenSearch
- Azure AI Search
Agents and Tools ΒΆ
Create agents that can use tools to accomplish complex tasks:
import (
"github.com/tmc/langchaingo/agents"
"github.com/tmc/langchaingo/tools/serpapi"
"github.com/tmc/langchaingo/tools/calculator"
)
// Create tools
searchTool := serpapi.New("your-api-key")
calcTool := calculator.New()
// Create an agent
agent := agents.NewMRKLAgent(llm, []tools.Tool{searchTool, calcTool})
executor := agents.NewExecutor(agent)
// Run the agent
result, err := executor.Call(ctx, map[string]any{
"input": "What's the current population of Tokyo multiplied by 2?",
})
Memory and Conversation ΒΆ
Maintain conversation context across multiple interactions:
import ( "github.com/tmc/langchaingo/memory" "github.com/tmc/langchaingo/chains" ) // Create memory memory := memory.NewConversationBuffer() // Create a conversation chain chain := chains.NewConversation(llm, memory) // Have a conversation chains.Run(ctx, chain, "Hello, my name is Alice") chains.Run(ctx, chain, "What's my name?") // Will remember "Alice"
Advanced Features ΒΆ
Streaming responses:
stream, err := llm.GenerateContentStream(ctx, messages)
for stream.Next() {
chunk := stream.Value()
fmt.Print(chunk.Choices[0].Content)
}
Function calling:
tools := []llms.Tool{
{
Type: "function",
Function: &llms.FunctionDefinition{
Name: "get_weather",
Parameters: map[string]any{
"type": "object",
"properties": map[string]any{
"location": map[string]any{"type": "string"},
},
},
},
},
}
content, err := llm.GenerateContent(ctx, messages, llms.WithTools(tools))
Multi-modal inputs (text and images):
parts := []llms.ContentPart{
llms.TextPart("What's in this image?"),
llms.ImagePart("data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQ..."),
}
content, err := llm.GenerateContent(ctx, []llms.MessageContent{
{Role: llms.ChatMessageTypeHuman, Parts: parts},
})
Configuration and Environment ΒΆ
Most providers require API keys set as environment variables:
export OPENAI_API_KEY="your-openai-key" export ANTHROPIC_API_KEY="your-anthropic-key" export GOOGLE_API_KEY="your-google-key" export HUGGINGFACEHUB_API_TOKEN="your-hf-token"
Error Handling ΒΆ
LangchainGo provides standardized error handling:
import "github.com/tmc/langchaingo/llms"
if err != nil {
if llms.IsAuthenticationError(err) {
log.Fatal("Invalid API key")
}
if llms.IsRateLimitError(err) {
log.Println("Rate limited, retrying...")
}
}
Testing ΒΆ
LangchainGo includes comprehensive testing utilities including HTTP record/replay for internal tests. The httprr package provides deterministic testing of HTTP interactions:
import "github.com/tmc/langchaingo/internal/httprr"
func TestMyFunction(t *testing.T) {
rr := httprr.OpenForTest(t, http.DefaultTransport)
defer rr.Close()
client := rr.Client()
// Use client for HTTP requests - they'll be recorded/replayed for deterministic testing
}
Examples ΒΆ
See the examples/ directory for complete working examples including:
- Basic LLM usage
- RAG (Retrieval Augmented Generation)
- Agent workflows
- Vector database integration
- Multi-modal applications
- Streaming responses
- Function calling
Contributing ΒΆ
LangchainGo welcomes contributions! The project follows Go best practices and includes comprehensive testing, linting, and documentation standards.
See CONTRIBUTING.md for detailed guidelines.
Directories
ΒΆ
| Path | Synopsis |
|---|---|
|
Package agents contains the standard interface all agents must implement, implementations of this interface, and an agent executor.
|
Package agents contains the standard interface all agents must implement, implementations of this interface, and an agent executor. |
|
Package callbacks includes a standard interface for hooking into various stages of your LLM application.
|
Package callbacks includes a standard interface for hooking into various stages of your LLM application. |
|
Package chains contains a standard interface for chains, a number of built-in chains and functions for calling and running chains.
|
Package chains contains a standard interface for chains, a number of built-in chains and functions for calling and running chains. |
|
Package documentloaders includes a standard interface for loading documents from a source and implementations of this interface.
|
Package documentloaders includes a standard interface for loading documents from a source and implementations of this interface. |
|
Package embeddings contains helpers for creating vector embeddings from text using different providers.
|
Package embeddings contains helpers for creating vector embeddings from text using different providers. |
|
examples
|
|
|
googleai-reasoning-caching
command
|
|
|
ollama-reasoning-caching
command
|
|
|
anthropic-completion-example
module
|
|
|
anthropic-tool-call-example
module
|
|
|
anthropic-vision-example
module
|
|
|
bedrock-provider-example
module
|
|
|
caching-llm-example
module
|
|
|
chroma-vectorstore-example
module
|
|
|
cohere-llm-example
module
|
|
|
cybertron-embedding-example
module
|
|
|
deepseek-completion-example
module
|
|
|
document-qa-example
module
|
|
|
ernie-chat-example
module
|
|
|
ernie-completion-example
module
|
|
|
ernie-function-call-example
module
|
|
|
googleai-completion-example
module
|
|
|
googleai-streaming-example
module
|
|
|
googleai-tool-call-example
module
|
|
|
groq-completion-example
module
|
|
|
huggingface-llm-example
module
|
|
|
json-mode-example
module
|
|
|
llamafile-completion-example
module
|
|
|
llm-chain-example
module
|
|
|
llmmath-chain-example
module
|
|
|
local-llm-example
module
|
|
|
maritaca-example
module
|
|
|
mistral-completion-example
module
|
|
|
mistral-embedding-example
module
|
|
|
mrkl-agent-example
module
|
|
|
nvidia-chat-completion
module
|
|
|
ollama-chat-example
module
|
|
|
ollama-completion-example
module
|
|
|
ollama-functions-example
module
|
|
|
ollama-stream-example
module
|
|
|
openai-chat-example
module
|
|
|
openai-completion-example
module
|
|
|
openai-embeddings-example
module
|
|
|
openai-function-call-example
module
|
|
|
openai-gpt4-turbo-example
module
|
|
|
openai-gpt4o-example
module
|
|
|
openai-gpt4o-mutil-content
module
|
|
|
openai-jsonformat-example
module
|
|
|
openai-o1-example
module
|
|
|
openai-readme
module
|
|
|
pgvector-vectorstore-example
module
|
|
|
pinecone-vectorstore-example
module
|
|
|
prompt-caching
module
|
|
|
prompt-template-example
module
|
|
|
prompts-with-partial-example
module
|
|
|
qdrant-vectorstore-example
module
|
|
|
reasoning-tokens
module
|
|
|
redis-vectorstore-example
module
|
|
|
sequential-chain-example
module
|
|
|
sql-database-chain-example
module
|
|
|
tutorial-basic-chat-app
module
|
|
|
vertex-completion-example
module
|
|
|
vertex-embedding-example
module
|
|
|
vertexai-palm-chat-example
module
|
|
|
watsonx-llm-example
module
|
|
|
zapier-llm-example
module
|
|
|
zep-memory-chain-example
module
|
|
|
Package exp contains experimental code that is subject to change or removal.
|
Package exp contains experimental code that is subject to change or removal. |
|
Package httputil provides HTTP transport and client utilities for LangChainGo.
|
Package httputil provides HTTP transport and client utilities for LangChainGo. |
|
internal
|
|
|
devtools/examples-updater
command
Package main provides a tool for updating example dependencies.
|
Package main provides a tool for updating example dependencies. |
|
devtools/lint
command
Package lint provides architectural linting for the LangChain Go codebase.
|
Package lint provides architectural linting for the LangChain Go codebase. |
|
devtools/normalize-recordings
command
Package main provides a tool to normalize version information in httprr recordings.
|
Package main provides a tool to normalize version information in httprr recordings. |
|
devtools/rrtool
command
|
|
|
httprr
Package httprr implements HTTP record and replay, mainly for use in tests.
|
Package httprr implements HTTP record and replay, mainly for use in tests. |
|
testutil/testctr
Package testctr provides utilities for setting up testcontainers in tests.
|
Package testctr provides utilities for setting up testcontainers in tests. |
|
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct.
|
Package jsonschema provides very simple functionality for representing a JSON schema as a (nested) struct. |
|
Package llms provides unified support for interacting with different Language Models (LLMs) from various providers.
|
Package llms provides unified support for interacting with different Language Models (LLMs) from various providers. |
|
cache
Package cache provides a generic wrapper that adds caching to a `llms.Model`.
|
Package cache provides a generic wrapper that adds caching to a `llms.Model`. |
|
compliance
Package compliance provides a test suite to verify provider implementations.
|
Package compliance provides a test suite to verify provider implementations. |
|
ernie
Package ernie wrapper around the Baidu Large Language Model Platform APIs.
|
Package ernie wrapper around the Baidu Large Language Model Platform APIs. |
|
googleai
Package googleai provides caching support for Google AI models.
|
Package googleai provides caching support for Google AI models. |
|
googleai/internal/cmd
command
Code generator for vertex.go from googleai.go nolint
|
Code generator for vertex.go from googleai.go nolint |
|
googleai/palm
package palm implements a langchaingo provider for Google Vertex AI legacy PaLM models.
|
package palm implements a langchaingo provider for Google Vertex AI legacy PaLM models. |
|
googleai/vertex
package vertex implements a langchaingo provider for Google Vertex AI LLMs, including the new Gemini models.
|
package vertex implements a langchaingo provider for Google Vertex AI LLMs, including the new Gemini models. |
|
local/internal/localclient
Package localclient provides a client for local LLMs.
|
Package localclient provides a client for local LLMs. |
|
openai
Package openai provides an interface to OpenAI's language models.
|
Package openai provides an interface to OpenAI's language models. |
|
Package memory provides an interface for managing conversational data and a variety of implementations for storing and retrieving that data.
|
Package memory provides an interface for managing conversational data and a variety of implementations for storing and retrieving that data. |
|
sqlite3
Package sqlite3 adds support for chat message history using sqlite3.
|
Package sqlite3 adds support for chat message history using sqlite3. |
|
Package outputparser provides a set of output parsers to process structured or unstructured data from language models (LLMs).
|
Package outputparser provides a set of output parsers to process structured or unstructured data from language models (LLMs). |
|
Package prompts provides utilities for creating and managing prompts for Large Language Models (LLMs).
|
Package prompts provides utilities for creating and managing prompts for Large Language Models (LLMs). |
|
internal/fstring
Package fstring contains template format with f-string.
|
Package fstring contains template format with f-string. |
|
internal/loader
Package loader provides secure filesystem access control for template engines.
|
Package loader provides secure filesystem access control for template engines. |
|
Package schema implements a shared core set of data types for use in langchaingo.
|
Package schema implements a shared core set of data types for use in langchaingo. |
|
testing
|
|
|
llmtest
Package llmtest provides utilities for testing LLM implementations.
|
Package llmtest provides utilities for testing LLM implementations. |
|
Package textsplitter provides tools for splitting long texts into smaller chunks based on configurable rules and parameters.
|
Package textsplitter provides tools for splitting long texts into smaller chunks based on configurable rules and parameters. |
|
Package tools defines a standard interface for tools to be used by agents.
|
Package tools defines a standard interface for tools to be used by agents. |
|
duckduckgo
Package duckduckgo contains an implementation of the tool interface with the duckduckgo api client.
|
Package duckduckgo contains an implementation of the tool interface with the duckduckgo api client. |
|
metaphor
// Package metaphor contains an implementation of the tool interface with the metaphor search api client.
|
// Package metaphor contains an implementation of the tool interface with the metaphor search api client. |
|
perplexity
Package perplexity provides integration with Perplexity AI's API for AI agents.
|
Package perplexity provides integration with Perplexity AI's API for AI agents. |
|
scraper
Package scraper contains an implementation of the tool interface for a web scraping tool.
|
Package scraper contains an implementation of the tool interface for a web scraping tool. |
|
serpapi
Package serpapi contains an implementation of the tool interface with the serapi.
|
Package serpapi contains an implementation of the tool interface with the serapi. |
|
wikipedia
Package wikipedia contains an implementation of the tool interface with the wikipedia api.
|
Package wikipedia contains an implementation of the tool interface with the wikipedia api. |
|
zapier
Package zapier contains an implementation of the tool interface with the zapier NLA api client.
|
Package zapier contains an implementation of the tool interface with the zapier NLA api client. |
|
util
|
|
|
Package vectorstores contains the implementation of VectorStore, an interface for saving and querying documents as vector embeddings.
|
Package vectorstores contains the implementation of VectorStore, an interface for saving and querying documents as vector embeddings. |
|
azureaisearch
Package azureaisearch contains an implementation of the VectorStore interface that connects to Azure AI search.
|
Package azureaisearch contains an implementation of the VectorStore interface that connects to Azure AI search. |
|
chroma
Package chroma contains an implementation of the VectorStore interface that connects to an external Chroma database.
|
Package chroma contains an implementation of the VectorStore interface that connects to an external Chroma database. |
|
dolt
Package dolt contains an implementation of the VectorStore interface using Dolt.
|
Package dolt contains an implementation of the VectorStore interface using Dolt. |
|
mariadb
Package mariadb contains an implementation of the VectorStore interface using MariaDB.
|
Package mariadb contains an implementation of the VectorStore interface using MariaDB. |
|
milvus
Package milvus provides a vectorstore implementation for Milvus.
|
Package milvus provides a vectorstore implementation for Milvus. |
|
milvus/v2
Package v2 provides a vectorstore implementation for Milvus using the new SDK.
|
Package v2 provides a vectorstore implementation for Milvus using the new SDK. |
|
mongovector
Package mongovector implements a vector store using MongoDB as the backend.
|
Package mongovector implements a vector store using MongoDB as the backend. |
|
opensearch
Package opensearch contains an implementation of the VectorStore interface that connects to Opensearch.
|
Package opensearch contains an implementation of the VectorStore interface that connects to Opensearch. |
|
pgvector
Package pgvector contains an implementation of the VectorStore interface using pgvector.
|
Package pgvector contains an implementation of the VectorStore interface using pgvector. |
|
pinecone
Package pinecone contains an implementation of the VectorStore interface using pinecone.
|
Package pinecone contains an implementation of the VectorStore interface using pinecone. |
|
qdrant
Package qdrant contains an implementation of the VectorStore interface using Qdrant.
|
Package qdrant contains an implementation of the VectorStore interface using Qdrant. |
|
redisvector
Package redisvector contains an implementation of the VectorStore interface using redisvector.
|
Package redisvector contains an implementation of the VectorStore interface using redisvector. |
|
weaviate
Package weaviate contains an implementation of the VectorStore interface using weaviate.
|
Package weaviate contains an implementation of the VectorStore interface using weaviate. |