langchain-golang

A community Go port of LangChain — the Python AI application framework. Build LLM agents and LLM applications in Go using LangChain's abstractions: chat models, tools, prompts, output parsers, messages, vector stores, retrievers, and the create_agent factory.
Not affiliated with or endorsed by LangChain, Inc. Preview quality (v0.1.0); the public API may still change before v1.0.0.
What this is
A Go port of:
langchain_core → core/ — base abstractions and interfaces.
langchain (the actively-maintained langchain_v1 package) → langchain/ — concrete implementations, the agent factory, middleware, tools.
langchain_text_splitters → textsplitters/.
langchain-tests → standardtests/ — shared conformance suites.
model-profiles → modelprofiles/ + the cmd/langchain-profiles CLI.
It is not a port of langchain_classic (the legacy package), and not a full port of langgraph — only the minimal graph runtime that create_agent depends on is internalized as a private package (see Not supported).
All tests green: go test ./... — 800+ tests across 51 packages.
✅ Supported
Core (core/)
messages (unified struct, content blocks, tool calls, trimming, serialization) · runnables (composition, batch, stream, fallback, branch, router, JSON/ASCII/Mermaid graph export) · language (ChatModel / LLM interfaces, fake models, ChatModel.Stream, rate-limiter hooks) · tools (base tool, render helpers, retriever-tool adapter) · prompts (string + structured + templated, local JSON loading) · outputparser (all parser variants, format instructions, partial parsing) · callbacks (manager fan-out, stdout/streaming/file handlers, usage aggregation) · streamevents (v3 content-block protocol, ChatModelStream projection) · documents · documentloaders · indexing (incl. SQL record manager) · embeddings · vectorstores (in-memory, filtering, MMR, retriever adapters) · retrievers · exampleselectors · tracers (context/root listener, memory, filtering, replay, event streaming, stdout) · load · stores · caches · ratelimiters · retry · _api (deprecation) · _security (SSRF protection, transport validation) · utils · chathistory · httpclient · modelconfig · outputs · structuredoutput · schema.
LangChain v1 (langchain/)
chatmodels / embeddings — provider registries, parsing, init-spec boundaries.
tools.ToolNode — concurrent dispatch, unknown-tool errors, configurable error handling, ToolCallWrapper.
messages, ratelimiters.
agents.CreateAgent — the Go equivalent of Python's create_agent
A model ↔ tools agent loop built on an internal graph runtime, with:
- Middleware chain —
WrapModelCall / WrapToolCall (outermost-first), BeforeModel / AfterModel / BeforeAgent / AfterAgent hooks, jump_to short-circuit convention, context.Context on every hook (for interrupt).
- 15 middleware modules: human-in-the-loop, model-call-limit, model-fallback, model/tool-retry, tool-call-limit, context-editing, file-search (ripgrep fast path), pii/redaction, provider-tool-search, shell, summarization, todo, tool-emulator, tool-selection.
system_prompt — plain string and templated PromptTemplate (with per-call variables).
state_schema — custom graph-state fields via StateField + reducers (WithAgentStateFields).
context_schema — read-only runtime context over Go context.Context (WithContextValues / ContextValue).
response_format — ToolStrategy (fully wired) and ProviderStrategy (best-effort JSON).
checkpointer — in-memory saver; interrupt / resume round trips.
recursion_limit, name, debug.
- Streaming —
Agent.StreamEvents: real per-token streaming (model deltas + tool/node lifecycle events) over runnables.Stream[StreamEvent].
Text splitters, standard tests, model profiles
textsplitters/ — full port (character, HTML, Markdown, code, recursive, header; sentence-transformers / NLTK / spaCy / KoNLPy adapter interfaces).
standardtests/ — chat-model / embeddings / retriever / vector-store / runnable conformance suites.
modelprofiles/ — profile registry, Markdown summary, the langchain-profiles refresh CLI (merges models.dev data + TOML overrides → profiles.json).
Partner packages
partners/openai · partners/anthropic · partners/ollama (chat models & embeddings) · partners/chroma (vector store). These are both usable integrations and validation aids for the conformance suites.
❌ Not supported / out of scope
Deliberately not ported
langchain_classic — legacy chains, agents, memory, tools, retrievers, vectorstores, storage. The classic AgentExecutor is gone; use agents.CreateAgent.
- A full
langgraph port. Only the minimal subset create_agent depends on lives here, internalized at langchain/internal/agentruntime/ (package agentruntime, not exported). Intentionally absent: subgraphs, streaming modes beyond events, time-travel / state history, caching/retry policies, the functional @entrypoint/@task API, persistent Postgres/SQLite checkpoint backends, and the langgraph CLI/SDK.
- Middleware-facing streaming — middleware cannot observe model deltas mid-stream. As a consequence, PII streaming-delta redaction and the subagent transformer (
run.subagents) are not ported (batch redaction works).
- Functional
@entrypoint/@task API, time-travel, subgraphs — see above.
Limited partner coverage
- Only
openai, anthropic, ollama, chroma. No Google/Gemini, AWS, Azure, Pinecone, etc. — community contributions welcome.
langchain/chatmodels can parse a model name to a ChatModelSpec, but cannot construct a partner ChatModel from a bare name string (no create_agent("gpt-4o", ...) — pass a constructed language.ChatModel).
langchain/tools.ToolNode does not support Command/Send returned from tools, or reflection-based InjectedState / InjectedStore / ToolRuntime argument injection.
Other gaps
core/tools has no callable→Tool schema inference (no @tool equivalent) — construct tools explicitly with a schema.
core/prompts does not load YAML, Jinja templates, or lc:// Hub prompts (string + local JSON only).
core/runnables PNG graph rendering is unsupported (JSON/ASCII/Mermaid are).
- Python-style dynamic provider import / instance construction is unsupported — construct concrete models in Go.
- File tools (
Read/Write/Edit/Bash) and sandboxing are out of scope — those are provided by claude-agent-sdk-golang, not by LangChain.
The support / gap tables above are the canonical compatibility reference. Open an issue if you need detail on a specific gap.
Installation
go get github.com/projanvil/langchain-golang@v0.1.0
Requires Go 1.23+.
Quick start
A minimal runnable example using the in-tree fake model (swap in a partner ChatModel for production):
package main
import (
"context"
"fmt"
"github.com/projanvil/langchain-golang/core/language"
"github.com/projanvil/langchain-golang/core/messages"
"github.com/projanvil/langchain-golang/langchain/agents"
)
func main() {
model := language.NewFakeChatModel(
language.WithResponses(messages.AI("It's sunny in Shanghai.")),
)
agent, err := agents.CreateAgent(model, nil,
agents.WithAgentSystemPrompt("You are a helpful assistant."),
agents.WithAgentName("my-agent"),
)
if err != nil {
panic(err)
}
// Non-streaming:
reply, _ := agent.Invoke(context.Background(), []messages.Message{
messages.User("What's the weather?"),
})
fmt.Println(reply[len(reply)-1].Content)
// Streaming:
stream, _ := agent.StreamEvents(context.Background(), []messages.Message{
messages.User("Tell me a story."),
})
for {
ev, ok, _ := stream.Next(context.Background())
if !ok {
break
}
if ev.Type == agents.StreamModelDelta && ev.Text != "" {
fmt.Print(ev.Text)
}
}
}
For a real model, construct a language.ChatModel from a partner package (e.g. partners/openai, partners/anthropic, partners/ollama) and pass it to agents.CreateAgent.
Repository layout
langchain-golang/
├── core/ # langchain_core port
├── langchain/ # langchain (v1) port
│ ├── agents/ # CreateAgent + 15 middleware
│ ├── chatmodels/ embeddings/ messages/ tools/ ratelimiters/
│ └── internal/agentruntime/ # internal graph runtime (not exported)
├── textsplitters/ # langchain_text_splitters port
├── standardtests/ # langchain-tests conformance port
├── modelprofiles/ # model-profiles port
├── partners/ # openai, anthropic, ollama, chroma
└── cmd/langchain-profiles # profiles refresh CLI
Acknowledgments
This project is a Go port of LangChain (MIT License, Copyright © LangChain, Inc.) and LangGraph. All credit for the original design and abstractions belongs to the LangChain team.
License
MIT — Copyright © 2026 ProjAnvil.