GITBOOK-25: change request with no subject merged in GitBook

pull/25/head
zorroj 2023-11-08 14:13:47 +00:00 committed by gitbook-bot
parent f0396310a3
commit 280e7cea93
No known key found for this signature in database
GPG Key ID: 07D2180C7B12D0FF
4 changed files with 236 additions and 64 deletions

View File

@ -54,7 +54,7 @@
* [接入 OpenLLM 部署的本地模型](advanced/model-configuration/openllm.md)
* [接入 LocalAI 部署的本地模型](advanced/model-configuration/localai.md)
* [更多集成](advanced/more-integration.md)
* [扩展](advanced/extension/README.md)
* [扩展外部能力](advanced/extension/README.md)
* [API 扩展](advanced/extension/api\_based\_extension/README.md)
* [外部数据工具](advanced/extension/api\_based\_extension/external\_data\_tool.md)
* [敏感内容审查](advanced/extension/api\_based\_extension/moderation.md)

View File

@ -5,11 +5,11 @@
* 新增一种新的外部数据工具类型 [external\_data\_tool.md](external\_data\_tool.md "mention")
* 扩展敏感内容审查策略 [moderation.md](moderation.md "mention")
可在上述功能的基础上,遵循代码层 interface 的规范,来实现横向扩展的目的。
可在上述功能的基础上,遵循代码层 interface 的规范,来实现横向扩展的目的。如果你愿意将扩展功能贡献给我们的话,非常欢迎给 Dify 提交 PR。
### schema.json 规范定义
## 前端组件规范定义
Code-based Extension 前端样式通过 `schema.json` 定义,以下是定义规范。
代码扩展的前端样式通过 `schema.json` 定义:
* label自定义类型名称支持系统语言切换
* form\_schema表单内容列表
@ -26,3 +26,73 @@ Code-based Extension 前端样式通过 `schema.json` 定义,以下是定义
* label下拉名称支持系统语言切换
* value下拉选项值
* max\_length组件「text-input」专有属性最大长度
### 模版样例
```json
{
"label": {
"en-US": "Cloud Service",
"zh-Hans": "云服务"
},
"form_schema": [
{
"type": "select",
"label": {
"en-US": "Cloud Provider",
"zh-Hans": "云厂商"
},
"variable": "cloud_provider",
"required": true,
"options": [
{
"label": {
"en-US": "AWS",
"zh-Hans": "亚马逊"
},
"value": "AWS"
},
{
"label": {
"en-US": "Google Cloud",
"zh-Hans": "谷歌云"
},
"value": "GoogleCloud"
},
{
"label": {
"en-US": "Azure Cloud",
"zh-Hans": "微软云"
},
"value": "Azure"
}
],
"default": "GoogleCloud",
"placeholder": ""
},
{
"type": "text-input",
"label": {
"en-US": "API Endpoint",
"zh-Hans": "API Endpoint"
},
"variable": "api_endpoint",
"required": true,
"max_length": 100,
"default": "",
"placeholder": "https://api.example.com"
},
{
"type": "paragraph",
"label": {
"en-US": "API Key",
"zh-Hans": "API Key"
},
"variable": "api_keys",
"required": true,
"default": "",
"placeholder": "Paste your API key here"
}
]
}
```

View File

