Skip to content

Commit e7fdb36

Browse files
committed
修复bug
1 parent da9f927 commit e7fdb36

File tree

7 files changed

+76
-39
lines changed

7 files changed

+76
-39
lines changed

examples/agent_example.py

Lines changed: 43 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
1818

1919
from pydify import AgentClient
20+
from pydify.common import DifyAPIError
2021

2122
# 从环境变量或直接设置 API 密钥
2223
API_KEY = os.environ.get("DIFY_API_KEY_AGENT", "app-JH2PWol59GDhOfLpB1Qwvts3")
@@ -73,7 +74,7 @@ def example_send_message_streaming():
7374

7475
# 定义处理函数
7576
def on_agent_message(chunk):
76-
print(f"收到文本块: {chunk.get('answer', '')}", end="", flush=True)
77+
print(f"{chunk.get('answer', '')}", end="", flush=True)
7778

7879
def on_agent_thought(chunk):
7980
print(f"\n\n[Agent思考] {chunk.get('position')}:")
@@ -96,29 +97,47 @@ def on_message_end(chunk):
9697
def on_error(chunk):
9798
print(f"\n错误: {chunk.get('message', '未知错误')}")
9899

99-
# 发送消息(流式模式,Agent只支持流式模式)
100-
stream = client.send_message(
101-
query="帮我搜索最近一周的股市行情,并分析趋势",
102-
user=USER_ID
103-
)
100+
# 请求参数,包括加入重试和超时设置
101+
request_kwargs = get_request_kwargs()
104102

105-
# 处理流式响应
106-
result = client.process_streaming_response(
107-
stream,
108-
handle_agent_message=on_agent_message,
109-
handle_agent_thought=on_agent_thought,
110-
handle_message_file=on_message_file,
111-
handle_message_end=on_message_end,
112-
handle_error=on_error
113-
)
114-
115-
print("\n\n处理结果摘要:")
116-
print(f"消息ID: {result.get('message_id')}")
117-
print(f"会话ID: {result.get('conversation_id')}")
118-
print(f"Agent思考步骤数: {len(result.get('agent_thoughts', []))}")
103+
try:
104+
# 发送消息(流式模式,Agent只支持流式模式)
105+
print("发送查询: '帮我搜索最近一周的股市行情,并分析趋势'")
106+
stream = client.send_message(
107+
query="帮我搜索最近一周的股市行情,并分析趋势",
108+
user=USER_ID,
109+
inputs={}, # 添加空的inputs参数
110+
**request_kwargs # 传递请求参数
111+
)
112+
113+
# 处理流式响应
114+
result = client.process_streaming_response(
115+
stream,
116+
handle_agent_message=on_agent_message,
117+
handle_agent_thought=on_agent_thought,
118+
handle_message_file=on_message_file,
119+
handle_message_end=on_message_end,
120+
handle_error=on_error
121+
)
122+
123+
print("\n\n处理结果摘要:")
124+
print(f"消息ID: {result.get('message_id')}")
125+
print(f"会话ID: {result.get('conversation_id')}")
126+
print(f"Agent思考步骤数: {len(result.get('agent_thoughts', []))}")
127+
128+
# 返回会话ID,可用于后续对话
129+
return result.get("conversation_id")
119130

120-
# 返回会话ID,可用于后续对话
121-
return result.get("conversation_id")
131+
except DifyAPIError as e:
132+
print(f"API错误: {str(e)}")
133+
print(f"状态码: {e.status_code}")
134+
print(f"错误数据: {e.error_data}")
135+
return None
136+
except Exception as e:
137+
print(f"发生异常: {str(e)}")
138+
import traceback
139+
traceback.print_exc()
140+
return None
122141

123142
def example_continuation_conversation():
124143
"""多轮对话示例"""
@@ -133,7 +152,7 @@ def example_continuation_conversation():
133152

134153
# 继续对话函数
135154
def on_agent_message(chunk):
136-
print(f"收到文本块: {chunk.get('answer', '')}", end="", flush=True)
155+
print(f"{chunk.get('answer', '')}", end="", flush=True)
137156

138157
def on_agent_thought(chunk):
139158
print(f"\n\n[Agent思考] {chunk.get('position')}:")
@@ -409,7 +428,7 @@ def example_send_message_with_image():
409428

410429
# 定义处理函数
411430
def on_agent_message(chunk):
412-
print(f"收到文本块: {chunk.get('answer', '')}", end="", flush=True)
431+
print(f"{chunk.get('answer', '')}", end="", flush=True)
413432

414433
def on_agent_thought(chunk):
415434
print(f"\n\n[Agent思考] {chunk.get('position')}:")

examples/chatbot_example.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def example_send_message_streaming():
7373

7474
# 消息处理函数
7575
def on_message(chunk):
76-
print(f"收到文本块: {chunk.get('answer', '')}", end="", flush=True)
76+
print(f"{chunk.get('answer', '')}", end="", flush=True)
7777

7878
def on_message_end(chunk):
7979
print("\n消息完成!")

examples/chatflow_example.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ def example_send_message_streaming():
7474

7575
# 消息处理函数
7676
def on_message(chunk):
77-
print(f"收到文本块: {chunk.get('answer', '')}", end="", flush=True)
77+
print(f"{chunk.get('answer', '')}", end="", flush=True)
7878

7979
def on_message_end(chunk):
8080
print("\n消息完成!")

