From fa89121f43e7890dbcb9409d8e9a283d7a88b7da Mon Sep 17 00:00:00 2001 From: guanjihuan Date: Fri, 7 Nov 2025 16:53:38 +0800 Subject: [PATCH] update --- .../langchain_example_with_tool_version_2.py | 54 +++++++++++ .../langchain_running_code_version_2.py | 91 +++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 2025.11.02_langchain/langchain_example_with_tool_version_2.py create mode 100644 2025.11.04_langchain_running_code/langchain_running_code_version_2.py diff --git a/2025.11.02_langchain/langchain_example_with_tool_version_2.py b/2025.11.02_langchain/langchain_example_with_tool_version_2.py new file mode 100644 index 0000000..b97c88e --- /dev/null +++ b/2025.11.02_langchain/langchain_example_with_tool_version_2.py @@ -0,0 +1,54 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47909 +""" + +import os +import dotenv +from langchain_openai import ChatOpenAI +from langchain_core.tools import tool +from langchain.agents import create_agent +from langchain_core.globals import set_debug # ✅ 用于开启详细日志 + +# 开启调试日志输出 +set_debug(True) + +# 加载环境变量 +dotenv.load_dotenv() + +# 定义工具 +@tool +def get_current_time() -> str: + """获取当前日期和时间""" + from datetime import datetime + return datetime.now().strftime("%Y-%m-%d %H:%M:%S") + +@tool +def add_numbers(a: float, b: float) -> float: + """将两个数字相加""" + return a + b + +tools = [get_current_time, add_numbers] + +# 创建 LLM +llm = ChatOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("DASHSCOPE_BASE_URL"), + model="qwen-plus", + temperature=0.7, +) + +# 创建 agent +agent = create_agent(llm, tools) + +# 执行调用(此时会打印详细步骤) +response = agent.invoke( + { + "messages": [ + {"role": "user", "content": "现在几点了?然后把 123 和 456 加起来。"} + ] + } +) + +print("\n---\n") +print(response["messages"][-1].content) \ No newline at end of file diff --git a/2025.11.04_langchain_running_code/langchain_running_code_version_2.py b/2025.11.04_langchain_running_code/langchain_running_code_version_2.py new file mode 100644 index 0000000..76d1abe --- /dev/null +++ b/2025.11.04_langchain_running_code/langchain_running_code_version_2.py @@ -0,0 +1,91 @@ +""" +This code is supported by the website: https://www.guanjihuan.com +The newest version of this code is on the web page: https://www.guanjihuan.com/archives/47925 +""" + +import os +import dotenv +from langchain_openai import ChatOpenAI +from langchain_core.tools import tool +from langchain.agents import create_agent +from langchain_core.globals import set_debug + +# 开启调试日志输出 +set_debug(True) +dotenv.load_dotenv() + +# ----------------------- +# 定义工具 +# ----------------------- +@tool +def execute_python(code: str) -> str: + """执行 Python 代码并返回输出""" + import sys, io + old_stdout = sys.stdout + sys.stdout = mystdout = io.StringIO() + try: + exec(code, {}) + except Exception as e: + return f"Error: {e}" + finally: + sys.stdout = old_stdout + return mystdout.getvalue().strip() + +tools = [execute_python] + +# ----------------------- +# 创建 LLM +# ----------------------- +llm = ChatOpenAI( + api_key=os.getenv("OPENAI_API_KEY"), + base_url=os.getenv("DASHSCOPE_BASE_URL"), + model="qwen-plus", + temperature=0, +) + +# ----------------------- +# 创建 Agent +# ----------------------- +agent = create_agent(llm, tools) + +# ----------------------- +# 系统消息,模拟 ReAct 风格 +# ----------------------- +system_message = """ +你是一个严谨的 Python 编程助手,必须通过工具执行代码来验证逻辑。 +每次只能执行一个 Action,所有 Python 代码必须通过工具执行,不得假设输出结果。 +Action Input 必须是纯 Python 代码,不要包含 Markdown 代码块符号。 +如果测试失败(如 assert 报错),请根据错误信息修正代码并重新测试。 +输出必须严格遵循以下格式: +Thought: <你的思考> +Action: <工具名称> +Action Input: <纯 Python 代码> +Observation: <工具返回结果> +Final Answer: <最终答案> +""" + +# ----------------------- +# 用户问题:编写 Fibonacci 函数 +# ----------------------- +user_message = """ +请编写一个 Python 函数 fibonacci(n),返回第 n 个斐波那契数。 +先测试代码正确性,如果测试通过再进行优化,并给出最终代码。 +""" + +# ----------------------- +# 调用 Agent +# ----------------------- +response = agent.invoke( + { + "messages": [ + {"role": "system", "content": system_message}, + {"role": "user", "content": user_message} + ] + } +) + +# ----------------------- +# 输出结果 +# ----------------------- +print("\n--- Agent 输出 ---\n") +print(response["messages"][-1].content) \ No newline at end of file