Skip to content

Commit 31d1dd3

Browse files
committed
add README
1 parent 1720b9e commit 31d1dd3

File tree

9 files changed

+53
-40
lines changed

9 files changed

+53
-40
lines changed

README.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
Pydify 是一个用于与 Dify API 交互的 Python 客户端库。
44

5+
[![PyPI version](https://badge.fury.io/py/pydify.svg)](https://badge.fury.io/py/pydify)
6+
[![Python Versions](https://img.shields.io/pypi/pyversions/pydify.svg)](https://pypi.org/project/pydify)
7+
[![Downloads](https://pepy.tech/badge/pydify)](https://pepy.tech/project/pydify)
8+
59
## 关于 Dify
610

711
[Dify](https://github.com/langgenius/dify) 是一个开源的 LLM 应用开发平台,提供直观的界面将 AI 工作流、RAG 管道、代理能力、模型管理、可观察性功能等结合在一起,使您能够快速从原型转向生产环境。

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/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
from .agent import AgentClient
99
from .chatbot import ChatbotClient
1010
from .chatflow import ChatflowClient
11+
from .common import DifyBaseClient, DifyType
1112
from .text_generation import TextGenerationClient
1213
from .workflow import WorkflowClient
13-
from .common import DifyType, DifyBaseClient
14+
1415

1516
def create_client(type: str, base_url: str, api_key: str) -> DifyBaseClient:
1617
if type == DifyType.Workflow:

pydify/agent.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,8 @@ class AgentClient(DifyBaseClient):
1818
1919
提供与Dify Agent应用API交互的方法,包括发送消息、获取历史消息、管理会话、
2020
上传文件、语音转文字、文字转语音等功能。Agent应用支持迭代式规划推理和自主工具调用。
21-
"""
21+
"""
22+
2223
type = DifyType.Agent
2324

2425
def send_message(
@@ -72,7 +73,7 @@ def send_message(
7273
endpoint = "chat-messages"
7374

7475
return self.post_stream(endpoint, json_data=payload, **kwargs) # 传递额外参数
75-
76+
7677
def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
7778
"""
7879
停止正在进行的响应流。此方法仅在流式模式下有效。
@@ -95,8 +96,6 @@ def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
9596
payload = {"user": user}
9697
return self.post(endpoint, json_data=payload)
9798

98-
99-
10099
def get_meta(self) -> Dict[str, Any]:
101100
"""
102101
获取应用Meta信息,用于获取工具icon等。

pydify/chatbot.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,9 @@ class ChatbotClient(DifyBaseClient):
1818
提供与Dify Chatbot应用API交互的方法,包括发送消息、获取历史消息、管理会话、
1919
上传文件、语音转文字、文字转语音等功能。
2020
"""
21+
2122
type = DifyType.Chatbot
23+
2224
def send_message(
2325
self,
2426
query: str,
@@ -81,7 +83,7 @@ def send_message(
8183
return self.post_stream(endpoint, json_data=payload, **kwargs)
8284
else:
8385
return self.post(endpoint, json_data=payload, **kwargs)
84-
86+
8587
def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
8688
"""
8789
停止正在进行的响应,仅支持流式模式。

pydify/chatflow.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,9 @@ class ChatflowClient(DifyBaseClient):
1919
提供与Dify Chatflow应用API交互的方法,包括发送消息、获取历史消息、管理会话、
2020
上传文件、语音转文字、文字转语音等功能。Chatflow应用基于工作流编排,适用于定义复杂流程的多轮对话场景。
2121
"""
22+
2223
type = DifyType.Chatflow
24+
2325
def send_message(
2426
self,
2527
query: str,
@@ -97,7 +99,9 @@ def stop_response(self, task_id: str, user: str) -> Dict[str, Any]:
9799
payload = {"user": user}
98100
return self.post(endpoint, json_data=payload)
99101

100-
def get_suggested_questions(self, message_id: str, user: str, **kwargs) -> Dict[str, Any]:
102+
def get_suggested_questions(
103+
self, message_id: str, user: str, **kwargs
104+
) -> Dict[str, Any]:
101105
"""
102106
获取下一轮建议问题列表。
103107

pydify/common.py

Lines changed: 21 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -26,35 +26,36 @@
2626

2727
class DifyType:
2828
"""Dify应用类型枚举
29-
29+
3030
Dify平台支持多种类型的应用,每种类型有不同的API端点和功能。
3131
此类定义了所有支持的应用类型常量,用于客户端类型标识。
3232
"""
33-
Workflow = 'workflow'
34-
Chatbot = 'chatbot'
35-
Chatflow = 'chatflow'
36-
Agent = 'agent'
37-
TextGeneration = 'text_generation'
38-
33+
34+
Workflow = "workflow"
35+
Chatbot = "chatbot"
36+
Chatflow = "chatflow"
37+
Agent = "agent"
38+
TextGeneration = "text_generation"
39+
3940

4041
class DifyBaseClient:
4142
"""Dify API 基础客户端类。
4243
4344
提供与Dify API进行交互的基本功能,包括身份验证、HTTP请求和通用方法。
4445
各种特定应用类型的客户端都继承自此类,以重用共同的功能。
45-
46+
4647
主要功能:
4748
- HTTP请求处理 (GET/POST/流式请求)
4849
- 错误处理和重试机制
4950
- 文件上传
5051
- 用户会话管理
5152
- 消息反馈功能
52-
53+
5354
子类应设置适当的type属性,并根据需要实现特定的API方法。
5455
"""
5556

5657
type = None
57-
58+
5859
def __init__(self, api_key: str, base_url: str = None):
5960
"""
6061
初始化Dify API客户端。
@@ -65,13 +66,15 @@ def __init__(self, api_key: str, base_url: str = None):
6566
base_url (str, optional): API基础URL。如果未提供,则使用默认的Dify API地址。
6667
可以设置为自托管Dify实例的URL。
6768
也可以通过DIFY_BASE_URL环境变量设置。
68-
69+
6970
注意:
7071
- API密钥应当保密,不要在客户端代码中硬编码
7172
- 对于自托管实例,确保base_url格式正确,通常以/v1结尾
7273
"""
7374
self.api_key = api_key
74-
self.base_url = base_url or os.environ.get("DIFY_BASE_URL") or "https://api.dify.ai/v1"
75+
self.base_url = (
76+
base_url or os.environ.get("DIFY_BASE_URL") or "https://api.dify.ai/v1"
77+
)
7578

7679
# 如果base_url不以斜杠结尾,则添加斜杠
7780
if not self.base_url.endswith("/"):
@@ -115,7 +118,7 @@ def _request(self, method: str, endpoint: str, **kwargs) -> requests.Response:
115118
- status_code: HTTP状态码
116119
- error_data: 服务器返回的错误数据
117120
- 常见错误包括认证错误(401)、参数错误(400)、资源不存在(404)等
118-
连接错误:
121+
连接错误:
119122
- 网络连接问题
120123
- SSL证书错误
121124
- 超时
@@ -227,12 +230,12 @@ def get(self, endpoint: str, **kwargs) -> Dict[str, Any]:
227230
228231
Raises:
229232
DifyAPIError: 当API请求失败时,包含详细的错误信息
230-
233+
231234
示例:
232235
```python
233236
# 获取应用信息
234237
app_info = client.get("app-info")
235-
238+
236239
# 带参数的请求
237240
messages = client.get("messages", params={"conversation_id": "conv_123", "limit": 10})
238241
```
@@ -272,7 +275,7 @@ def post(
272275
273276
Raises:
274277
DifyAPIError: 当API请求失败时,包含详细的错误信息
275-
278+
276279
示例:
277280
```python
278281
# 发送消息
@@ -317,7 +320,7 @@ def post_stream(
317320
Raises:
318321
DifyAPIError: 当API请求失败时
319322
网络错误: 连接问题、超时等
320-
323+
321324
示例:
322325
```python
323326
# 流式生成文本
@@ -326,7 +329,7 @@ def post_stream(
326329
"user": "user_123",
327330
"response_mode": "streaming"
328331
})
329-
332+
330333
# 处理每个事件块
331334
for chunk in stream:
332335
if "answer" in chunk:

pydify/text_generation.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,8 @@ class TextGenerationClient(DifyBaseClient):
1818
上传文件、文字转语音等功能。Text Generation应用无会话支持,
1919
适合用于翻译、文章写作、总结等AI任务。
2020
"""
21+
2122
type = DifyType.TextGeneration
22-
2323

2424
def completion(
2525
self,

pydify/workflow.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -16,9 +16,9 @@ class WorkflowClient(DifyBaseClient):
1616
1717
提供与Dify Workflow应用API交互的方法,包括执行工作流、停止响应、上传文件和获取日志等功能。
1818
"""
19-
19+
2020
type = DifyType.Workflow
21-
21+
2222
def run(
2323
self,
2424
inputs: Dict[str, Any],
@@ -29,24 +29,24 @@ def run(
2929
) -> Union[Dict[str, Any], Generator[Dict[str, Any], None, None]]:
3030
"""
3131
执行工作流。
32-
32+
3333
Args:
3434
inputs (Dict[str, Any]): 必需参数。包含工作流所需的输入变量键值对。
3535
每个键对应一个工作流定义中的变量名称,值为该变量的具体内容。
36-
36+
3737
注意:根据API版本的不同,Dify API可能期望不同的参数格式:
3838
- 有些API版本要求使用 "inputs" 作为键
3939
- 有些API版本要求使用 "input" 作为键
4040
- 有些API版本期望直接提供扁平的输入结构
41-
41+
4242
常见输入示例:
4343
```
4444
# 简单文本输入
4545
inputs = {
4646
"prompt": "请给我写一首诗",
4747
"topic": "人工智能"
4848
}
49-
49+
5050
# 包含更复杂结构的输入
5151
inputs = {
5252
"text_to_analyze": "这是一段需要分析的文本",
@@ -57,14 +57,14 @@ def run(
5757
}
5858
}
5959
```
60-
60+
6161
user (str): 用户标识,用于跟踪和区分不同用户的请求
62-
62+
6363
response_mode (str, optional): 响应模式:
6464
- 'streaming'(流式): 实时获取工作流执行过程和结果,适合长时间运行的任务
6565
- 'blocking'(阻塞): 等待工作流完全执行完毕后返回结果,适合简短任务
6666
默认为'streaming'。
67-
67+
6868
files (List[Dict[str, Any]], optional): 文件列表,每个文件为一个字典,包含以下字段:
6969
- type (str): 文件类型,支持:
7070
- document: 支持'TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS',
@@ -78,7 +78,7 @@ def run(
7878
- 'local_file': 使用之前通过upload_file上传的文件ID
7979
- url (str): 文件的URL地址(仅当transfer_method为'remote_url'时需要)
8080
- upload_file_id (str): 上传文件ID(仅当transfer_method为'local_file'时需要)
81-
81+
8282
示例:
8383
```
8484
[
@@ -94,7 +94,7 @@ def run(
9494
}
9595
]
9696
```
97-
97+
9898
**kwargs: 额外的请求参数:
9999
- timeout (int): 请求超时时间(秒),默认为30秒
100100
- max_retries (int): 网络错误时的最大重试次数,默认为2次
@@ -103,7 +103,7 @@ def run(
103103
Union[Dict[str, Any], Generator[Dict[str, Any], None, None]]:
104104
如果response_mode为'blocking',返回完整响应字典,包含工作流执行结果;
105105
如果response_mode为'streaming',返回一个字典生成器,实时提供工作流执行状态。
106-
106+
107107
阻塞模式返回示例:
108108
```
109109
{
@@ -117,7 +117,7 @@ def run(
117117
"ended_at": 1617979575
118118
}
119119
```
120-
120+
121121
流式模式返回的每个事件示例:
122122
```
123123
{

0 commit comments

Comments
 (0)