pydify/agent.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ def send_message(
2828
conversation_id: str = None,
2929
files: List[Dict[str, Any]] = None,
3030
auto_generate_name: bool = True,
31+
**kwargs # 添加kwargs参数,用于接收额外的请求参数
3132
) -> Generator[Dict[str, Any], None, None]:
3233
"""
3334
发送对话消息,创建会话消息。在Agent模式下,只支持streaming流式模式。
@@ -40,13 +41,14 @@ def send_message(
4041
conversation_id (str, optional): 会话ID,基于之前的聊天记录继续对话时需提供。默认为None
4142
files (List[Dict[str, Any]], optional): 要包含在消息中的文件列表,每个文件为一个字典。默认为None
4243
auto_generate_name (bool, optional): 是否自动生成会话标题。默认为True
44+
**kwargs: 传递给底层API请求的额外参数,如timeout, max_retries等
4345
4446
Returns:
4547
Generator[Dict[str, Any], None, None]: 返回字典生成器
4648
4749
Raises:
4850
ValueError: 当提供了无效的参数时
49-
requests.HTTPError: 当API请求失败时
51+
DifyAPIError: 当API请求失败时
5052
"""
5153
if response_mode != "streaming":
5254
raise ValueError("Agent mode only supports streaming response mode")
@@ -56,11 +58,9 @@ def send_message(
5658
"user": user,
5759
"response_mode": "streaming",
5860
"auto_generate_name": auto_generate_name,
61+
"inputs": inputs or {}, # 确保inputs参数总是存在,如果未提供则使用空字典
5962
}
6063

61-
if inputs:
62-
payload["inputs"] = inputs
63-
6464
if conversation_id:
6565
payload["conversation_id"] = conversation_id
6666

@@ -69,7 +69,7 @@ def send_message(
6969

7070
endpoint = "chat-messages"
7171

72-
return self.post_stream(endpoint, json_data=payload)
72+
return self.post_stream(endpoint, json_data=payload, **kwargs) # 传递额外参数
7373

7474
def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
7575
"""
@@ -528,7 +528,8 @@ def process_streaming_response(
528528
示例:
529529
```python
530530
def on_agent_message(chunk):
531-
print(f"收到文本块: {chunk['answer']}")
531+
# 打印Agent返回的文本块
532+
print(f"{chunk['answer']}")
532533
533534
def on_agent_thought(chunk):
534535
print(f"Agent思考: {chunk['thought']}")

pydify/chatbot.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -202,7 +202,7 @@ def process_streaming_response(
202202
示例:
203203
```python
204204
def on_message(chunk):
205-
print(f"收到文本块: {chunk['answer']}")
205+
print(f"{chunk['answer']}")
206206
207207
def on_message_end(chunk):
208208
print(f"消息结束: ID={chunk['message_id']}")

pydify/common.py

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -191,20 +191,37 @@ def post_stream(self, endpoint: str, json_data: Dict[str, Any], **kwargs) -> Gen
191191
# 添加超时参数
192192
kwargs["timeout"] = timeout
193193

194+
# 打印请求信息,方便调试
195+
print(f"请求URL: {url}")
196+
print(f"请求参数: {json.dumps(json_data, ensure_ascii=False)[:500]}")
197+
194198
for attempt in range(max_retries + 1):
195199
try:
196200
with requests.post(url, json=json_data, headers=headers, stream=True, **kwargs) as response:
197201
if not response.ok:
198202
error_msg = f"API request failed: {response.status_code}"
199203
error_data = {}
204+
200205
try:
206+
# 尝试解析响应内容作为JSON
201207
error_data = response.json()
202-
error_msg = f"{error_msg} - {error_data.get('error', {}).get('message', '')}"
203-
except RequestsJSONDecodeError:
204-
# 如果无法解析为JSON,提供一个简单的错误消息
205-
error_msg = f"{error_msg} - 响应无法解析为JSON"
208+
# 提取标准错误信息字段
209+
if "error" in error_data and isinstance(error_data["error"], dict):
210+
error_msg = f"{error_msg} - {error_data['error'].get('message', '')}"
211+
elif "message" in error_data:
212+
error_msg = f"{error_msg} - {error_data.get('message', '')}"
213+
except Exception:
214+
# 如果无法解析为JSON,提供原始响应内容
206215
if response.text:
207-
print(f"响应内容: {response.text[:100]}")
216+
error_msg = f"{error_msg} - 响应内容: {response.text[:200]}"
217+
else:
218+
error_msg = f"{error_msg} - 服务器未返回错误详情"
219+
220+
# 打印详细的错误信息,方便调试
221+
print(f"API请求失败 ({endpoint}):")
222+
print(f"状态码: {response.status_code}")
223+
print(f"响应头: {dict(response.headers)}")
224+
print(f"响应内容: {response.text[:500] if response.text else '(无内容)'}")
208225

209226
# 如果是可重试的错误码,并且还有重试次数,则重试
210227
if response.status_code in [429, 500, 502, 503, 504] and attempt < max_retries:

pydify/text_generation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,7 @@ def process_streaming_response(
122122
示例:
123123
```python
124124
def on_message(chunk):
125-
print(f"收到文本块: {chunk['answer']}")
125+
print(f"{chunk['answer']}")
126126
127127
def on_message_end(chunk):
128128
print(f"消息结束: ID={chunk['message_id']}")

0 commit comments

Comments
 (0)