LangChain
LangChain 详解 什么是 LangChain LangChain 是一个用于构建基于大语言模型(LLM)应用的开源框架。它提供了一套标准化的组件和工具,简化了 AI Agent、聊天机器人、问答系统等应用的开发过程。 核心理念:通过"链(Chain)“将多个组件连接起来,构建复杂的 LLM 应用。 官方仓库: Python:langchain-ai/langchain JavaScript/TypeScript:langchain-ai/langchainjs 核心组件 1. Models(模型) 支持多种 LLM 提供商: from langchain.llms import OpenAI, Anthropic, HuggingFaceHub from langchain.chat_models import ChatOpenAI, ChatAnthropic # OpenAI llm = OpenAI(temperature=0.7) # Claude chat = ChatAnthropic(model="claude-3-sonnet-20240229") # 本地模型 from langchain.llms import Ollama local_llm = Ollama(model="llama2") 2. Prompts(提示模板) 管理和复用提示词: from langchain.prompts import PromptTemplate, ChatPromptTemplate # 简单模板 prompt = PromptTemplate( input_variables=["product"], template="给{product}写一个广告语" ) # 聊天模板 chat_prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个{role}"), ("human", "{user_input}") ]) # 使用 formatted = prompt.format(product="智能手表") result = llm(formatted) 3. Chains(链) 将多个组件串联: from langchain.chains import LLMChain, SimpleSequentialChain # 单个链 chain = LLMChain(llm=llm, prompt=prompt) result = chain.run(product="智能手表") # 顺序链 chain1 = LLMChain(llm=llm, prompt=prompt1) # 生成产品描述 chain2 = LLMChain(llm=llm, prompt=prompt2) # 生成广告语 overall_chain = SimpleSequentialChain( chains=[chain1, chain2], verbose=True ) result = overall_chain.run("智能手表") 4. Agents(代理) 动态决策和工具调用: ...