1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234
| """ 简单工具创建和使用 演示:如何给AI添加"技能" """
from langchain.tools import tool from langchain.agents import create_react_agent, AgentExecutor from langchain_openai import ChatOpenAI from langchain.prompts import PromptTemplate from dotenv import load_dotenv import os from datetime import datetime
load_dotenv()
@tool def get_current_time() -> str: """ 获取当前时间
Returns: 当前时间的字符串表示 """ return datetime.now().strftime("%Y-%m-%d %H:%M:%S")
@tool def calculator(expression: str) -> str: """ 计算数学表达式
Args: expression: 数学表达式,如 "3+5*2"
Returns: 计算结果 """ try: result = eval(expression) return f"{expression} = {result}" except Exception as e: return f"计算错误:{e}"
@tool def search_info(query: str) -> str: """ 搜索信息(模拟)
Args: query: 搜索关键词
Returns: 搜索结果 """ mock_data = { "python": "Python是一种高级编程语言,由Guido van Rossum创建于1991年", "langchain": "LangChain是一个用于开发由语言模型驱动的应用程序的框架", "ai": "人工智能(AI)是计算机科学的一个分支,致力于创建智能机器" }
for key, value in mock_data.items(): if key in query.lower(): return value
return f"未找到关于'{query}'的信息"
def example1_test_tools() -> None: """示例1:测试工具""" print("=== 示例1:测试工具 ===\n")
print("⏰ 调用时间工具:") time_result = get_current_time.invoke({}) print(f" 结果:{time_result}\n")
print("🧮 调用计算器工具:") calc_result = calculator.invoke({"expression": "10 + 5 * 2"}) print(f" 结果:{calc_result}\n")
print("🔍 调用搜索工具:") search_result = search_info.invoke({"query": "Python"}) print(f" 结果:{search_result}\n")
def example2_agent_with_tools() -> None: """示例2:让Agent使用工具""" print("=== 示例2:Agent使用工具 ===\n")
llm = ChatOpenAI( base_url=os.getenv("ALIBABA_BASE_URL"), api_key=os.getenv("ALIBABA_API_KEY"), model="qwen-plus", temperature=0, )
tools = [get_current_time, calculator, search_info]
prompt = PromptTemplate.from_template(""" 回答以下问题。你有以下工具可用:
{tools}
工具描述: {tool_names}
使用这个格式:
Question: 需要回答的问题 Thought: 思考需要做什么 Action: 要使用的工具,必须是 [{tool_names}] 中的一个 Action Input: 工具的输入 Observation: 工具的返回结果 ... (可以重复 Thought/Action/Action Input/Observation 多次) Thought: 我现在知道最终答案了 Final Answer: 最终答案
开始!
Question: {input} Thought: {agent_scratchpad} """)
agent = create_react_agent( llm=llm, tools=tools, prompt=prompt )
agent_executor = AgentExecutor( agent=agent, tools=tools, verbose=True, max_iterations=5, handle_parsing_errors=True )
test_cases = [ "现在几点了?", "计算 15 * 3 + 7", "告诉我关于LangChain的信息" ]
for question in test_cases: print(f"\n{'='*60}") print(f"❓ 问题:{question}") print('='*60)
try: result = agent_executor.invoke({"input": question}) print(f"\n✅ 最终答案:{result['output']}\n") except Exception as e: print(f"\n❌ 错误:{e}\n")
def example3_complex_task() -> None: """示例3:复杂任务""" print("\n=== 示例3:需要多个工具的复杂任务 ===\n")
llm = ChatOpenAI( base_url=os.getenv("ALIBABA_BASE_URL"), api_key=os.getenv("ALIBABA_API_KEY"), model="qwen-plus", temperature=0, )
tools = [get_current_time, calculator, search_info]
prompt = PromptTemplate.from_template(""" 回答以下问题。你有以下工具:
{tools}
工具名称:{tool_names}
格式: Question: 问题 Thought: 思考 Action: 工具名 Action Input: 输入 Observation: 结果 ... (重复) Thought: 知道答案了 Final Answer: 答案
Question: {input} {agent_scratchpad} """)
agent = create_react_agent(llm=llm, tools=tools, prompt=prompt) agent_executor = AgentExecutor( agent=agent, tools=tools, verbose=True, max_iterations=10 )
question = "先告诉我现在的时间,然后搜索Python的信息,最后计算2的10次方"
print(f"❓ 复杂问题:{question}\n") print("="*60 + "\n")
try: result = agent_executor.invoke({"input": question}) print(f"\n✅ 最终答案:\n{result['output']}\n") except Exception as e: print(f"\n❌ 错误:{e}\n")
def main() -> None: """主函数""" example1_test_tools() print("\n" + "="*70 + "\n")
example2_agent_with_tools() print("\n" + "="*70 + "\n")
example3_complex_task()
if __name__ == "__main__": main()
|