diff --git a/code/chapter1/FirstAgentTest.py b/code/chapter1/FirstAgentTest.py index 43098741..1b2f8ce5 100644 --- a/code/chapter1/FirstAgentTest.py +++ b/code/chapter1/FirstAgentTest.py @@ -28,10 +28,11 @@ def get_weather(city: str) -> str: """ - 通过调用 wttr.in API 查询真实的天气信息。 + 通过调用 WeatherAPI 查询真实的天气信息。 """ + weather_api_key='YOUR_API_KEY' # API端点,我们请求JSON格式的数据 - url = f"https://wttr.in/{city}?format=j1" + url = f"https://api.weatherapi.com/v1/current.json?key={weather_api_key}&q={city}&aqi=no" try: # 发起网络请求 @@ -42,9 +43,9 @@ def get_weather(city: str) -> str: data = response.json() # 提取当前天气状况 - current_condition = data['current_condition'][0] - weather_desc = current_condition['weatherDesc'][0]['value'] - temp_c = current_condition['temp_C'] + current_condition = data['current'] + weather_desc = current_condition['condition']['text'] + temp_c = current_condition['temp_c'] # 格式化成自然语言返回 return f"{city}当前天气:{weather_desc},气温{temp_c}摄氏度" diff --git a/code/chapter2/ELIZA.py b/code/chapter2/ELIZA.py index 5d161c18..b9ac158e 100644 --- a/code/chapter2/ELIZA.py +++ b/code/chapter2/ELIZA.py @@ -42,7 +42,7 @@ # 定义代词转换规则 pronoun_swap = { - "i": "you", "you": "i", "me": "you", "my": "your", + "i": "you", "you": "i", "me": "you", "my": "your", "your": "my", "am": "are", "are": "am", "was": "were", "i'd": "you would", "i've": "you have", "i'll": "you will", "yours": "mine", "mine": "yours" diff --git a/code/chapter3/BPE.py b/code/chapter3/BPE.py index cee0e589..20c3509b 100644 --- a/code/chapter3/BPE.py +++ b/code/chapter3/BPE.py @@ -17,7 +17,8 @@ def merge_vocab(pair, v_in): for word in v_in: w_out = p.sub(''.join(pair), word) v_out[w_out] = v_in[word] - return v_out + return v_outs + # 准备语料库,每个词末尾加上表示结束,并切分好字符 vocab = {'h u g ': 1, 'p u g ': 1, 'p u n ': 1, 'b u n ': 1} diff --git a/code/chapter4/.env copy b/code/chapter4/.env copy deleted file mode 100644 index 26b81a57..00000000 --- a/code/chapter4/.env copy +++ /dev/null @@ -1,4 +0,0 @@ -LLM_MODEL_ID="YOUR-MODEL" -LLM_API_KEY="YOUR-API-KEY" -LLM_BASE_URL="YOUR-URL" -SERPAPI_API_KEY="YOUR_SERPAPI_API_KEY" \ No newline at end of file diff --git a/code/chapter4/Reflection.py b/code/chapter4/Reflection.py index fdf0d402..1a2ae82d 100644 --- a/code/chapter4/Reflection.py +++ b/code/chapter4/Reflection.py @@ -107,6 +107,7 @@ def run(self, task: str): print("\n--- 正在进行初始尝试 ---") initial_prompt = INITIAL_PROMPT_TEMPLATE.format(task=task) initial_code = self._get_llm_response(initial_prompt) + print(f"✅ 初始尝试完成,生成的代码:\n{initial_code}") self.memory.add_record("execution", initial_code) # --- 2. 迭代循环:反思与优化 --- @@ -118,6 +119,7 @@ def run(self, task: str): last_code = self.memory.get_last_execution() reflect_prompt = REFLECT_PROMPT_TEMPLATE.format(task=task, code=last_code) feedback = self._get_llm_response(reflect_prompt) + print(f"✅ 反思完成,反馈: {feedback}") self.memory.add_record("reflection", feedback) # b. 检查是否需要停止 @@ -133,6 +135,7 @@ def run(self, task: str): feedback=feedback ) refined_code = self._get_llm_response(refine_prompt) + print(f"✅ 优化完成,生成的代码:\n{refined_code}") self.memory.add_record("execution", refined_code) final_code = self.memory.get_last_execution() diff --git a/code/chapter4/llm_client.py b/code/chapter4/llm_client.py index b7e2d0a3..104b2678 100644 --- a/code/chapter4/llm_client.py +++ b/code/chapter4/llm_client.py @@ -43,9 +43,9 @@ def think(self, messages: List[Dict[str, str]], temperature: float = 0) -> str: collected_content = [] for chunk in response: content = chunk.choices[0].delta.content or "" - print(content, end="", flush=True) + # print(content, end="", flush=True) collected_content.append(content) - print() # 在流式输出结束后换行 + # print() # 在流式输出结束后换行 return "".join(collected_content) except Exception as e: diff --git a/code/chapter6/AgentScopeDemo/main_cn.py b/code/chapter6/AgentScopeDemo/main_cn.py index 2cd6aa3f..af6df490 100644 --- a/code/chapter6/AgentScopeDemo/main_cn.py +++ b/code/chapter6/AgentScopeDemo/main_cn.py @@ -33,6 +33,8 @@ MAX_DISCUSSION_ROUND, ) +os.environ["DASHSCOPE_API_KEY"] = "sk-fbd837c733ba4ce5a15d4a5555c27f41" + class ThreeKingdomsWerewolfGame: """三国狼人杀游戏主类""" diff --git a/code/chapter6/AutoGenDemo/.env copy b/code/chapter6/AutoGenDemo/.env copy deleted file mode 100644 index 57b59999..00000000 --- a/code/chapter6/AutoGenDemo/.env copy +++ /dev/null @@ -1,4 +0,0 @@ -LLM_MODEL_ID="YOUR-MODEL" -LLM_API_KEY="YOUR-API-KEY" -LLM_BASE_URL="YOUR-URL" -LLM_TIMEOUT=60 \ No newline at end of file diff --git a/code/chapter6/AutoGenDemo/autogen_software_team.py b/code/chapter6/AutoGenDemo/autogen_software_team.py index 1dd5f9d0..d21abb3d 100644 --- a/code/chapter6/AutoGenDemo/autogen_software_team.py +++ b/code/chapter6/AutoGenDemo/autogen_software_team.py @@ -106,11 +106,32 @@ def create_user_proxy(): name="UserProxy", description="""用户代理,负责以下职责: 1. 代表用户提出开发需求 -2. 执行最终的代码实现 -3. 验证功能是否符合预期 -4. 提供用户反馈和建议 - -完成测试后请回复 TERMINATE。""", +2. 在代码审查完成后执行测试验证 +3. 验证功能是否符合原始需求 +4. 对工程师提供的代码进行实际验证和测试 + +你刚刚收到的代码是工程师为黄金价格显示应用开发的完整实现,包含: +- 完整的app.py文件代码 +- Streamlit应用的所有功能 +- 数据获取、UI展示、错误处理等完整模块 + +测试验证步骤: +1. **代码语法检查**:分析代码是否有语法错误或导入问题 +2. **核心功能验证**:检查以下功能是否实现: + - 实时黄金价格显示(美元/盎司) + - 24小时价格趋势图表 + - 手动刷新按钮功能 + - 错误处理和加载状态 +3. **用户体验评估**:评估界面是否简洁美观、用户友好 +4. **运行环境检查**:确认代码依赖(streamlit, requests, pandas, altair等)是否合理 +5. **安全性检查**:确认API密钥通过环境变量注入,前端不可见 + +请基于工程师提供的完整代码进行上述测试验证,然后提供具体的测试结果反馈,包括: +- 哪些功能已经正确实现 +- 是否存在任何问题或改进建议 +- 代码的整体质量评估 + +完成测试验证后,请总结测试结果并回复 TERMINATE。""", ) async def run_software_development_team(): @@ -145,10 +166,10 @@ async def run_software_development_team(): ) # 定义开发任务 - task = """我们需要开发一个比特币价格显示应用,具体要求如下: + task = """我们需要开发一个黄金价格显示应用,具体要求如下: 核心功能: -- 实时显示比特币当前价格(USD) +- 实时显示黄金当前价格(美元/盎司) - 显示24小时价格变化趋势(涨跌幅和涨跌额) - 提供价格刷新功能 @@ -188,6 +209,3 @@ async def run_software_development_team(): print(f"❌ 运行错误:{e}") import traceback traceback.print_exc() - - - diff --git a/code/chapter6/CAMEL/DigitalBookWriting.py b/code/chapter6/CAMEL/DigitalBookWriting.py index 1ef23d38..0ab80083 100644 --- a/code/chapter6/CAMEL/DigitalBookWriting.py +++ b/code/chapter6/CAMEL/DigitalBookWriting.py @@ -6,22 +6,21 @@ from dotenv import load_dotenv import os -load_dotenv() -LLM_API_KEY = os.getenv("LLM_API_KEY") -LLM_BASE_URL = os.getenv("LLM_BASE_URL") -LLM_MODEL = os.getenv("LLM_MODEL") +LLM_MODEL_ID="coding-glm-4.7-free" +LLM_API_KEY="sk-Yfh9jNQSWoNgoZAC23Cb8d1a924d43E286Cd81Dc17Fa0b89" +LLM_BASE_URL="https://aihubmix.com/v1" #创建模型,在这里以Qwen为例,调用的百炼大模型平台API model = ModelFactory.create( - model_platform=ModelPlatformType.QWEN, - model_type=LLM_MODEL, + model_platform=ModelPlatformType.ZHIPU, + model_type=LLM_MODEL_ID, url=LLM_BASE_URL, api_key=LLM_API_KEY ) # 定义协作任务 task_prompt = """ -创作一本关于"拖延症心理学"的短篇电子书,目标读者是对心理学感兴趣的普通大众。 +创作一本关于"人类移民"的短篇电子书,目标读者是对科幻题材感兴趣的普通大众。 要求: 1. 内容科学严谨,基于实证研究 2. 语言通俗易懂,避免过多专业术语 @@ -34,7 +33,7 @@ # 初始化角色扮演会话 role_play_session = RolePlaying( - assistant_role_name="心理学家", + assistant_role_name="量子力学学家", user_role_name="作家", task_prompt=task_prompt, model=model diff --git a/code/chapter6/Langgraph/Dialogue_System.py b/code/chapter6/Langgraph/Dialogue_System.py index 281868a4..35ff832c 100644 --- a/code/chapter6/Langgraph/Dialogue_System.py +++ b/code/chapter6/Langgraph/Dialogue_System.py @@ -31,13 +31,13 @@ class SearchState(TypedDict): # 初始化模型和Tavily客户端 llm = ChatOpenAI( model=os.getenv("LLM_MODEL_ID", "gpt-4o-mini"), - api_key=os.getenv("LLM_API_KEY"), + api_key=os.getenv("LLM_API_KEY", ""), base_url=os.getenv("LLM_BASE_URL", "https://api.openai.com/v1"), temperature=0.7 ) # 初始化Tavily客户端 -tavily_client = TavilyClient(api_key=os.getenv("TAVILY_API_KEY")) +tavily_client = TavilyClient(api_key=os.getenv("TAVILY_API_KEY", "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")) def understand_query_node(state: SearchState) -> SearchState: """步骤1:理解用户查询并生成搜索关键词""" @@ -195,11 +195,7 @@ def create_search_assistant(): async def main(): """主函数:运行智能搜索助手""" - - # 检查API密钥 - if not os.getenv("TAVILY_API_KEY"): - print("❌ 错误:请在.env文件中配置TAVILY_API_KEY") - return + app = create_search_assistant() diff --git a/docs/chapter1/Chapter1-Introduction-to-Agents.md b/docs/chapter1/Chapter1-Introduction-to-Agents.md index 8fe22d43..2ff2196e 100644 --- a/docs/chapter1/Chapter1-Introduction-to-Agents.md +++ b/docs/chapter1/Chapter1-Introduction-to-Agents.md @@ -258,17 +258,18 @@ Let's begin! (2) Tool 1: Query Real Weather -We will use the free weather query service `wttr.in`, which can return weather data for a specified city in JSON format. Here is the code to implement this tool: +We will use the free weather query service `weatherapi`(You need to register an account at https://www.weatherapi.com to obtain the weather_api_key), which can return weather data for a specified city in JSON format. Here is the code to implement this tool: ```python import requests def get_weather(city: str) -> str: """ - Query real weather information by calling the wttr.in API. + Query real weather information by calling the WeatherAPI. """ + weather_api_key='YOUR_API_KEY' # API endpoint, we request data in JSON format - url = f"https://wttr.in/{city}?format=j1" + url = f"https://api.weatherapi.com/v1/current.json?key={weather_api_key}&q={city}&aqi=no" try: # Make network request @@ -279,9 +280,9 @@ def get_weather(city: str) -> str: data = response.json() # Extract current weather conditions - current_condition = data['current_condition'][0] - weather_desc = current_condition['weatherDesc'][0]['value'] - temp_c = current_condition['temp_C'] + current_condition = data['current'] + weather_desc = current_condition['condition']['text'] + temp_c = current_condition['temp_c'] # Format as natural language return return f"{city} current weather: {weather_desc}, temperature {temp_c} degrees Celsius" @@ -296,7 +297,7 @@ def get_weather(city: str) -> str: (3) Tool 2: Search and Recommend Tourist Attractions -We will define a new tool `search_attraction` that searches the internet for suitable attractions based on city and weather conditions: +We will define a new tool `get_attraction` that searches the internet for suitable attractions based on city and weather conditions: ```python import os diff --git "a/docs/chapter1/\347\254\254\344\270\200\347\253\240 \345\210\235\350\257\206\346\231\272\350\203\275\344\275\223.md" "b/docs/chapter1/\347\254\254\344\270\200\347\253\240 \345\210\235\350\257\206\346\231\272\350\203\275\344\275\223.md" index cf8625eb..71ffcae3 100644 --- "a/docs/chapter1/\347\254\254\344\270\200\347\253\240 \345\210\235\350\257\206\346\231\272\350\203\275\344\275\223.md" +++ "b/docs/chapter1/\347\254\254\344\270\200\347\253\240 \345\210\235\350\257\206\346\231\272\350\203\275\344\275\223.md" @@ -262,17 +262,18 @@ Action的格式必须是以下之一: (2)工具 1:查询真实天气 -我们将使用免费的天气查询服务 `wttr.in`,它能以 JSON 格式返回指定城市的天气数据。下面是实现该工具的代码: +我们将使用免费的天气查询服务 `weatherapi`(需要去https://www.weatherapi.com注册账户以获取weather_api_key),它能以 JSON 格式返回指定城市的天气数据。下面是实现该工具的代码: ```python import requests def get_weather(city: str) -> str: """ - 通过调用 wttr.in API 查询真实的天气信息。 + 通过调用 WeatherAPI 查询真实的天气信息。 """ + weather_api_key='YOUR_API_KEY' # API端点,我们请求JSON格式的数据 - url = f"https://wttr.in/{city}?format=j1" + url = f"https://api.weatherapi.com/v1/current.json?key={weather_api_key}&q={city}&aqi=no" try: # 发起网络请求 @@ -283,9 +284,9 @@ def get_weather(city: str) -> str: data = response.json() # 提取当前天气状况 - current_condition = data['current_condition'][0] - weather_desc = current_condition['weatherDesc'][0]['value'] - temp_c = current_condition['temp_C'] + current_condition = data['current'] + weather_desc = current_condition['condition']['text'] + temp_c = current_condition['temp_c'] # 格式化成自然语言返回 return f"{city}当前天气:{weather_desc},气温{temp_c}摄氏度" @@ -300,7 +301,7 @@ def get_weather(city: str) -> str: (3)工具 2:搜索并推荐旅游景点 -我们将定义一个新工具 `search_attraction`,它会根据城市和天气状况,互联网上搜索合适的景点: +我们将定义一个新工具 `get_attraction`,它会根据城市和天气状况,互联网上搜索合适的景点: ```python import os