
LangChain + 微調本地模型:無 API 成本的管道構建
LangChain 可與任何 OpenAI 相容 API 配合使用——包括 Ollama。用微調本地模型替換 LangChain 管道中的 API 調用。相同的鏈結構,零按 token 計費成本。
LangChain 是構建 AI 管道最廣泛使用的框架:文件處理、RAG、代理、鏈。大多數 LangChain 教程指向 OpenAI 的 API。你的生產帳單反映了這一點。
LangChain 通過 Ollama 支持本地模型——而 Ollama 的 OpenAI 相容介面意味著你可以用最少的代碼更改交換 LangChain 管道中的 AI 後端。將此與微調模型結合,你將獲得在領域任務上更快、在規模化時更便宜、 且預設私密的管道。
LangChain + Ollama 整合選項
LangChain 有兩種 Ollama 整合路徑:
選項 1:ChatOllama(LangChain 原生)
from langchain_ollama import ChatOllama
llm = ChatOllama(
model="your-fine-tuned-model",
base_url="http://localhost:11434",
temperature=0.3
)
# 用法與 ChatOpenAI 完全相同
response = llm.invoke("Generate a listing for this property: ...")
print(response.content)
選項 2:帶 Ollama base URL 的 ChatOpenAI(直接替換的首選)
from langchain_openai import ChatOpenAI
llm = ChatOpenAI(
model="your-fine-tuned-model",
base_url="http://localhost:11434/v1",
api_key="ollama", # 必填欄位,不驗證
temperature=0.3
)
# 與雲端 ChatOpenAI 介面完全相同
選項 2 是最乾淨的遷移方式:如果你已有使用 ChatOpenAI 的 LangChain 代碼,唯一的更改是 base_url 和 model。
常見管道模式
模式 1:文件處理鏈
之前(GPT-4 API):
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
llm = ChatOpenAI(model="gpt-4o") # $0.005/1K input tokens
template = PromptTemplate.from_template(
"Classify this support ticket:\n{ticket}\nOutput: category, priority, suggested_response"
)
chain = LLMChain(llm=llm, prompt=template)
result = chain.invoke({"ticket": ticket_text})
之後(微調本地模型):
from langchain_openai import ChatOpenAI
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
# 只改一行
llm = ChatOpenAI(
model="support-classifier-v3", # 你的微調分類器
base_url="http://localhost:11434/v1",
api_key="ollama"
)
# 鏈定義保持不變
template = PromptTemplate.from_template(
"Classify this support ticket:\n{ticket}\nOutput: category, priority, suggested_response"
)
chain = LLMChain(llm=llm, prompt=template)
result = chain.invoke({"ticket": ticket_text})
處理 10,000 個支持工單:
- 之前:10,000 × $0.005 = $50 的 API 成本
- 之後:每月 $50 的 VPS,攤銷到所有處理量中
模式 2:帶微調閱讀器的 RAG 管道
對於檢索增強生成(RAG),你通常希望檢索模型(嵌入)和閱讀器模型(答案生成)都校準到你的領域。
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain.chains import RetrievalQA
from langchain_chroma import Chroma
# 通過 Ollama 的本地嵌入(nomic-embed-text 效果很好)
embeddings = OpenAIEmbeddings(
model="nomic-embed-text",
base_url="http://localhost:11434/v1",
api_key="ollama"
)
# 微調閱讀器模型
reader_llm = ChatOpenAI(
model="your-domain-reader-model",
base_url="http://localhost:11434/v1",
api_key="ollama"
)
# 從你的文件構建向量存儲
vectorstore = Chroma.from_documents(
documents=your_docs,
embedding=embeddings,
persist_directory="./chroma_db"
)
# RAG 鏈——推論時零雲端 API 調用
qa_chain = RetrievalQA.from_chain_type(
llm=reader_llm,
retriever=vectorstore.as_retriever(search_kwargs={"k": 5})
)
answer = qa_chain.invoke({"query": "What is our return policy for sale items?"})
嵌入和生成都在本地進行。檢索模型理解你的領域術語。閱讀器模型在你的領域問答上進行了微調。零 API 調用。
模式 3:帶本地工具執行器的 LangGraph 代理
LangGraph(LangChain 的代理框架)適用於任何與 LangChain 相容的 LLM:
from langgraph.graph import StateGraph, END
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
# 代理使用本地模型進行協調
orchestrator = ChatOpenAI(
model="your-orchestrator-model", # 或使用 Claude/GPT-4 進行協調
base_url="http://localhost:11434/v1",
api_key="ollama"
)
# 工具執行器使用專門的微調模型
domain_executor = ChatOpenAI(
model="your-domain-model",
base_url="http://localhost:11434/v1",
api_key="ollama"
)
def run_domain_task(state):
task = state["current_task"]
result = domain_executor.invoke(task)
return {"result": result.content}
# 構建圖
graph = StateGraph(dict)
graph.add_node("domain_executor", run_domain_task)
# ... 添加協調邏輯
app = graph.compile()
LangChain + Ollama 的性能調優
批量處理: 對於大量處理(分類 5,000 個工單),使用 LangChain 的批量方法並行化調用:
# 並發處理 100 個工單
results = await chain.abatch(
[{"ticket": t} for t in tickets],
config={"max_concurrency": 10} # 10 個並發 Ollama 調用
)
快取: 啟用 LangChain 的語義快取以避免冗餘模型調用:
from langchain.globals import set_llm_cache
from langchain_community.cache import SQLiteCache
set_llm_cache(SQLiteCache(database_path=".langchain.db"))
# 相同的提示詞返回快取結果——不需要 Ollama 調用
上下文長度: 7B 模型通常支持 4K-8K 上下文。對於長文件處理,在傳遞給模型之前使用 LangChain 的文字分割器進行分塊。
在 LangChain 管道中何時使用微調本地模型 vs 雲端
| 任務 | 本地微調 | 雲端(GPT-4) |
|---|---|---|
| 領域分類 | 更好且更便宜 | 過度殺傷 |
| 領域生成 | 更好且更便宜 | 過度殺傷 |
| 複雜推理鏈 | 考慮使用 | 更好 |
| 當前事件/網絡 | 不適用 | 必需 |
| 高流量批次處理 | 便宜得多 | 昂貴 |
| 一次性/低流量 | 均可 | 均可 |
Ship AI that runs on your users' devices.
Ertas early bird pricing starts at $14.50/mo — locked in for life. Plans for builders and agencies.
延伸閱讀
- OpenAI 相容本地 API — Ollama 的 API 介面詳解
- MCP + 微調本地模型 — Claude 整合的 MCP 架構
- 無 API 成本的 AI SaaS 創業 — 本地推論的經濟學
- MCP 伺服器零 API 成本 — 使用 MCP 的零成本 AI 工具
Ship AI that runs on your users' devices.
Early bird pricing starts at $14.50/mo — locked in for life. Plans for builders and agencies.
Keep reading

MCP + Fine-Tuned Local Model: Connect Claude to Your Domain-Specific AI
Model Context Protocol (MCP) lets Claude Desktop talk to any server — including your own Ollama-hosted fine-tuned model. Here's the architecture and setup for routing Claude requests to a custom domain model.

Ollama's OpenAI-Compatible API: Drop Your Fine-Tuned Model Into Any OpenAI Integration
Ollama exposes an OpenAI-compatible REST API. Any code written for the OpenAI SDK — Langchain, LlamaIndex, your own app — works with your fine-tuned local model by changing one URL. Here's what to know.

Replit App AI Costs Exploding? Replace OpenAI with a Fine-Tuned Local Model
Replit's always-on deployment and easy AI integration create a specific API cost problem. Here's how to replace OpenAI with a fine-tuned local model and cut costs to flat rate.