网站阶段推广计划广告策划活动公司
2026/1/2 13:32:42 网站建设 项目流程
网站阶段推广计划,广告策划活动公司,网站改版 方案,asp.net 建立网站吗本文档详细介绍了基于LangChain框架的智能体开发全流程#xff0c;涵盖工具创建、模型绑定、智能体初始化、结构化输出等核心概念#xff0c;为开发者提供完整的实践指导。 一、工具开发与初始化 1.1 基础工具创建 from langchain_core.tools import tool from pydantic i…本文档详细介绍了基于LangChain框架的智能体开发全流程涵盖工具创建、模型绑定、智能体初始化、结构化输出等核心概念为开发者提供完整的实践指导。一、工具开发与初始化1.1 基础工具创建from langchain_core.tools import tool from pydantic import BaseModel, Field from typing import Dict, Any # 定义输入参数模型 class AddInputArgs(BaseModel): a: int Field(description第一个数字) b: int Field(description第二个数字) # 创建计算工具 tool( description两个数字相加, args_schemaAddInputArgs, return_directFalse ) def add(a: int, b: int) - int: 执行两个数字的加法运算 return a b # 创建工具集合 def create_calc_tools(): 创建计算工具集 return [add] # 初始化工具 calc_tools create_calc_tools()1.2 高级工具开发示例# 数学计算工具集 class MathInputArgs(BaseModel): a: float Field(description第一个操作数) b: float Field(description第二个操作数) tool(description两个数字相减, args_schemaMathInputArgs) def subtract(a: float, b: float) - float: 执行减法运算 return a - b tool(description两个数字相乘, args_schemaMathInputArgs) def multiply(a: float, b: float) - float: 执行乘法运算 return a * b tool(description两个数字相除, args_schemaMathInputArgs) def divide(a: float, b: float) - float: 执行除法运算 if b 0: raise ValueError(除数不能为零) return a / b def create_advanced_math_tools(): 创建高级数学工具集 return [add, subtract, multiply, divide]二、大模型配置与绑定2.1 大模型初始化from langchain_openai import ChatOpenAI from pydantic import SecretStr import os # 初始化大模型 llm ChatOpenAI( modelgpt-3.5-turbo, # 或使用其他模型如 gpt-4 base_urlhttps://api.openai.com/v1, # 模型API地址 api_keySecretStr(os.getenv(OPENAI_API_KEY)), # 从环境变量获取API密钥 streamingTrue, # 启用流式响应 temperature0, # 控制随机性0表示确定性输出 max_tokens1000 # 最大输出token数 ) # 绑定工具到模型 llm_with_tools llm.bind_tools(calc_tools)2.2 多模型配置支持class ModelManager: 模型管理器支持多种模型配置 def __init__(self): self.models {} self.setup_models() def setup_models(self): 配置多种模型 # OpenAI模型 self.models[openai] ChatOpenAI( modelgpt-3.5-turbo, api_keySecretStr(os.getenv(OPENAI_API_KEY)), temperature0 ) # 本地模型如Ollama try: from langchain_ollama import OllamaLLM self.models[local] OllamaLLM(modelllama3) except ImportError: print(Ollama未安装跳过本地模型配置) def get_model(self, model_typeopenai): 获取指定类型的模型 return self.models.get(model_type, self.models[openai]) # 使用模型管理器 model_manager ModelManager() llm model_manager.get_model(openai)三、 智能体创建与配置3.1 智能体初始化from langchain.agents import initialize_agent, AgentType # 创建智能体 agent initialize_agent( toolscalc_tools, llmllm_with_tools, agentAgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verboseTrue, # 显示详细执行过程 handle_parsing_errorsTrue, # 处理解析错误 max_iterations5, # 最大迭代次数 early_stopping_methodforce # 提前停止策略 )3.2 智能体类型详解# 不同的智能体类型配置 AGENT_CONFIGS { zero_shot: { agent_type: AgentType.ZERO_SHOT_REACT_DESCRIPTION, description: 零样本反应式智能体适合简单任务 }, structured_chat: { agent_type: AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, description: 结构化聊天智能体适合复杂对话 }, conversational: { agent_type: AgentType.CONVERSATIONAL_REACT_DESCRIPTION, description: 对话式智能体支持多轮对话 } } def create_agent_by_type(agent_type: str, tools: list, llm): 根据类型创建智能体 config AGENT_CONFIGS.get(agent_type, AGENT_CONFIGS[zero_shot]) return initialize_agent( toolstools, llmllm, agentconfig[agent_type], verboseTrue, max_iterations5 )四、 智能体调用与结果处理4.1 基础调用方式# 调用智能体 def invoke_agent(question: str, context: dict None): 调用智能体并处理结果 try: input_data { role: 计算专家, domain: 数学计算, question: question } if context: input_data.update(context) # 执行智能体调用 response agent.invoke(input_data) # 处理工具调用结果 if hasattr(response, tool_calls) and response.tool_calls: return process_tool_calls(response.tool_calls) else: return response.get(output, 未获取到有效响应) except Exception as e: return f智能体调用失败: {str(e)} def process_tool_calls(tool_calls): 处理工具调用结果 results [] tool_dict {tool.name: tool for tool in calc_tools} for tool_call in tool_calls: try: args tool_call.get(args, {}) func_name tool_call.get(name, ) if func_name in tool_dict: tool_func tool_dict[func_name] result tool_func.invoke(args) results.append(f{func_name} 结果: {result}) else: results.append(f未知工具: {func_name}) except Exception as e: results.append(f工具 {func_name} 执行失败: {str(e)}) return \n.join(results) # 使用示例 result invoke_agent(使用工具计算: 100 100 ?) print(result)4.2 流式响应处理async def stream_agent_response(question: str): 流式处理智能体响应 input_data { role: 计算专家, domain: 数学计算, question: question } try: # 流式调用 async for chunk in agent.astream(input_data): if hasattr(chunk, tool_calls): yield f工具调用: {chunk.tool_calls} elif hasattr(chunk, output): yield chunk.output else: yield str(chunk) except Exception as e: yield f错误: {str(e)} # 使用示例 import asyncio async def main(): async for response in stream_agent_response(计算 50 * 2): print(response, end, flushTrue) # asyncio.run(main())五、结构化输出处理5.1 JSON输出解析器from langchain_core.output_parsers import JsonOutputParser from pydantic import BaseModel from typing import List, Optional # 定义结构化输出模型 class MathSolution(BaseModel): problem: str solution: float steps: List[str] unit: Optional[str] None class Summary(BaseModel): question: str answer: float explanation: str formula_used: str # 创建解析器 parser JsonOutputParser(pydantic_objectSummary) format_instructions parser.get_format_instructions() print(格式要求:) print(format_instructions)5.2 结构化提示词模板from langchain.prompts import ChatPromptTemplate # 创建结构化提示词 structured_prompt ChatPromptTemplate.from_messages([ (system, 你是一位{role}专家擅长{domain}。 请严格按照JSON格式返回结果不要使用Markdown代码块包裹 格式要求{format_instructions}), (human, 问题{question}) ]) # 使用示例 messages structured_prompt.format_messages( role计算专家, domain使用工具进行数学计算, format_instructionsformat_instructions, question如果一个矩形的长度是10米宽度是5米它的面积是多少平方米? ) # 创建带结构化输出的链 structured_chain structured_prompt | llm | parser # 调用链 try: result structured_chain.invoke({ role: 数学专家, domain: 几何计算, question: 矩形面积计算问题 }) print(结构化结果:, result) except Exception as e: print(f解析失败: {e})六、LangChain内置工具使用6.1 常用内置工具from langchain.agents import load_tools # 加载内置工具 def load_builtin_tools(): 加载常用内置工具 tools load_tools([ python_repl, # Python REPL环境 requests, # HTTP请求 terminal, # 终端命令执行 google-search, # 谷歌搜索 wolfram-alpha # 数学计算 ], llmllm) return tools # 工具使用示例 builtin_tools load_builtin_tools() # 创建使用内置工具的智能体 builtin_agent initialize_agent( toolsbuiltin_tools, llmllm, agentAgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verboseTrue )6.2 Python REPL工具详解# Python REPL工具使用示例 def execute_python_code(code: str): 使用Python REPL执行代码 python_repl_tool load_tools([python_repl], llmllm)[0] try: result python_repl_tool.run(code) return f执行成功: {result} except Exception as e: return f执行失败: {str(e)} # 使用示例 code_examples [ print(Hello, World!), x 10 20\nprint(x), import math\nprint(math.sqrt(16)) ] for code in code_examples: result execute_python_code(code) print(f代码: {code}) print(f结果: {result}\n)七、完整开发示例7.1 数学智能体完整实现class MathAgent: 数学智能体实现 def __init__(self): self.setup_agent() def setup_agent(self): 初始化智能体 # 创建工具 self.tools create_advanced_math_tools() # 配置模型 self.llm ChatOpenAI( modelgpt-3.5-turbo, temperature0, streamingTrue ) # 绑定工具 self.llm_with_tools self.llm.bind_tools(self.tools) # 创建智能体 self.agent initialize_agent( toolsself.tools, llmself.llm_with_tools, agentAgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION, verboseTrue, max_iterations3 ) def solve_math_problem(self, problem: str): 解决数学问题 try: response self.agent.invoke({ input: f请解决以下数学问题: {problem} }) return response.get(output, 未获取到解决方案) except Exception as e: return f解决问题时出错: {str(e)} def batch_solve(self, problems: list): 批量解决数学问题 results [] for problem in problems: result self.solve_math_problem(problem) results.append({ problem: problem, solution: result }) return results # 使用示例 math_agent MathAgent() # 单个问题 result math_agent.solve_math_problem(计算 (15 25) × 2 ÷ 5) print(result) # 批量问题 problems [ 12 × 15 - 8, 圆的半径是7cm面积是多少, 解方程: 2x 5 15 ] batch_results math_agent.batch_solve(problems) for result in batch_results: print(f问题: {result[problem]}) print(f解答: {result[solution]}\n)八、错误处理与调试8.1 异常处理机制class RobustMathAgent(MathAgent): 增强的数学智能体包含错误处理 def solve_math_problem(self, problem: str, max_retries3): 带重试机制的数学问题解决 for attempt in range(max_retries): try: return super().solve_math_problem(problem) except Exception as e: if attempt max_retries - 1: return f经过{max_retries}次尝试后仍失败: {str(e)} print(f第{attempt1}次尝试失败重试...) return 未知错误 # 使用增强版智能体 robust_agent RobustMathAgent() result robust_agent.solve_math_problem(复杂的数学问题) print(result)九、性能优化建议9.1 缓存策略from functools import lru_cache class CachedMathAgent(MathAgent): 带缓存功能的数学智能体 lru_cache(maxsize100) def solve_math_problem(self, problem: str): 带缓存的数学问题解决 return super().solve_math_problem(problem) # 使用缓存版本 cached_agent CachedMathAgent() # 相同问题只会计算一次 result1 cached_agent.solve_math_problem(10 20) result2 cached_agent.solve_math_problem(10 20) # 从缓存获取如何学习大模型 AI 由于新岗位的生产效率要优于被取代岗位的生产效率所以实际上整个社会的生产效率是提升的。但是具体到个人只能说是“最先掌握AI的人将会比较晚掌握AI的人有竞争优势”。这句话放在计算机、互联网、移动互联网的开局时期都是一样的道理。我在一线科技企业深耕十二载见证过太多因技术卡位而跃迁的案例。那些率先拥抱 AI 的同事早已在效率与薪资上形成代际优势我意识到有很多经验和知识值得分享给大家也可以通过我们的能力和经验解答大家在大模型的学习中的很多困惑。我们整理出这套AI 大模型突围资料包✅ 从零到一的 AI 学习路径图✅ 大模型调优实战手册附医疗/金融等大厂真实案例✅ 百度/阿里专家闭门录播课✅ 大模型当下最新行业报告✅ 真实大厂面试真题✅ 2025 最新岗位需求图谱所有资料 ⚡️ 朋友们如果有需要《AI大模型入门进阶学习资源包》下方扫码获取~① 全套AI大模型应用开发视频教程包含提示工程、RAG、LangChain、Agent、模型微调与部署、DeepSeek等技术点② 大模型系统化学习路线作为学习AI大模型技术的新手方向至关重要。 正确的学习路线可以为你节省时间少走弯路方向不对努力白费。这里我给大家准备了一份最科学最系统的学习成长路线图和学习规划带你从零基础入门到精通③ 大模型学习书籍文档学习AI大模型离不开书籍文档我精选了一系列大模型技术的书籍和学习文档电子版它们由领域内的顶尖专家撰写内容全面、深入、详尽为你学习大模型提供坚实的理论基础。④ AI大模型最新行业报告2025最新行业报告针对不同行业的现状、趋势、问题、机会等进行系统地调研和评估以了解哪些行业更适合引入大模型的技术和应用以及在哪些方面可以发挥大模型的优势。⑤ 大模型项目实战配套源码学以致用在项目实战中检验和巩固你所学到的知识同时为你找工作就业和职业发展打下坚实的基础。⑥ 大模型大厂面试真题面试不仅是技术的较量更需要充分的准备。在你已经掌握了大模型技术之后就需要开始准备面试我精心整理了一份大模型面试题库涵盖当前面试中可能遇到的各种技术问题让你在面试中游刃有余。以上资料如何领取为什么大家都在学大模型最近科技巨头英特尔宣布裁员2万人传统岗位不断缩减但AI相关技术岗疯狂扩招有3-5年经验大厂薪资就能给到50K*20薪不出1年“有AI项目经验”将成为投递简历的门槛。风口之下与其像“温水煮青蛙”一样坐等被行业淘汰不如先人一步掌握AI大模型原理应用技术项目实操经验“顺风”翻盘这些资料真的有用吗这份资料由我和鲁为民博士(北京清华大学学士和美国加州理工学院博士)共同整理现任上海殷泊信息科技CEO其创立的MoPaaS云平台获Forrester全球’强劲表现者’认证服务航天科工、国家电网等1000企业以第一作者在IEEE Transactions发表论文50篇获NASA JPL火星探测系统强化学习专利等35项中美专利。本套AI大模型课程由清华大学-加州理工双料博士、吴文俊人工智能奖得主鲁为民教授领衔研发。资料内容涵盖了从入门到进阶的各类视频教程和实战项目无论你是小白还是有些技术基础的技术人员这份资料都绝对能帮助你提升薪资待遇转行大模型岗位。以上全套大模型资料如何领取

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询