Mastering Chains in LangChainGo: Build Complex LLM Workflows Step‑by‑Step
This guide explains LangChainGo’s Chain abstraction, detailing the core Chain interface, the LLMChain implementation, various chain types such as SequentialChain and RetrievalQA, and provides a complete walkthrough of setting up prompts, creating chains, and executing them with example Go code.
Core Concepts
In LangChainGo, a Chain combines multiple components (LLM, prompt templates, other chains, or tools) to accomplish a specific task, enabling more complex and intelligent workflows beyond a single LLM call.
Chain Interface
All chains implement the Chain interface, which defines the following core methods: Call(...): Executes the chain, accepting a map[string]any as input and returning a map[string]any as output. GetInputKeys(): Returns the keys the chain expects as input. GetOutputKeys(): Returns the keys produced by the chain. GetMemory(): Returns any memory component associated with the chain.
LLMChain
The LLMChain is the most basic and frequently used chain. It couples a PromptTemplate with an LLM. Its workflow is:
Receive input variables.
Use PromptTemplate to format the input into a final prompt.
Send the formatted prompt to the LLM.
Return the LLM’s output.
The article’s main.go example centers on LLMChain.
More Chain Types
SequentialChain (顺序链) : Executes a series of chains in a predefined order, passing each chain’s output as the next chain’s input.
Chains for Documents : StuffDocuments: Packs all documents into a single prompt and calls an LLMChain. Suitable for a small number of documents. MapReduceDocuments: Runs an initial chain on each document (Map step), merges results, then processes the merged result with another chain (Reduce step). Handles large document sets while respecting context limits.
RetrievalQA (检索问答链) : Combines a Retriever and an LLMChain to answer questions over a document set. It first retrieves relevant documents, then lets the LLM generate an answer based on them.
Executing Chains
Call: The most generic execution function; both input and output are map[string]any, allowing arbitrary complexity. Predict: Use when the chain’s output is a single string; it extracts the value of the text key automatically. Run: Simplest function for chains with one input and one string output; it handles map creation and parsing internally.
Code Walkthrough (main.go)
Import and Initialization : The code imports required packages such as chains and prompts , then creates an LLM instance.
Define Prompt Template using prompts.PromptTemplate :
prompt := prompts.PromptTemplate{
Template: "将以下文本翻译成中文:
{{.text}}",
InputVariables: []string{"text"},
TemplateFormat: prompts.GoTemplate,
}The template format can be prompts.GoTemplate (default Go text/template syntax), prompts.TemplateFormatFString (Python‑style f‑string), or prompts.TemplateFormatJinja2 (Jinja2 syntax).
Create the LLMChain : chain := chains.NewLLMChain(llm, prompt) Call the Chain :
input := map[string]any{"text": "Hello, how are you?"}
result, err := chains.Call(ctx, chain, input)
fmt.Println(result["text"])F‑string Format Example : Demonstrates using different template formats to create and invoke another chain, showing flexibility.
SequentialChain Example : Shows how to combine two LLMChain instances into a SequentialChain for a multi‑step workflow.
// First sub-chain: Generate product name
productNameChain := chains.NewLLMChain(llm, productNameTemplate)
productNameChain.OutputKey = "product_name"
// Second sub-chain: Generate product slogan
sloganChain := chains.NewLLMChain(llm, sloganTemplate)
// Create the SequentialChain
sequentialChain, err := chains.NewSequentialChain(
[]chains.Chain{productNameChain, sloganChain},
[]string{"product_description"},
[]string{"text"}, // Only the output keys from the LAST chain.
)Important Note : The third parameter outputVariables of NewSequentialChain can only contain output keys from the final chain; intermediate outputs (e.g., product_name ) are not directly returned.
First sub‑chain (productNameChain) : Generates a product name from the description and sets OutputKey to "product_name" so the next chain can consume it.
Second sub‑chain (sloganChain) : Takes product_name as input and produces a slogan with the default output key "text".
How to Run
Set Environment Variable : export OPENAI_API_KEY="your‑api‑key" Download Dependencies : go mod tidy Run the Code :
go run main.goBirdNest Tech Talk
Author of the rpcx microservice framework, original book author, and chair of Baidu's Go CMC committee.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