@ -4,34 +4,78 @@
而对于本地部署 Dify 的开发者,为了满足更加定制化的需求,或者不希望额外开发一个 API Server可以直接在 Dify 服务的基础上,以插件的形式插入定制的外部数据工具实现逻辑。扩展自定义工具后,将会在工具类型的下拉列表中增加您的自定义工具选项,团队成员即可使用自定义的工具来获取外部数据。
## 如何开发扩展
## 快速开始
开发新的外部数据工具需要准备下面几个文件
这里以一个 `天气查询` 外部数据工具扩展为例,步骤如下
* `{your_tool_name}.py` 工具扩展实现代码
1. 初始化目录
2. 添加前端表单规范
3. 添加实现类
4. 预览前端界面
5. 调试扩展
*   `your_tool_name` 为您定义的工具唯一标识,唯一标识不可与其他工具重复,建议以 `custom_` 为开头,目录结构示例如下:
### 1. **初始化目录**
新增自定义类型 `Weather Search` ,需要在 `api/core/external_data_tool` 目录下新建相关的目录和文件。
```python
.
└── api
└── core
└── external_data_tool
└── weather_search
├── __init__.py
├── weather_search.py
└── schema.json
```
```Python
.
└── external_data_tool
└── custom_db_search
├── custom_db_search.py
└── schema.json
```
### 2. **添加前端组件规范**
PS. Python 文件名称必须与文件夹名称保持一致。
* `schema.json` 前端表单结构规范
* `schema.json`,这里定义了前端组件规范,详细见 [.](./ "mention")
```json
{
"label": {
"en-US": "Weather Search",
"zh-Hans": "天气查询"
},
"form_schema": [
{
"type": "select",
"label": {
"en-US": "Temperature Unit",
"zh-Hans": "温度单位"
},
"variable": "temperature_unit",
"required": true,
"options": [
{
"label": {
"en-US": "Fahrenheit",
"zh-Hans": "华氏度"
},
"value": "fahrenheit"
},
{
"label": {
"en-US": "Centigrade",
"zh-Hans": "摄氏度"
},
"value": "centigrade"
}
],
"default": "centigrade",
"placeholder": "Please select temperature unit"
}
]
}
```
### 3. 添加实现类
<figure><img src="../../../.gitbook/assets/红框.png" alt=""><figcaption><p>Front-end Form Structure</p></figcaption></figure>
`weather_search.py` 代码模版,你可以在这里实现具体的业务逻辑。
红框上的为固定表单项,红框中的表单项可在 schema.json 中的 form\_schema 自定义,规范见:[.](./ "mention")
### 实现代码
> 注意:类变量 name 为自定义类型名称,需要跟目录和文件名保持一致,而且唯一。
```python
from typing import Optional
@ -39,20 +83,30 @@ from typing import Optional
from core.external_data_tool.base import ExternalDataTool
class YourToolNameTool(ExternalDataTool):
name: str = "{your_tool_name}"
class WeatherSearch(ExternalDataTool):
"""
The name of custom type must be unique, keep the same with directory and file name.
"""
name: str = "weather_search"
@classmethod
def validate_config(cls, tenant_id: str, config: dict) -> None:
"""
Validate the incoming form config data.
schema.json validation. It will be called when user save the config.
Example:
.. code-block:: python
config = {
"temperature_unit": "centigrade"
}
:param tenant_id: the id of workspace
:param config: the form config data
:param config: the variables of form config
:return:
"""
# implement your own validate logic here
if not config.get('temperature_unit'):
raise ValueError('temperature unit is required')
def query(self, inputs: dict, query: Optional[str] = None) -> str:
"""
@ -62,24 +116,76 @@ class YourToolNameTool(ExternalDataTool):
:param query: the query of chat app
:return: the tool query result
"""
# TODO implement your own query logic here
return ''
city = inputs.get('city')
temperature_unit = self.config.get('temperature_unit')
if temperature_unit == 'fahrenheit':
return f'Weather in {city} is 32°F'
else:
return f'Weather in {city} is 0°C'
```
代码需要放置在 `api/core/external_data_tool`中,目录结构如下:
### 4. **预览前端界面**
按照上面步骤执行,运行服务即可见新增的自定义类型。
<figure><img src="https://langgenius.feishu.cn/space/api/box/stream/download/asynccode/?code=NDZkOTBjNjJmZDdkNTdkYTkxMDllNTgzMzA1MjE2MzBfM0FYYjFtWkE1bHVPdWdYQ0ZkNWNRdXBXbmhoMklkVW9fVG9rZW46SnZSVWIyN3Nkb09pZkV4NDZyM2NIckJtbnhnXzE2OTk0NTE5NjM6MTY5OTQ1NTU2M19WNA" alt=""><figcaption><p>Add Tool</p></figcaption></figure>
### 5. **调试扩展**
至此,即可在 Dify 应用编排界面选择自定义的 `Weather Search` 外部数据工具扩展类型进行调试。
## 实现类模版
```python
.
└── api
└── core
└── external_data_tool
├── base.py
├── external_data_tool_factory.py
├── api
│ ├── api.py
│ └── schema.json
├── {your_tool_name}
│ ├── {your_tool_name}.py
│ └── schema.json
from typing import Optional
from core.external_data_tool.base import ExternalDataTool
class WeatherSearch(ExternalDataTool):
"""
The name of custom type must be unique, keep the same with directory and file name.
"""
name: str = "weather_search"
@classmethod
def validate_config(cls, tenant_id: str, config: dict) -> None:
"""
schema.json validation. It will be called when user save the config.
:param tenant_id: the id of workspace
:param config: the variables of form config
:return:
"""
# implement your own logic here
def query(self, inputs: dict, query: Optional[str] = None) -> str:
"""
Query the external data tool.
:param inputs: user inputs
:param query: the query of chat app
:return: the tool query result
"""
# implement your own logic here
return "your own data."
```
### 实现类开发详细介绍
### def validate\_config
`schema.json` 表单校验方法,当用户点击「发布」保存配置时调用
* `config` 表单参数
* `{{variable}}` 表单自定义变量
### def query
用户自定义数据查询实现,返回的结果将会被替换到指定的变量。
* `inputs` :终端用户传入变量值
* `query` :终端用户当前对话输入内容,对话型应用固定参数。

