ARTICLE DETAIL

资讯详情

深耕网站视觉设计与运营推广的一线实战洞察。

Langchain实战3-Model和Prompt

Langchain实战3-Model和Prompt 本节聚焦 LangChain 1.0 的 Model 与 Prompt模型参数如何影响输出、消息如何组织上下文、Prompt 模板如何复用以及怎样让模型返回可校验的结构化结果。1. 初始化模型importosfromlangchain.chat_modelsimportinit_chat_model modelinit_chat_model(Qwen/Qwen3-8B,model_provideropenai,base_urlos.getenv(OPENAI_BASE_URL),api_keyos.getenv(OPENAI_API_KEY),temperature0.2,max_tokens1024,timeout30,max_retries2,)常用参数参数作用建议temperature控制随机性抽取/分类设低创作适当提高max_tokens限制最大输出长度结合任务与成本设置timeout单次请求超时避免无限等待max_retries临时错误重试次数配合指数退避使用stop遇到指定文本停止适合固定格式输出参数不能替代 Prompt。低温度只能让结果更稳定不能自动让指令更清晰。2. 消息模型Chat Model 接收的是消息序列而不是一整段无角色文本。fromlangchain_core.messagesimport(SystemMessage,HumanMessage,AIMessage,)messages[SystemMessage(content你是一名专业的旅游顾问。),HumanMessage(content推荐两家适合商务出行的柏林酒店。),]responsemodel.invoke(messages)print(response.content)SystemMessage设定角色、规则和边界HumanMessage用户输入AIMessage模型回答也可能包含 Tool CallToolMessage工具执行后返回给模型的结果。3. Prompt 模板当提示词需要反复使用时不应手工拼接字符串而应使用ChatPromptTemplate。fromlangchain_core.promptsimportChatPromptTemplate promptChatPromptTemplate.from_messages([(system,你是一名{domain}专家。请使用{style}风格回答不知道时明确说明不要编造。,),(human,{question}),])messagesprompt.invoke({domain:Python,style:简洁且包含代码示例,question:解释上下文管理器,})responsemodel.invoke(messages)print(response.content)模板变量由{变量名}声明调用时必须提供所有必填变量。4. 在模板中加入历史消息fromlangchain_core.promptsimport(ChatPromptTemplate,MessagesPlaceholder,)chat_promptChatPromptTemplate.from_messages([(system,你是一名中文技术助手。),MessagesPlaceholder(variable_namehistory),(human,{question}),])history[HumanMessage(content我正在学习 LangChain。),AIMessage(content好的我会结合 LangChain 示例回答。),]messageschat_prompt.invoke({history:history,question:Agent 的状态保存在哪里,})MessagesPlaceholder会原样插入消息列表避免把多轮对话压成一段普通字符串。5. 组合 Prompt、Model 与解析器LangChain 的 Runnable 可以使用管道运算符组合fromlangchain_core.output_parsersimportStrOutputParser chainprompt|model|StrOutputParser()answerchain.invoke({domain:LangChain,style:分点说明,question:什么是 Runnable,})print(answer)这里的执行顺序是变量字典 → PromptValue → AIMessage → 字符串6. 批量、异步与流式处理inputs[{domain:AI,style:一句话,question:解释 RAG,},{domain:AI,style:一句话,question:解释 Agent,},]resultschain.batch(inputs)resultawaitchain.ainvoke(inputs[0])forchunkinchain.stream(inputs[0]):print(chunk,end,flushTrue)7. 结构化输出自由文本适合给人阅读程序消费时应使用结构化输出。frompydanticimportBaseModel,FieldclassReviewAspect(BaseModel):name:strField(description评价维度)score:floatField(ge0,le5,description0~5 分)comment:strField(description该维度的简短说明)classProductReview(BaseModel):overall_sentiment:strField(descriptionpositive、neutral 或 negative)overall_score:floatField(ge0,le5)aspects:list[ReviewAspect]structured_modelmodel.with_structured_output(ProductReview)resultstructured_model.invoke(分析以下评论 手机拍照清晰续航也不错但充电速度偏慢。 )print(result.model_dump())Pydantic 同时完成四件事描述目标字段约束数据类型校验数值范围将返回结果转为 Python 对象。8. Prompt 设计检查表角色是谁需要完成什么目标有哪些输入数据可以使用哪些知识不能做什么输出格式是什么资料不足时如何处理是否需要给出来源、步骤或置信度。9. 常见问题9.1 模板变量报错检查 Prompt 中所有{name}是否都在invoke()参数中提供。需要输出字面量大括号时应写成{{和}}。9.2 JSON 解析失败不要只在 Prompt 中说“返回 JSON”优先使用with_structured_output()并为字段增加类型和说明。9.3 结果不稳定先明确任务、边界和输出格式再降低temperature。必要时加入少量高质量示例。9.4 上下文越来越长不要无限追加历史消息。后续可以使用消息裁剪、自动摘要和 Checkpointer 控制上下文。10. 本节小结一个稳定的模型功能需要同时控制三层模型参数决定生成特性Prompt 决定任务边界结构化输出决定结果能否被程序可靠消费。
返回列表