Skip to content

Commit 8a06030

Browse files
committed
完善整体
1 parent bb5560c commit 8a06030

File tree

6 files changed

+248
-325
lines changed

6 files changed

+248
-325
lines changed

examples/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,7 @@ def run_example(example_fn: Callable, *args, **kwargs):
344344
print(f"{example_fn.__doc__.strip()}\n")
345345

346346
return example_fn(*args, **kwargs)
347-
347+
348348
except Exception as e:
349349
print(f"\n示例运行过程中发生错误: {e}")
350350
import traceback

pydify/agent.py

Lines changed: 11 additions & 101 deletions
Original file line numberDiff line numberDiff line change
@@ -72,120 +72,30 @@ def send_message(
7272
endpoint = "chat-messages"
7373

7474
return self.post_stream(endpoint, json_data=payload, **kwargs) # 传递额外参数
75-
75+
7676
def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
7777
"""
78-
停止正在进行的响应,仅支持流式模式
78+
停止正在进行的响应流。此方法仅在流式模式下有效
7979
8080
Args:
81-
task_id (str): 任务ID,可在流式返回Chunk中获取
82-
user (str): 用户标识,必须和发送消息接口传入user保持一致
81+
task_id (str): 任务唯一标识,可从流式响应的数据块中获取
82+
user (str): 用户唯一标识,需要与发送消息时的user参数保持一致
8383
8484
Returns:
85-
Dict[str, Any]: 停止响应的结果
85+
Dict[str, Any]: 停止响应的结果,格式如下:
86+
{
87+
"result": "success" # 表示成功停止响应
88+
}
8689
8790
Raises:
88-
requests.HTTPError: 当API请求失败时
91+
requests.HTTPError: API请求失败时抛出此异常,包含具体的错误信息
92+
DifyAPIError: Dify服务端返回错误时抛出此异常
8993
"""
9094
endpoint = f"chat-messages/{task_id}/stop"
9195
payload = {"user": user}
9296
return self.post(endpoint, json_data=payload)
9397

94-
def message_feedback(
95-
self,
96-
message_id: str,
97-
user: str,
98-
rating: str = None,
99-
content: str = None,
100-
) -> Dict[str, Any]:
101-
"""
102-
对消息进行反馈(点赞/点踩)。
103-
104-
Args:
105-
message_id (str): 消息ID
106-
user (str): 用户标识
107-
rating (str, optional): 评价,可选值:'like'(点赞), 'dislike'(点踩), None(撤销)。默认为None
108-
content (str, optional): 反馈的具体信息。默认为None
109-
110-
Returns:
111-
Dict[str, Any]: 反馈结果
112-
113-
Raises:
114-
ValueError: 当提供了无效的参数时
115-
requests.HTTPError: 当API请求失败时
116-
"""
117-
if rating and rating not in ["like", "dislike", None]:
118-
raise ValueError("rating must be 'like', 'dislike' or None")
119-
120-
endpoint = f"messages/{message_id}/feedbacks"
121-
122-
payload = {"user": user}
123-
124-
if rating is not None:
125-
payload["rating"] = rating
126-
127-
if content:
128-
payload["content"] = content
129-
130-
return self.post(endpoint, json_data=payload)
131-
132-
def get_suggested_questions(
133-
self, message_id: str, user: str, **kwargs
134-
) -> Dict[str, Any]:
135-
"""
136-
获取下一轮建议问题列表。
137-
138-
Args:
139-
message_id (str): 消息ID
140-
user (str): 用户标识
141-
**kwargs: 额外的请求参数,如timeout、max_retries等
142-
143-
Returns:
144-
Dict[str, Any]: 建议问题列表
145-
146-
Raises:
147-
DifyAPIError: 当API请求失败时
148-
"""
149-
# 尝试多种可能的端点路径格式
150-
possible_endpoints = [
151-
f"messages/{message_id}/suggested", # 原始格式
152-
f"messages/{message_id}/suggested-questions", # 新格式1
153-
f"chat-messages/{message_id}/suggested-questions", # 新格式2
154-
"suggested-questions", # 当前格式
155-
]
156-
157-
params = {
158-
"user": user,
159-
}
160-
161-
# 添加详细日志
162-
# print(f"请求推荐问题: 消息ID={message_id}, 用户={user}")
163-
164-
# 尝试所有可能的端点,直到找到一个有效的
165-
last_error = None
166-
for endpoint in possible_endpoints:
167-
try:
168-
params_to_use = params.copy()
169-
# 如果端点是standalone的suggested-questions,需要添加message_id参数
170-
if endpoint == "suggested-questions":
171-
params_to_use["message_id"] = message_id
172-
else:
173-
# 否则可能不需要在参数中包含message_id
174-
params_to_use.pop("message_id", None)
175-
176-
print(f"尝试端点: {endpoint}, 参数: {params_to_use}")
177-
result = self.get(endpoint, params=params_to_use, **kwargs)
178-
print(f"端点 {endpoint} 请求成功!")
179-
return result
180-
except Exception as e:
181-
last_error = e
182-
print(f"端点 {endpoint} 请求失败: {str(e)}")
183-
continue
184-
185-
# 如果所有端点都失败,记录最后一个错误并返回空结果
186-
print(f"所有推荐问题端点请求都失败。最后错误: {str(last_error)}")
187-
return {"data": []}
188-
98+
18999

190100
def get_meta(self) -> Dict[str, Any]:
191101
"""

pydify/chatbot.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import os
1010
from typing import Any, Dict, Generator, List, Optional, Union
1111

12-
from .common import DifyBaseClient
12+
from .common import DifyBaseClient, DifyType
1313

1414

1515
class ChatbotClient(DifyBaseClient):
@@ -18,7 +18,7 @@ class ChatbotClient(DifyBaseClient):
1818
提供与Dify Chatbot应用API交互的方法,包括发送消息、获取历史消息、管理会话、
1919
上传文件、语音转文字、文字转语音等功能。
2020
"""
21-
21+
type = DifyType.Chatbot
2222
def send_message(
2323
self,
2424
query: str,
@@ -81,7 +81,7 @@ def send_message(
8181
return self.post_stream(endpoint, json_data=payload, **kwargs)
8282
else:
8383
return self.post(endpoint, json_data=payload, **kwargs)
84-
84+
8585
def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
8686
"""
8787
停止正在进行的响应,仅支持流式模式。

pydify/chatflow.py

Lines changed: 9 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -97,61 +97,27 @@ def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
9797
payload = {"user": user}
9898
return self.post(endpoint, json_data=payload)
9999

100-
def message_feedback(
101-
self,
102-
message_id: str,
103-
user: str,
104-
rating: str = None,
105-
content: str = None,
106-
) -> Dict[str, Any]:
107-
"""
108-
对消息进行反馈(点赞/点踩)。
109-
110-
Args:
111-
message_id (str): 消息ID
112-
user (str): 用户标识
113-
rating (str, optional): 评价,可选值:'like'(点赞), 'dislike'(点踩), None(撤销)。默认为None
114-
content (str, optional): 反馈的具体信息。默认为None
115-
116-
Returns:
117-
Dict[str, Any]: 反馈结果
118-
119-
Raises:
120-
ValueError: 当提供了无效的参数时
121-
requests.HTTPError: 当API请求失败时
122-
"""
123-
if rating and rating not in ["like", "dislike", None]:
124-
raise ValueError("rating must be 'like', 'dislike' or None")
125-
126-
endpoint = f"messages/{message_id}/feedbacks"
127-
128-
payload = {"user": user}
129-
130-
if rating is not None:
131-
payload["rating"] = rating
132-
133-
if content:
134-
payload["content"] = content
135-
136-
return self.post(endpoint, json_data=payload)
137-
138-
def get_suggested_questions(self, message_id: str, user: str) -> Dict[str, Any]:
100+
def get_suggested_questions(self, message_id: str, user: str, **kwargs) -> Dict[str, Any]:
139101
"""
140102
获取下一轮建议问题列表。
141103
142104
Args:
143105
message_id (str): 消息ID
144106
user (str): 用户标识
107+
**kwargs: 额外的请求参数,如timeout、max_retries等
145108
146109
Returns:
147110
Dict[str, Any]: 建议问题列表
148111
149112
Raises:
150-
requests.HTTPError: 当API请求失败时
113+
DifyAPIError: 当API请求失败时
151114
"""
152-
endpoint = f"messages/{message_id}/suggested"
153-
params = {"user": user}
154-
return self.get(endpoint, params=params)
115+
params = {
116+
"user": user,
117+
"message_id": message_id,
118+
}
119+
120+
return self.get("suggested-questions", params=params, **kwargs)
155121

156122
def get_messages(
157123
self,
@@ -402,95 +368,6 @@ def text_to_audio(
402368

403369
return self.post(endpoint, json_data=payload)
404370

405-
def upload_file(self, file_path: str, user: str) -> Dict[str, Any]:
406-
"""
407-
上传文件到Dify API,可用于图文多模态理解。支持多种格式的文件。
408-
409-
Args:
410-
file_path (str): 要上传的文件路径
411-
user (str): 用户标识
412-
413-
Returns:
414-
Dict[str, Any]: 上传文件的响应数据
415-
416-
Raises:
417-
FileNotFoundError: 当文件不存在时
418-
requests.HTTPError: 当API请求失败时
419-
"""
420-
if not os.path.exists(file_path):
421-
raise FileNotFoundError(f"File not found: {file_path}")
422-
423-
# 获取MIME类型
424-
mime_type, _ = mimetypes.guess_type(file_path)
425-
if not mime_type:
426-
mime_type = "application/octet-stream"
427-
428-
with open(file_path, "rb") as file:
429-
files = {"file": file}
430-
data = {"user": user}
431-
432-
headers = self._get_headers()
433-
# 移除Content-Type,让requests自动设置multipart/form-data
434-
headers.pop("Content-Type", None)
435-
436-
response = self._request(
437-
"POST", "files/upload", headers=headers, files=files, data=data
438-
)
439-
return response.json()
440-
441-
def upload_file_obj(
442-
self, file_obj: BinaryIO, filename: str, user: str
443-
) -> Dict[str, Any]:
444-
"""
445-
使用文件对象上传文件到Dify API。
446-
447-
Args:
448-
file_obj (BinaryIO): 文件对象
449-
filename (str): 文件名
450-
user (str): 用户标识
451-
452-
Returns:
453-
Dict[str, Any]: 上传文件的响应数据
454-
455-
Raises:
456-
requests.HTTPError: 当API请求失败时
457-
"""
458-
files = {"file": (filename, file_obj)}
459-
data = {"user": user}
460-
461-
headers = self._get_headers()
462-
# 移除Content-Type,让requests自动设置multipart/form-data
463-
headers.pop("Content-Type", None)
464-
465-
response = self._request(
466-
"POST", "files/upload", headers=headers, files=files, data=data
467-
)
468-
return response.json()
469-
470-
def get_app_info(self) -> Dict[str, Any]:
471-
"""
472-
获取应用基本信息。
473-
474-
Returns:
475-
Dict[str, Any]: 应用信息,包含名称、描述和标签
476-
477-
Raises:
478-
requests.HTTPError: 当API请求失败时
479-
"""
480-
return self.get("info")
481-
482-
def get_parameters(self) -> Dict[str, Any]:
483-
"""
484-
获取应用参数,包括功能开关、输入参数名称、类型及默认值等。
485-
486-
Returns:
487-
Dict[str, Any]: 应用参数配置
488-
489-
Raises:
490-
requests.HTTPError: 当API请求失败时
491-
"""
492-
return self.get("parameters")
493-
494371
def get_meta(self) -> Dict[str, Any]:
495372
"""
496373
获取应用Meta信息,用于获取工具icon等。

0 commit comments

Comments
 (0)