View File

@ -1,12 +1,10 @@
# 敏感内容审查
## **内容审查扩展**
除了系统内置的内容审查类型Dify 也支持用户扩展自定义实现,该方法适用于私有部署的用户定制开发,如果您愿意将扩展功能贡献给我们的话,非常欢迎给 Dify 提交 PR。
除了系统内置的内容审查类型Dify 也支持用户扩展自定义的内容审查规则,该方法适用于私有部署的开发者定制开发。比如企业内部客服,规定用户在查询的时候以及客服回复的时候,除了不可以输入暴力,性和非法行为等相关词语,也不能出现企业自己规定的禁词或违反内部制定的审查逻辑,那么开发者可以在私有部署的 Dify 代码层扩展自定义内容审查规则。
## 快速开始
这里以一个 `Cloud Service` 内容审查扩展为例:大致步骤如下:
这里以一个 `Cloud Service` 内容审查扩展为例步骤如下:
1. 初始化目录
2. 添加前端组件定义文件
@ -14,9 +12,7 @@
4. 预览前端界面
5. 调试扩展
1. ### 初始化目录
### 1. 初始化目录
新增自定义类型 `Cloud Service`,需要在 `api/core/moderation` 目录下新建相关的目录和文件。
@ -31,11 +27,11 @@
└── schema.json
```
2. ### 添加前端组件规范
### 2.添加前端组件规范
* `schema.json`,这里定义了前端组件规范,详细见 [.](./ "mention")
* `schema.json`,这里定义了前端组件规范,详细见 [.](./ "mention")
```JSON
```json
{
"label": {
"en-US": "Cloud Service",
@ -103,13 +99,15 @@
}
```
3. ### 添加实现类
### 3. 添加实现类
`cloud_service.py` 代码模版,你可以在这里实现具体的业务逻辑。
> 注意:类变量 name 为自定义类型名称,需要跟目录和文件名保持一致,而且唯一。
{% hint style="warning" %}
注意:类变量 name 为自定义类型名称,需要跟目录和文件名保持一致,而且唯一。
{% endhint %}
```Python
```python
from core.moderation.base import Moderation, ModerationAction, ModerationInputsResult, ModerationOutputsResult
class CloudServiceModeration(Moderation):
@ -204,22 +202,20 @@ class CloudServiceModeration(Moderation):
return False
```
4. ### 预览前端界面
### 4. 预览前端界面
按照上面步骤执行,运行服务即可见新增的自定义类型。
5. ### 调试扩展
<figure><img src="https://langgenius.feishu.cn/space/api/box/stream/download/asynccode/?code=ZmRiMDI5YTU3NGY5M2JmNmY0N2Y0NmEwMGIwNGI0N2VfOGRrVE5GV25BT3laRnVxYlhLMUFYRWZWbm9NVkp3YXJfVG9rZW46Q1JPS2I3bFU0b0NQY2l4YVlhUGNVSTNNblJkXzE2OTk0NTExMTc6MTY5OTQ1NDcxN19WNA" alt=""><figcaption><p>Cloud Service</p></figcaption></figure>
### 5. 调试扩展
至此,即可在 Dify 应用编排界面选择自定义的 `Cloud Service` 内容审查扩展类型进行调试。\
## 前端组件规范
* 请参考 [.](./ "mention")
## 实现类模版
```Python
```python
from core.moderation.base import Moderation, ModerationAction, ModerationInputsResult, ModerationOutputsResult
class CloudServiceModeration(Moderation):
@ -316,6 +312,6 @@ class CloudServiceModeration(Moderation):
* `direct_output`直接输出预设回复
* `overrided`覆写传入变量值
* `preset_response` 预设回复(仅当 action=direct\_output 返回)
* `text` 覆写的 LLM 回答内容(仅当 action=overrided 返回)
* `text` 覆写的 LLM 回答内容(仅当 action=overrided 返回)
\