diff --git a/langgraph-tutorial/README.md b/langgraph-tutorial/README.md index 6906e49..156dbc7 100644 --- a/langgraph-tutorial/README.md +++ b/langgraph-tutorial/README.md @@ -33,22 +33,24 @@ python hello.py # Hello World python conditional.py # 条件边 python loop.py # 循环 python agent.py # AI 智能体 (模拟模式) -python react_agent.py # ReAct 智能体 (需要 API) ``` ## ReAct 智能体配置 +编辑 `config.py`: + +```python +API_KEY = "sk-..." # 你的 API Key +BASE_URL = "https://api.openai.com/v1" # API 地址 +MODEL = "gpt-4o-mini" # 模型名称 +MAX_ITERATIONS = 4 # 最大迭代次数 +TEMPERATURE = 0.3 # 温度参数 +``` + +运行: ```powershell -# 必需 -$env:OPENAI_API_KEY = "your-api-key" - -# 可选 -$env:OPENAI_BASE_URL = "https://your-api.com/v1" # 默认 OpenAI -$env:MODEL_NAME = "gpt-4o-mini" # 默认 gpt-4o-mini - -# 运行 -python react_agent.py # 内置测试 -python react_agent.py "你的问题" # 自定义问题 +python react_agent.py # 内置测试 +python react_agent.py "你的问题" # 自定义问题 ``` ## 下一步学习 diff --git a/langgraph-tutorial/config.py b/langgraph-tutorial/config.py new file mode 100644 index 0000000..dda23e0 --- /dev/null +++ b/langgraph-tutorial/config.py @@ -0,0 +1,13 @@ +""" +API 配置文件 +修改这里来配置你的 API +""" + +# API 配置 +API_KEY = "sk-..." # 你的 API Key +BASE_URL = "https://api.openai.com/v1" # API 地址(OpenAI 兼容) +MODEL = "gpt-4o-mini" # 模型名称 + +# 智能体配置 +MAX_ITERATIONS = 4 # 最大迭代次数 +TEMPERATURE = 0.3 # 温度参数(越低越确定) \ No newline at end of file diff --git a/langgraph-tutorial/react_agent.py b/langgraph-tutorial/react_agent.py index b7333e9..04abea3 100644 --- a/langgraph-tutorial/react_agent.py +++ b/langgraph-tutorial/react_agent.py @@ -1,23 +1,17 @@ """ LangGraph 第 5 步:真实 LLM 智能体 ReAct 模式:思考(Reason) - 行动(Act) - 观察(Observe) -支持自定义 OpenAI 兼容 API +配置见 config.py """ -import os import sys from langgraph.graph import StateGraph, START, END from typing import TypedDict -# 1️⃣ 配置 API -API_KEY = os.environ.get("OPENAI_API_KEY", "") -BASE_URL = os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1") -MODEL = os.environ.get("MODEL_NAME", "gpt-4o-mini") +# 1️⃣ 加载配置 +from config import API_KEY, BASE_URL, MODEL, MAX_ITERATIONS, TEMPERATURE -if not API_KEY: - print("请先设置环境变量:") - print(" $env:OPENAI_API_KEY = 'your-api-key'") - print(" $env:OPENAI_BASE_URL = 'your-api-base-url' # 可选,默认 OpenAI") - print(" $env:MODEL_NAME = 'gpt-4o-mini' # 可选") +if API_KEY == "sk-...": + print("请先在 config.py 中配置 API_KEY") exit(1) from openai import OpenAI @@ -95,7 +89,7 @@ def think_node(state: AgentState): model=MODEL, messages=messages, max_tokens=300, - temperature=0.3, + temperature=TEMPERATURE, ) thought_text = response.choices[0].message.content @@ -192,6 +186,7 @@ print("LangGraph ReAct 智能体") print("=" * 50) print(f"API: {BASE_URL}") print(f"模型: {MODEL}") +print(f"最大迭代: {MAX_ITERATIONS}") print("\n图结构:") print(" START -> think -> [有行动?] -> act -> think (循环)") print(" |") @@ -215,7 +210,7 @@ for q in questions: "question": q, "thoughts": [], "iteration": 0, - "max_iterations": 4, + "max_iterations": MAX_ITERATIONS, "action": "", "observation": "", "final_answer": "",