Commit 92e69588 by Archer Committed by GitHub

perf: workflow v1 abort check (#6945)

* perf: workflow v1 abort check

* fix: avoid direct llms type deps

* pro

* fix: cast remark include through unknown

* fix: handle client reset abort ordering
parent 82852fad
......@@ -12,7 +12,7 @@ import { SidebarScrollFix } from '@/components/sidebarScrollFix';
import { CategorySwitcher } from '@/components/docs/categorySwitcher';
import { LanguageSwitcher } from '@/components/docs/languageSwitcher';
import { normalizePageTreeSections } from '@/lib/page-tree';
import { BookOpen, Code, Lightbulb, CircleHelp, Server } from 'lucide-react';
import { BookOpen, Code, CircleHelp, Handshake, Server } from 'lucide-react';
export default async function Layout({
params,
......@@ -31,11 +31,6 @@ export default async function Layout({
url: getLocalizedPath('/guide', lang)
},
{
icon: <Lightbulb className={iconClass} />,
title: t('common:use-cases', lang),
url: getLocalizedPath('/use-cases', lang)
},
{
icon: <Server className={iconClass} />,
title: t('common:selfHost', lang),
url: getLocalizedPath('/self-host', lang)
......@@ -49,6 +44,11 @@ export default async function Layout({
icon: <CircleHelp className={iconClass} />,
title: t('common:faq', lang),
url: getLocalizedPath('/faq', lang)
},
{
icon: <Handshake className={iconClass} />,
title: t('common:businessConsultation', lang),
url: 'https://fael3z0zfze.feishu.cn/share/base/form/shrcnjJWtKqjOI9NbQTzhNyzljc'
}
];
......
......@@ -10,10 +10,12 @@ import { i18n } from '@/lib/i18n';
export const revalidate = false;
const includeMdxFiles = remarkInclude as unknown as typeof remarkMdx;
const processor = remark()
.use(remarkMdx)
// https://fumadocs.vercel.app/docs/mdx/include
.use(remarkInclude)
.use(includeMdxFiles)
// gfm styles
.use(remarkGfm)
// .use(your remark plugins)
......
......@@ -79,6 +79,23 @@ export function SwitcherDropdown({
);
if (item.href) {
if (/^https?:\/\//i.test(item.href)) {
return (
<a
key={item.key}
href={item.href}
target="_blank"
rel="noreferrer noopener"
onClick={() => selectItem(item)}
className={className}
role="option"
aria-selected={active}
>
{content}
</a>
);
}
return (
<Link
key={item.key}
......
......@@ -28,7 +28,3 @@ When the user asks "What is the second point?", the system searches the Knowledg
Calls an AI model to complete and refine the user's current question. It primarily resolves coreferences (pronouns and vague references), making search queries more complete and reliable. This improves Knowledge Base search accuracy in multi-turn conversations.
The main challenge is that the model may not have a clear understanding of "completion" and often struggles to determine how to properly refine queries with long context.
## Examples
- [Integrate Google Search](../../../../use-cases/app-cases/google_search.en.mdx)
......@@ -19,17 +19,12 @@ description: 问题优化模块介绍和使用
![](/imgs/coreferenceResolution2.webp)
用户在提问“第二点是什么”的时候,只会去知识库里查找“第二点是什么”,压根查不到内容。实际上需要查询的是“QA结构是什么”。因此我们需要引入一个【问题优化】模块,来对用户当前的问题进行补全,从而使得知识库搜索能够搜索到合适的内容。使用补全后效果如下:
用户在提问“第二点是什么”的时候,只会去知识库里查找“第二点是什么”,压根查不到内容。实际上需要查询的是“QA 结构是什么”。因此我们需要引入一个【问题优化】模块,来对用户当前的问题进行补全,从而使得知识库搜索能够搜索到合适的内容。使用补全后效果如下:
![](/imgs/coreferenceResolution3.webp)
## 功能
调用 AI 去对用户当前的问题进行补全。目前主要是补全“指代”词,使得检索词更加的完善可靠,从而增强上下文连续对话的知识库搜索能力。
遇到最大的难题在于:模型对于【补全】的概念可能不清晰,且对于长上下文往往无法准确的知道应该如何补全。
## 示例
- [接入谷歌搜索](../../../../use-cases/app-cases/google_search.mdx)
......@@ -45,9 +45,9 @@ Usage is the same as Postman and ApiFox.
Use `{{key}}` to reference variables. For example:
| key | value |
| --- | --- |
| appId | `{{appId}}` |
| key | value |
| ------------- | ------------------ |
| appId | `{{appId}}` |
| Authorization | Bearer `{{token}}` |
### Body
......@@ -59,7 +59,6 @@ Write a custom JSON body and use `{{key}}` to reference variables. For example:
<Tabs items={['Sample variables','Body declaration in HTTP node','Final parsed result']}>
<Tab value="Sample variables" >
```json
{
"string": "字符串",
......@@ -73,11 +72,9 @@ Write a custom JSON body and use `{{key}}` to reference variables. For example:
}
```
</Tab>
<Tab value="Body declaration in HTTP node" >
When referencing a `string` in the Body, wrap it in quotes: `"{{string}}"`.
```json
......@@ -92,11 +89,9 @@ When referencing a `string` in the Body, wrap it in quotes: `"{{string}}"`.
}
```
</Tab>
<Tab value="Final parsed result" >
```json
{
"string": "字符串",
......@@ -112,7 +107,6 @@ When referencing a `string` in the Body, wrap it in quotes: `"{{string}}"`.
}
```
</Tab>
</Tabs>
......@@ -125,54 +119,49 @@ Syntax reference: https://github.com/JSONPath-Plus/JSONPath?tab=readme-ov-file
<Tabs items={['API response example','Extraction example']}>
<Tab value="API response example" >
```json
{
"message": "测试",
"data":{
"user": {
"data": {
"user": {
"name": "xxx",
"age": 12
},
"list": [
{
"name": "xxx",
"age": 12
"age": 50
},
"list": [
{
"name": "xxx",
"age": 50
},
[{ "test": 22 }]
],
"psw": "xxx"
[{ "test": 22 }]
],
"psw": "xxx"
}
}
```
</Tab>
<Tab value="Extraction example" >
```json
{
"$.message": "测试",
"$.data.user": { "name": "xxx", "age": 12 },
"$.data.user.name": "xxx",
"$.data.user.age": 12,
"$.data.list": [ { "name": "xxx", "age": 50 }, [{ "test": 22 }] ],
"$.data.list": [{ "name": "xxx", "age": 50 }, [{ "test": 22 }]],
"$.data.list[0]": { "name": "xxx", "age": 50 },
"$.data.list[0].name": "xxx",
"$.data.list[0].age": 50,
"$.data.list[1]": [ { "test": 22 } ],
"$.data.list[1]": [{ "test": 22 }],
"$.data.list[1][0]": { "test": 22 },
"$.data.list[1][0].test": 22,
"$.data.psw": "xxx"
}
```
</Tab>
</Tabs>
Configure the `key` to extract values from FastGPT's parsed format, following standard JavaScript object access rules. For example:
1. To get the `message` content, set the `key` to `message`.
......@@ -183,55 +172,53 @@ Configure the `key` to extract values from FastGPT's parsed format, following st
Starting from FastGPT v4.6.8, output formatting was added, primarily converting `JSON` to `string`. If you select `string` as the output type, the HTTP node will convert the corresponding key's value to a JSON string. This lets you pipe HTTP output directly into a `Text Processing` node, append appropriate prompts, and feed the result into `AI Chat`.
<Alert context="warning">
The HTTP node is extremely versatile. You can integrate public APIs to extend your workflow capabilities.
If you don't want to deploy additional services, use [Laf](https://laf.dev/) to quickly develop and publish APIs -- write and ship instantly with no deployment needed.
</Alert>
## Laf HTTP Integration Example
Here is a POST request example written in Laf:
```ts
import cloud from '@lafjs/cloud'
const db = cloud.database()
import cloud from '@lafjs/cloud';
const db = cloud.database();
type RequestType = {
appId: string;
appointment: string;
action: 'post' | 'delete' | 'put' | 'get'
}
action: 'post' | 'delete' | 'put' | 'get';
};
export default async function (ctx: FunctionContext) {
try {
// Get parameters from body
const { appId, appointment, action } = ctx.body as RequestType
const { appId, appointment, action } = ctx.body as RequestType;
const parseBody = JSON.parse(appointment)
const parseBody = JSON.parse(appointment);
if (action === 'get') {
return await getRecord(parseBody)
return await getRecord(parseBody);
}
if (action === 'post') {
return await createRecord(parseBody)
return await createRecord(parseBody);
}
if (action === 'put') {
return await putRecord(parseBody)
return await putRecord(parseBody);
}
if (action === 'delete') {
return await removeRecord(parseBody)
return await removeRecord(parseBody);
}
return {
response: "Error"
}
response: 'Error'
};
} catch (err) {
return {
response: "Error"
}
response: 'Error'
};
}
}
```
......@@ -239,15 +226,9 @@ export default async function (ctx: FunctionContext) {
## Use Cases
The HTTP node enables unlimited extensibility, such as:
- Database operations
- External data source calls
- Web searches
- Sending emails
- ....
## Related Examples
- [Google Search](../../../../use-cases/app-cases/google_search.en.mdx)
- [Send Lark Webhook](../../../../use-cases/app-cases/feishu_webhook.en.mdx)
- [Lab Appointment (Database Operations)](../../../../use-cases/app-cases/lab_appointment.en.mdx)
......@@ -18,48 +18,47 @@ import { Alert } from '@/components/docs/Alert';
HTTP 模块会向对应的地址发送一个 `HTTP` 请求,实际操作与 Postman 和 ApiFox 这类直流工具使用差不多。
- Params 为路径请求参数,GET请求中用的居多。
- Body 为请求体,POST/PUT请求中用的居多。
- Headers 为请求头,用于传递一些特殊的信息。
- Params 为路径请求参数,GET 请求中用的居多。
- Body 为请求体,POST/PUT 请求中用的居多。
- Headers 为请求头,用于传递一些特殊的信息。
- 自定义变量中可以接收前方节点的输出作为变量
- 3 种数据中均可以通过 `{{}}` 来引用变量。
- url 也可以通过 `{{}}` 来引用变量。
- 变量来自于`全局变量`、`系统变量`、`前方节点输出`
- URL 也可以通过 `{{}}` 来引用变量。
- 变量来自于 `全局变量`、`系统变量`、`前方节点输出`
## 参数结构
### 系统变量说明
你可以将鼠标放置在`请求参数`旁边的问号中,里面会提示你可用的变量。
你可以将鼠标放置在 `请求参数` 旁边的问号中,里面会提示你可用的变量。
- appId: 应用的ID
- chatId: 当前对话的ID,测试模式下不存在。
- responseChatItemId: 当前对话中,响应的消息ID,测试模式下不存在。
- appId: 应用的 ID
- chatId: 当前对话的 ID,测试模式下不存在。
- responseChatItemId: 当前对话中,响应的消息 ID,测试模式下不存在。
- variables: 当前对话的全局变量。
- cTime: 当前时间。
- histories: 历史记录(默认最多取10条,无法修改长度)
- histories: 历史记录(默认最多取 10 条,无法修改长度)
### Params, Headers
不多描述,使用方法和Postman, ApiFox 基本一致。
不多描述,使用方法和 Postman, ApiFox 基本一致。
可通过 `{{key}}` 来引入变量。例如:
| key | value |
| --- | --- |
| appId | `{{appId}}` |
| key | value |
| ------------- | ------------------ |
| appId | `{{appId}}` |
| Authorization | Bearer `{{token}}` |
### Body
只有特定请求类型下会生效。
可以写一个`自定义的 Json`,并通过 `{{key}}` 来引入变量。例如:
可以写一个 `自定义的 Json`,并通过 `{{key}}` 来引入变量。例如:
<Tabs items={['假设有一组变量','Http 模块中的Body声明','最终得到的解析']}>
<Tab value="假设有一组变量" >
```json
{
"string": "字符串",
......@@ -73,12 +72,10 @@ HTTP 模块会向对应的地址发送一个 `HTTP` 请求,实际操作与 Pos
}
```
</Tab>
<Tab value="Http 模块中的Body声明" >
注意,在 Body 中,你如果引用`字符串`,则需要加上`""`,例如:`"{{string}}"`。
注意,在 Body 中,你如果引用 `字符串`,则需要加上 `""`,例如:`"{{string}}"`。
```json
{
......@@ -92,11 +89,9 @@ HTTP 模块会向对应的地址发送一个 `HTTP` 请求,实际操作与 Pos
}
```
</Tab>
<Tab value="最终得到的解析" >
```json
{
"string": "字符串",
......@@ -112,126 +107,118 @@ HTTP 模块会向对应的地址发送一个 `HTTP` 请求,实际操作与 Pos
}
```
</Tab>
</Tabs>
### 如何获取返回值
从图中可以看出,FastGPT可以添加多个返回值,这个返回值并不代表接口的返回值,而是代表`如何解析接口返回值`,可以通过 `JSON path` 的语法,来`提取`接口响应的值。
从图中可以看出,FastGPT 可以添加多个返回值,这个返回值并不代表接口的返回值,而是代表 `如何解析接口返回值`,可以通过 `JSON path` 的语法,来 `提取` 接口响应的值。
语法可以参考: https://github.com/JSONPath-Plus/JSONPath?tab=readme-ov-file
<Tabs items={['接口响应示例','提取示例']}>
<Tab value="接口响应示例" >
```json
{
"message": "测试",
"data":{
"user": {
"data": {
"user": {
"name": "xxx",
"age": 12
},
"list": [
{
"name": "xxx",
"age": 12
"age": 50
},
"list": [
{
"name": "xxx",
"age": 50
},
[{ "test": 22 }]
],
"psw": "xxx"
[{ "test": 22 }]
],
"psw": "xxx"
}
}
```
</Tab>
<Tab value="提取示例" >
```json
{
"$.message": "测试",
"$.data.user": { "name": "xxx", "age": 12 },
"$.data.user.name": "xxx",
"$.data.user.age": 12,
"$.data.list": [ { "name": "xxx", "age": 50 }, [{ "test": 22 }] ],
"$.data.list": [{ "name": "xxx", "age": 50 }, [{ "test": 22 }]],
"$.data.list[0]": { "name": "xxx", "age": 50 },
"$.data.list[0].name": "xxx",
"$.data.list[0].age": 50,
"$.data.list[1]": [ { "test": 22 } ],
"$.data.list[1]": [{ "test": 22 }],
"$.data.list[1][0]": { "test": 22 },
"$.data.list[1][0].test": 22,
"$.data.psw": "xxx"
}
```
</Tab>
</Tabs>
你可以配置对应的 `key` 来从 `FastGPT 转化后的格式` 获取需要的值,该规则遵守 JS 的对象取值规则。例如:
你可以配置对应的`key`来从`FastGPT 转化后的格式`获取需要的值,该规则遵守 JS 的对象取值规则。例如:
1. 获取`message`的内容,那么你可以配置`message`的`key`为`message`,这样就可以获取到`message`的内容。
2. 获取`user的name`,则`key`可以为:`data.user.name`。
3. 获取list中第二个元素,则`key`可以为:`data.list[1]`,然后输出类型选择字符串,则获自动获取到`[ { "test": 22 } ]`的`json`字符串。
1. 获取 `message` 的内容,那么你可以配置 `message` 的 `key` 为 `message`,这样就可以获取到 `message` 的内容。
2. 获取 `user的name`,则 `key` 可以为:`data.user.name`。
3. 获取 list 中第二个元素,则 `key` 可以为:`data.list[1]`,然后输出类型选择字符串,则获自动获取到 `[ { "test": 22 } ]` 的 `json` 字符串。
### 自动格式化输出
FastGPT v4.6.8 后,加入了出参格式化功能,主要以`json`格式化成`字符串`为主。如果你的输出类型选择了`字符串`,则会将`HTTP`对应`key`的值,转成`json`字符串进行输出。因此,未来你可以直接从`HTTP`接口输出内容至`文本加工`中,然后拼接适当的提示词,最终输入给`AI对话`。
FastGPT v4.6.8 后,加入了出参格式化功能,主要以 `json` 格式化成 `字符串` 为主。如果你的输出类型选择了 `字符串`,则会将 `HTTP` 对应 `key` 的值,转成 `json` 字符串进行输出。因此,未来你可以直接从 `HTTP` 接口输出内容至 `文本加工` 中,然后拼接适当的提示词,最终输入给 `AI对话`。
<Alert context="warning">
HTTP模块非常强大,你可以对接一些公开的API,来提高编排的功能。
HTTP 模块非常强大,你可以对接一些公开的 API,来提高编排的功能。
如果你不想额外部署服务,可以使用 [Laf](https://laf.dev/) 来快速开发上线接口,即写即发,无需部署。
</Alert>
## laf 对接 HTTP 示例
下面是在 Laf 编写的 POST 请求示例:
```ts
import cloud from '@lafjs/cloud'
const db = cloud.database()
import cloud from '@lafjs/cloud';
const db = cloud.database();
type RequestType = {
appId: string;
appointment: string;
action: 'post' | 'delete' | 'put' | 'get'
}
action: 'post' | 'delete' | 'put' | 'get';
};
export default async function (ctx: FunctionContext) {
try {
// 从 body 中获取参数
const { appId, appointment, action } = ctx.body as RequestType
const { appId, appointment, action } = ctx.body as RequestType;
const parseBody = JSON.parse(appointment)
const parseBody = JSON.parse(appointment);
if (action === 'get') {
return await getRecord(parseBody)
return await getRecord(parseBody);
}
if (action === 'post') {
return await createRecord(parseBody)
return await createRecord(parseBody);
}
if (action === 'put') {
return await putRecord(parseBody)
return await putRecord(parseBody);
}
if (action === 'delete') {
return await removeRecord(parseBody)
return await removeRecord(parseBody);
}
return {
response: "异常"
}
response: '异常'
};
} catch (err) {
return {
response: "异常"
}
response: '异常'
};
}
}
```
......@@ -239,15 +226,9 @@ export default async function (ctx: FunctionContext) {
## 作用
通过 HTTP 模块你可以无限扩展,比如:
- 操作数据库
- 调用外部数据源
- 执行联网搜索
- 发送邮箱
- ....
## 相关示例
- [谷歌搜索](../../../../use-cases/app-cases/google_search.mdx)
- [发送飞书webhook](../../../../use-cases/app-cases/feishu_webhook.mdx)
- [实验室预约(操作数据库)](../../../../use-cases/app-cases/lab_appointment.mdx)
- ……
......@@ -21,7 +21,3 @@ In the example above, any input will have "The user's question is:" prepended to
## Use Cases
Provide custom-formatted text to any module, or preprocess system prompts for AI modules.
## Examples
- [Google Search Integration](../../../../use-cases/app-cases/google_search.en.mdx)
......@@ -12,17 +12,12 @@ description: FastGPT 文本加工模块介绍
![](/imgs/string.png)
## 功能
对输入文本进行固定加工处理,入参仅支持字符串和数字格式,入参以变量形式使用在文本编辑区域。
根据上方示例图的处理方式,对任何输入都会在前面拼接“用户的问题是:”。
## 作用
给任意模块输入自定格式文本,或处理 AI 模块系统提示词。
## 示例
- [接入谷歌搜索](../../../../use-cases/app-cases/google_search.mdx)
......@@ -38,8 +38,8 @@ Models that support `function calling` can invoke multiple tools in a single tur
### How to Use
| | |
| --- | --- |
| | |
| ------------------------- | ------------------------- |
| ![](/imgs/flow-tool3.png) | ![](/imgs/flow-tool4.png) |
In the advanced workflow editor, drag from the tool calling connection point. Eligible tools display a diamond icon at the top, which you can connect to the diamond at the bottom of the tool calling module.
......@@ -71,8 +71,3 @@ Tool Calling Termination ends the current call cycle. Place it after a tool node
Custom variables extend tool input capabilities. For nodes that aren't recognized as tool parameters or can't be directly tool-called, you can define custom tool variables with appropriate parameter descriptions. The tool calling node will then invoke this node and its downstream workflow accordingly.
![](/imgs/flow-tool7.png)
### Related Examples
- [Google Search](https://doc.fastgpt.in/docs/use-cases/app-cases/google_search/)
- [Send Lark Webhook](https://doc.fastgpt.in/docs/use-cases/app-cases/feishu_webhook/)
......@@ -3,57 +3,54 @@ title: 工具调用&终止
description: FastGPT 工具调用模块介绍
---
![](/imgs/flow-tool1.png)
### **什么是工具**
工具可以是一个系统模块,例如:AI对话、知识库搜索、HTTP模块等。也可以是一个插件。
工具可以是一个系统模块,例如:AI 对话、知识库搜索、HTTP 模块等。也可以是一个插件。
工具调用可以让 LLM 更动态的决策流程,而不都是固定的流程。(当然,缺点就是费tokens)
工具调用可以让 LLM 更动态的决策流程,而不都是固定的流程。(当然,缺点就是费 tokens)
### **工具的组成**
1. 工具介绍。通常是模块的介绍或插件的介绍,这个介绍会告诉LLM,这个工具的作用是什么。
1. 工具介绍。通常是模块的介绍或插件的介绍,这个介绍会告诉 LLM,这个工具的作用是什么。
2. 工具参数。对于系统模块来说,工具参数已经是固定的,无需额外配置。对于插件来说,工具参数是一个可配置项。
### **工具是如何运行的**
要了解工具如何运行的,首先需要知道它的运行条件。
1. 需要工具的介绍(或者叫描述)。这个介绍会告诉LLM,这个工具的作用是什么,LLM会根据上下文语义,决定是否需要调用这个工具。
2. 工具的参数。有些工具调用时,可能需要一些特殊的参数。参数中有2个关键的值:`参数介绍`和`是否必须`。
1. 需要工具的介绍(或者叫描述)。这个介绍会告诉 LLM,这个工具的作用是什么,LLM 会根据上下文语义,决定是否需要调用这个工具。
2. 工具的参数。有些工具调用时,可能需要一些特殊的参数。参数中有 2 个关键的值:`参数介绍` 和 `是否必须`。
结合工具的介绍、参数介绍和参数是否必须,LLM会决定是否调用这个工具。有以下几种情况:
结合工具的介绍、参数介绍和参数是否必须,LLM 会决定是否调用这个工具。有以下几种情况:
1. 无参数的工具:直接根据工具介绍,决定是否需要执行。例如:获取当前时间。
2. 有参数的工具:
1. 无必须的参数:尽管上下文中,没有适合的参数,也可以调用该工具。但有时候,LLM会自己伪造一个参数。
2. 有必须的参数:如果没有适合的参数,LLM可能不会调用该工具。可以通过提示词,引导用户提供参数。
1. 无必须的参数:尽管上下文中,没有适合的参数,也可以调用该工具。但有时候,LLM 会自己伪造一个参数。
2. 有必须的参数:如果没有适合的参数,LLM 可能不会调用该工具。可以通过提示词,引导用户提供参数。
#### **工具调用逻辑**
在支持`函数调用`的模型中,可以一次性调用多个工具,调用逻辑如下:
在支持 `函数调用` 的模型中,可以一次性调用多个工具,调用逻辑如下:
![](/imgs/flow-tool2.png)
### **怎么用**
| | |
| --- | --- |
| | |
| ------------------------- | ------------------------- |
| ![](/imgs/flow-tool3.png) | ![](/imgs/flow-tool4.png) |
高级编排中,拖动工具调用的连接点,可用的工具头部会出现一个菱形,可以将它与工具调用模块底部的菱形相连接。
被连接的工具,会自动分离工具输入与普通的输入,并且可以编辑`介绍`,可以通过调整介绍,使得该工具调用时机更加精确。
被连接的工具,会自动分离工具输入与普通的输入,并且可以编辑 `介绍`,可以通过调整介绍,使得该工具调用时机更加精确。
关于工具调用,如何调试仍然是一个玄学,所以建议,不要一次性增加太多工具,选择少量工具调优后再进一步尝试。
#### 用途
默认情况下,工具调用节点,在决定调用工具后,会将工具运行的结果,返回给AI,让 AI 对工具运行的结果进行总结输出。有时候,如果你不需要 AI 进行进一步的总结输出,可以使用该节点,将其接入对于工具流程的末尾。
默认情况下,工具调用节点,在决定调用工具后,会将工具运行的结果,返回给 AI,让 AI 对工具运行的结果进行总结输出。有时候,如果你不需要 AI 进行进一步的总结输出,可以使用该节点,将其接入对于工具流程的末尾。
如下图,在执行知识库搜索后,发送给了 HTTP 请求,搜索将不会返回搜索的结果给工具调用进行 AI 总结。
......@@ -74,8 +71,3 @@ description: FastGPT 工具调用模块介绍
自定义变量可以扩展工具的变量输入,即对于一些未被视作工具参数或无法工具调用的节点,可以自定义工具变量,填上对应的参数描述,那么工具调用便会相对应的调用这个节点,进而调用其之后的工作流。
![](/imgs/flow-tool7.png)
### **相关示例**
- [谷歌搜索](https://doc.fastgpt.in/docs/use-cases/app-cases/google_search/)
- [发送飞书webhook](https://doc.fastgpt.in/docs/use-cases/app-cases/feishu_webhook/)
......@@ -10,12 +10,11 @@ description: 'FastGPT V4.15.0-beta2 更新说明'
## ⚙️ 优化
1. 优化 OTEL 日志采集格式。
2. 增加 workflow zod 检查鲁棒性。
3. 禁用工作流无效连接模式。
4. 增加工作流节点,名字超长适配。
5. 知识库搜索测试交互。
6. 知识库数据编辑弹窗。
7. reason hide 开关完善,确保只是 UI 不显示,但是 request llm 时候依然可以保留。
2. 禁用工作流无效连接模式。
3. 增加工作流节点,名字超长适配。
4. 知识库搜索测试交互。
5. 知识库数据编辑弹窗。
6. reason hide 开关完善,确保只是 UI 不显示,但是 request llm 时候依然可以保留。
## 🐛 修复
......
......@@ -208,12 +208,3 @@ description: FastGPT Toc
- [/en/self-host/upgrading/outdated/498](/en/self-host/upgrading/outdated/498)
- [/en/self-host/upgrading/outdated/499](/en/self-host/upgrading/outdated/499)
- [/en/self-host/upgrading/upgrade-intruction](/en/self-host/upgrading/upgrade-intruction)
- [/en/use-cases/app-cases/dalle3](/en/use-cases/app-cases/dalle3)
- [/en/use-cases/app-cases/english_essay_correction_bot](/en/use-cases/app-cases/english_essay_correction_bot)
- [/en/use-cases/app-cases/feishu_webhook](/en/use-cases/app-cases/feishu_webhook)
- [/en/use-cases/app-cases/fixingEvidence](/en/use-cases/app-cases/fixingEvidence)
- [/en/use-cases/app-cases/google_search](/en/use-cases/app-cases/google_search)
- [/en/use-cases/app-cases/lab_appointment](/en/use-cases/app-cases/lab_appointment)
- [/en/use-cases/app-cases/multi_turn_translation_bot](/en/use-cases/app-cases/multi_turn_translation_bot)
- [/en/use-cases/app-cases/submit_application_template](/en/use-cases/app-cases/submit_application_template)
- [/en/use-cases/app-cases/translate-subtitle-using-gpt](/en/use-cases/app-cases/translate-subtitle-using-gpt)
......@@ -212,12 +212,3 @@ description: FastGPT 文档目录
- [/self-host/upgrading/outdated/498](/self-host/upgrading/outdated/498)
- [/self-host/upgrading/outdated/499](/self-host/upgrading/outdated/499)
- [/self-host/upgrading/upgrade-intruction](/self-host/upgrading/upgrade-intruction)
- [/use-cases/app-cases/dalle3](/use-cases/app-cases/dalle3)
- [/use-cases/app-cases/english_essay_correction_bot](/use-cases/app-cases/english_essay_correction_bot)
- [/use-cases/app-cases/feishu_webhook](/use-cases/app-cases/feishu_webhook)
- [/use-cases/app-cases/fixingEvidence](/use-cases/app-cases/fixingEvidence)
- [/use-cases/app-cases/google_search](/use-cases/app-cases/google_search)
- [/use-cases/app-cases/lab_appointment](/use-cases/app-cases/lab_appointment)
- [/use-cases/app-cases/multi_turn_translation_bot](/use-cases/app-cases/multi_turn_translation_bot)
- [/use-cases/app-cases/submit_application_template](/use-cases/app-cases/submit_application_template)
- [/use-cases/app-cases/translate-subtitle-using-gpt](/use-cases/app-cases/translate-subtitle-using-gpt)
---
title: DALL-E 3 Image Generation
description: Generate images using the HTTP Request module with DALL-E 3
---
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/demo-dalle1.webp) | ![](../../../public/imgs/demo-dalle2.webp) |
## OpenAI DALL-E 3 API
Here are the official API parameters and response format:
Body
```json
{
"model": "dall-e-3",
"prompt": "A cute baby sea otter",
"n": 1,
"size": "1024x1024"
}
```
Response
```json
{
"created": 1589478378,
"data": [
{
"url": "https://..."
},
{
"url": "https://..."
}
]
}
```
## Workflow Design
1. Use AI to optimize the image generation prompt (skipped here — use your own prompt).
2. Use the `HTTP Request` module to call the DALL-E 3 API and retrieve the image URL.
3. Use the `Text Editor` module to construct a `Markdown` image tag.
4. Use the `Specified Reply` module to output the image link directly.
### 1. Build the HTTP Module
Copy the DALL-E 3 API request parameters and replace `prompt` with a variable. You also need to add a `Headers.Authorization` header.
Body:
```json
{
"model": "dall-e-3",
"prompt": "{{prompt}}",
"n": 1,
"size": "1024x1024"
}
```
Headers:
`Authorization: Bearer sk-xxx`
Response:
Extract the response value based on the DALL-E 3 API return format. Since we only generate one image, we just need the first image's URL. Add a custom output `data[0].url` to the HTTP module.
### 2. Text Editor — Build Image Link
In `Markdown` syntax, `![image description](image URL)` inserts an image, where the image URL comes from the `HTTP Request` module output.
Add an input to receive the image URL from the `HTTP Request` module, then reference it as a variable in the `Text Editor` module to produce a complete `Markdown` image tag.
### 3. Specified Reply
The Specified Reply module outputs incoming content directly to the client, so it can render the processed `Markdown` image format as-is.
## Workflow Configuration
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "System Config",
"intro": "Configure system parameters for the application",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 531.2422736065552,
"y": -486.7611729549753
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "Workflow Start",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 532.1275542407774,
"y": 46.03775600322817
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "User Question",
"required": true,
"toolDescription": "User Question"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "tMyUnRL5jIrC",
"name": "HTTP Request",
"intro": "Send an HTTP request for advanced operations (web search, database queries, etc.)",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 921.2377506442713,
"y": -483.94114977914256
},
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"key": "prompt",
"valueType": "string",
"label": "prompt",
"renderTypeList": [
"reference"
],
"description": "",
"canEdit": true,
"editField": {
"key": true,
"valueType": true
},
"value": [
"448745",
"userChatInput"
]
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": "https://api.openai.com/v1/images/generations"
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [
{
"key": "Authorization",
"type": "string",
"value": "Bearer "
}
],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\n \"model\": \"dall-e-3\",\n \"prompt\": \"{{prompt}}\",\n \"n\": 1,\n \"size\": \"1024x1024\"\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "Raw Response",
"description": "The raw HTTP response. Only accepts string or JSON response data.",
"valueType": "any",
"type": "static"
},
{
"id": "DeKGGioBwaMf",
"type": "dynamic",
"key": "data[0].url",
"valueType": "string",
"label": "data[0].url"
}
]
},
{
"nodeId": "CO3POL8svbbi",
"name": "Text Editor",
"intro": "Process fixed or incoming text and output the result. Non-string data is converted to string.",
"avatar": "/imgs/workflow/textEditor.svg",
"flowNodeType": "pluginModule",
"showStatus": false,
"position": {
"x": 1417.5940290051137,
"y": -478.81889618104356
},
"inputs": [
{
"key": "system_addInputParam",
"valueType": "dynamic",
"label": "Dynamic External Data",
"renderTypeList": [
"addInputParam"
],
"required": false,
"description": "",
"canEdit": false,
"value": "",
"editField": {
"key": true
},
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
},
{
"key": "url",
"valueType": "string",
"label": "url",
"renderTypeList": [
"reference"
],
"required": true,
"description": "",
"canEdit": true,
"editField": {
"key": true
},
"value": [
"tMyUnRL5jIrC",
"DeKGGioBwaMf"
]
},
{
"key": "文本",
"valueType": "string",
"label": "文本",
"renderTypeList": [
"textarea"
],
"required": true,
"description": "",
"canEdit": false,
"value": "![]({{url}})",
"editField": {
"key": true
},
"maxLength": "",
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
}
],
"outputs": [
{
"id": "text",
"type": "static",
"key": "text",
"valueType": "string",
"label": "text",
"description": ""
}
],
"pluginId": "community-textEditor"
},
{
"nodeId": "7mapnCgHfKW6",
"name": "Specified Reply",
"intro": "Directly replies with specified content. Commonly used for guidance and prompts. Non-string input is converted to string for output.",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1922.5628399315042,
"y": -471.67391598231796
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "string",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 1,
"value": [
"CO3POL8svbbi",
"text"
]
}
],
"outputs": []
}
],
"edges": [
{
"source": "448745",
"target": "tMyUnRL5jIrC",
"sourceHandle": "448745-source-right",
"targetHandle": "tMyUnRL5jIrC-target-left"
},
{
"source": "tMyUnRL5jIrC",
"target": "CO3POL8svbbi",
"sourceHandle": "tMyUnRL5jIrC-source-right",
"targetHandle": "CO3POL8svbbi-target-left"
},
{
"source": "CO3POL8svbbi",
"target": "7mapnCgHfKW6",
"sourceHandle": "CO3POL8svbbi-source-right",
"targetHandle": "7mapnCgHfKW6-target-left"
}
]
}
```
</details>
---
title: Dalle3 绘图
description: 使用 HTTP 模块绘制图片
---
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/demo-dalle1.webp) | ![](../../../public/imgs/demo-dalle2.webp) |
## OpenAI Dalle3 接口
先来看下官方接口的参数和响应值:
Body
```json
{
"model": "dall-e-3",
"prompt": "A cute baby sea otter",
"n": 1,
"size": "1024x1024"
}
```
Response
```json
{
"created": 1589478378,
"data": [
{
"url": "https://..."
},
{
"url": "https://..."
}
]
}
```
## 编排思路
1. 通过 AI 来优化图片绘制的提示词(这步省略了,自己找提示词即可)
2. 通过 `【HTTP 请求】模块` 调用 Dalle3 接口,获取图片的 URL。
3. 通过 `【文本加工】模块` 来构建 `Markdown` 的图片格式。
4. 通过 `【指定回复】模块` 来直接输出图片链接。
### 1. 构建 HTTP 模块
请求参数直接复制 Dalle3 接口的即可,并求改 prompt 为变量。需要增加一个 `Headers.Authorization` 。
Body:
```json
{
"model": "dall-e-3",
"prompt": "{{prompt}}",
"n": 1,
"size": "1024x1024"
}
```
Headers:
`Authorization: Bearer sk-xxx`
Response:
响应值需要根据 Dalle3 接口的返回值进行获取,我们只绘制了1张图片,所以只需要取第一张图片的 URL 即可。给 HTTP 模块增加一个自定义输出 `data[0].url` 。
### 2. 文本加工 - 构建图片链接
在 `Markdown` 语法中 `![图片描述](图片链接)` 表示插入图片,图片链接由【HTTP 请求】模块输出。
因此可以增加一个输入来接收 `【HTTP 请求】模块` 的图片链接输出,并在 `【文本加工】模块 - 文本` 中通过变量来引用图片链接,从而得到一个完整的 `Markdown` 图片格式。
### 3. 指定回复
指定回复可以直接输出传入的内容到客户端,因此可以直接输出加工好的 `Markdown` 图片格式即可。
## 编排代码
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 531.2422736065552,
"y": -486.7611729549753
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 532.1275542407774,
"y": 46.03775600322817
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "tMyUnRL5jIrC",
"name": "HTTP 请求",
"intro": "可以发出一个 HTTP 请求,实现更为复杂的操作(联网搜索、数据库查询等)",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 921.2377506442713,
"y": -483.94114977914256
},
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"key": "prompt",
"valueType": "string",
"label": "prompt",
"renderTypeList": [
"reference"
],
"description": "",
"canEdit": true,
"editField": {
"key": true,
"valueType": true
},
"value": [
"448745",
"userChatInput"
]
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": "https://api.openai.com/v1/images/generations"
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [
{
"key": "Authorization",
"type": "string",
"value": "Bearer "
}
],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\n \"model\": \"dall-e-3\",\n \"prompt\": \"{{prompt}}\",\n \"n\": 1,\n \"size\": \"1024x1024\"\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "原始响应",
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。",
"valueType": "any",
"type": "static"
},
{
"id": "DeKGGioBwaMf",
"type": "dynamic",
"key": "data[0].url",
"valueType": "string",
"label": "data[0].url"
}
]
},
{
"nodeId": "CO3POL8svbbi",
"name": "文本加工",
"intro": "可对固定或传入的文本进行加工后输出,非字符串类型数据最终会转成字符串类型。",
"avatar": "/imgs/workflow/textEditor.svg",
"flowNodeType": "pluginModule",
"showStatus": false,
"position": {
"x": 1417.5940290051137,
"y": -478.81889618104356
},
"inputs": [
{
"key": "system_addInputParam",
"valueType": "dynamic",
"label": "动态外部数据",
"renderTypeList": [
"addInputParam"
],
"required": false,
"description": "",
"canEdit": false,
"value": "",
"editField": {
"key": true
},
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
},
{
"key": "url",
"valueType": "string",
"label": "url",
"renderTypeList": [
"reference"
],
"required": true,
"description": "",
"canEdit": true,
"editField": {
"key": true
},
"value": [
"tMyUnRL5jIrC",
"DeKGGioBwaMf"
]
},
{
"key": "文本",
"valueType": "string",
"label": "文本",
"renderTypeList": [
"textarea"
],
"required": true,
"description": "",
"canEdit": false,
"value": "![]({{url}})",
"editField": {
"key": true
},
"maxLength": "",
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
}
],
"outputs": [
{
"id": "text",
"type": "static",
"key": "text",
"valueType": "string",
"label": "text",
"description": ""
}
],
"pluginId": "community-textEditor"
},
{
"nodeId": "7mapnCgHfKW6",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1922.5628399315042,
"y": -471.67391598231796
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "string",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 1,
"value": [
"CO3POL8svbbi",
"text"
]
}
],
"outputs": []
}
],
"edges": [
{
"source": "448745",
"target": "tMyUnRL5jIrC",
"sourceHandle": "448745-source-right",
"targetHandle": "tMyUnRL5jIrC-target-left"
},
{
"source": "tMyUnRL5jIrC",
"target": "CO3POL8svbbi",
"sourceHandle": "tMyUnRL5jIrC-source-right",
"targetHandle": "CO3POL8svbbi-target-left"
},
{
"source": "CO3POL8svbbi",
"target": "7mapnCgHfKW6",
"sourceHandle": "CO3POL8svbbi-source-right",
"targetHandle": "7mapnCgHfKW6-target-left"
}
]
}
```
</details>
---
title: English Essay Correction Bot
description: Build an English essay correction bot with FastGPT to detect and fix language errors
---
FastGPT provides a straightforward way to build applications powered by LLM models.
This article demonstrates how to use **Workflows** by building an English essay correction bot.
## Building Process
### 1. Create a Workflow
![](../../../public/imgs/spellcheck1.png)
You can start from the *Multi-turn Translation Bot* template.
> The Multi-turn Translation Bot was created by @米开朗基杨 — also a great workflow worth studying.
### 2. Get Input and Analyze with LLM
We want the LLM to process text and return structured data that we handle ourselves.
![](../../../public/imgs/spellcheck2.png)
The **System Prompt** is the most critical parameter. Here is a reference prompt:
~~~markdown
## Role
Senior English Writing Expert
## Task
Analyze the input text. Find all types of errors, including but not limited to spelling mistakes and grammar errors.
Note: Ignore spacing issues around punctuation.
Note: For sentences with errors, the suggestion should identify the specific part of the sentence and propose what to replace it with.
## Output Format
Do not use Markdown syntax. Output in JSON format.
Output the "reason" field in Chinese.
Directly output a list whose members are objects of the same type, defined as follows:
```
{
"raw": string; // the original text
"reason": string; // the reason
"suggestion": string; // suggested correction
}
```
~~~
You can disable AI reply in the model selection window.
This hides the raw JSON output from the user.
![](../../../public/imgs/spellcheck3.png)
### 3. Data Processing
The LLM outputs JSON, which needs further processing. Use the Code Execution module for this.
![](../../../public/imgs/spellcheck4.png)
```javascript
function main({data}){
const array = JSON.parse(data)
return {
content: array.map(
(item, index) => {
return `
## Analysis ${index+1}
- **Error**: ${item.raw}
- **Analysis**: ${item.reason}
- **Suggestion**: ${item.suggestion}
`
}
).join('')
}
}
```
The code parses the JSON into an object, then concatenates it into a Markdown-formatted string.
FastGPT's Specified Reply module renders Markdown as HTML in the response.
## Publishing
Publish through the available publishing channels.
![](../../../public/imgs/spellcheck5.png)
You can access it via URL or embed it directly into your webpage.
> [Click to try it](https://share.fastgpt.in/chat/share?shareId=b4r173wkcjae7wpnexcvmyc3)
---
title: 英语作文纠错机器人
description: 使用 FastGPT 创建一个用于英语作文纠错的机器人,帮助用户检测并纠正语言错误
---
FastGPT 提供了一种基于 LLM Model 搭建应用的简便方式。
本文通过搭建一个英语作文纠错机器人,介绍一下如何使用 **工作流**
## 搭建过程
### 1. 创建工作流
![](../../../public/imgs/spellcheck1.png)
可以从 *多轮翻译机器人* 开始创建。
> 多轮翻译机器人是 @米开朗基杨 同学创建的,同样也是一个值得学习的工作流。
### 2. 获取输入,使用大模型进行分析
我们期望让大模型处理文字,返回一个结构化的数据,由我们自己处理。
![](../../../public/imgs/spellcheck2.png)
**提示词** 是最重要的一个参数,这里提供的提示词仅供参考:
~~~markdown
## 角色
资深英语写作专家
## 任务
对输入的原文进行分析。 找出其中的各种错误, 包括但不限于单词拼写错误、 语法错误等。
注意: 忽略标点符号前后空格的问题。
注意: 对于存在错误的句子, 提出修改建议是指指出这个句子中的具体部分, 然后提出将这一个部分修改替换为什么。
## 输出格式
不要使用 Markdown 语法, 输入 JSON 格式的内容。
输出的"reason"的内容使用中文。
直接输出一个列表, 其成员为一个相同类型的对象, 定义如下
您正在找回 FastGPT 账号
```
{
“raw”: string; // 表示原文
“reason”: string; // 表示原因
“suggestion”: string; // 修改建议
}
```
~~~
可以在模型选择的窗口中设置禁用 AI 回复。
这样就看不到输出的 json 格式的内容了。
![](../../../public/imgs/spellcheck3.png)
### 3. 数据处理
上面的大模型输出了一个 json,这里要进行数据处理。数据处理可以使用代码执行组件。
![](../../../public/imgs/spellcheck4.png)
```javascript
function main({data}){
const array = JSON.parse(data)
return {
content: array.map(
(item, index) => {
return `
## 分析${index+1}
- **错误**: ${item.raw}
- **分析**: ${item.reason}
- **修改建议**: ${item.suggestion}
`
}
).join('')
}
}
```
上面的代码将 JSON 解析为 Object, 然后拼接成一串 Markdown 语法的字符串。
FastGPT 的指定回复组件可以将 Markdown 解析为 Html 返回。
## 发布
可以使用发布渠道进行发布。
![](../../../public/imgs/spellcheck5.png)
可以选择通过 URL 访问,或者是直接嵌入你的网页中。
> [点我使用](https://share.fastgpt.in/chat/share?shareId=b4r173wkcjae7wpnexcvmyc3)
---
title: Send Lark Webhook Notifications
description: Use the Tool Call module to send Lark webhook notifications
---
This article shows how to send a simple Lark webhook notification. The same approach applies to other types of notifications.
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/feishuwebhook1.webp) | ![](../../../public/imgs/feishuwebhook2.webp) |
## 1. Set Up the Lark Bot
| | | |
| --------------------- | --------------------- |--------------------- |
| ![](../../../public/imgs/feishuwebhook3.png) | ![](../../../public/imgs/feishuwebhook4.webp) |![](../../../public/imgs/feishuwebhook5.png) |
## 2. Import Workflow Configuration
Copy the configuration below, click the import button in the top-right corner of "Advanced Orchestration", and import it. After importing, paste the webhook URL provided by Lark into the "HTTP Request" module.
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 303.41163758039283,
"y": -552.297639861266
},
"version": "481",
"inputs": [],
"outputs": []
},
{
"nodeId": "workflowStartNodeId",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 529.3935295017156,
"y": 197.114018410347
},
"version": "481",
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "u6IAOEssxoZT",
"name": "工具调用",
"intro": "通过AI模型自动选择一个或多个功能块进行调用,也可以对插件进行调用。",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 1003.146243538873,
"y": 48.52327869406625
},
"version": "481",
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"description": "最多携带多少轮对话记录",
"required": true,
"min": 0,
"max": 50,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"value": [
"workflowStartNodeId",
"userChatInput"
]
}
],
"outputs": [
{
"id": "answerText",
"key": "answerText",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "fvY5hb0K646V",
"name": "工具调用终止",
"intro": "该模块需配置工具调用使用。当该模块被执行时,本次工具调用将会强制结束,并且不再调用AI针对工具调用结果回答问题。",
"avatar": "/imgs/workflow/toolStop.svg",
"flowNodeType": "stopTool",
"position": {
"x": 2367.838362362707,
"y": 732.355988936165
},
"version": "481",
"inputs": [],
"outputs": []
},
{
"nodeId": "x9rN2a4WnZmt",
"name": "HTTP 请求",
"intro": "向飞书发送一个webhooks通知信息。",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1623.9214305901633,
"y": 22.777089001645862
},
"version": "486",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "text",
"label": "text",
"toolDescription": "发送的消息",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": ""
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\r\n \"msg_type\": \"text\",\r\n \"content\": {\r\n \"text\": \"{{text}}\"\r\n }\r\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "error",
"key": "error",
"label": "请求错误",
"description": "HTTP请求错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "原始响应",
"required": true,
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。",
"valueType": "any",
"type": "static"
}
]
},
{
"nodeId": "aGHGqH2oUupj",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 2350.7077940158674,
"y": 107.32448732713493
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "嘻嘻,发送成功"
}
],
"outputs": []
}
],
"edges": [
{
"source": "workflowStartNodeId",
"target": "u6IAOEssxoZT",
"sourceHandle": "workflowStartNodeId-source-right",
"targetHandle": "u6IAOEssxoZT-target-left"
},
{
"source": "u6IAOEssxoZT",
"target": "x9rN2a4WnZmt",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "x9rN2a4WnZmt",
"target": "fvY5hb0K646V",
"sourceHandle": "x9rN2a4WnZmt-source-right",
"targetHandle": "fvY5hb0K646V-target-left"
},
{
"source": "x9rN2a4WnZmt",
"target": "aGHGqH2oUupj",
"sourceHandle": "x9rN2a4WnZmt-source-right",
"targetHandle": "aGHGqH2oUupj-target-left"
}
],
"chatConfig": {
"variables": [
{
"id": "txq1ca",
"key": "test",
"label": "测试",
"type": "custom",
"required": true,
"maxLen": 50,
"enums": [
{
"value": ""
}
]
}
],
"questionGuide": false,
"scheduledTriggerConfig": {
"cronString": "",
"timezone": "Asia/Shanghai",
"defaultPrompt": ""
},
"_id": "66715d4bf577287d39e35ecf"
}
}
```
</details>
## 3. How It Works
1. Attach an HTTP module to the Tool Call with the description: "Call Lark webhook to send a notification."
2. In the HTTP module's input parameters, fill in the Lark bot's webhook URL and the notification content.
3. Connect the HTTP module's output to a Tool Call Terminator to force-end the tool call. Without this, the result would be sent back to the model, which would generate another response — wasting tokens.
4. Also connect the HTTP module's output to a Specified Reply to directly return a success message, replacing the AI's response.
---
title: 发送飞书webhook通知
description: 利用工具调用模块,发送一个飞书webhook通知
---
该文章展示如何发送一个简单的飞书webhook通知,以此类推,发送其他类型的通知也可以这么操作。
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/feishuwebhook1.webp) | ![](../../../public/imgs/feishuwebhook2.webp) |
## 1. 准备飞书机器人
| | | |
| --------------------- | --------------------- |--------------------- |
| ![](../../../public/imgs/feishuwebhook3.png) | ![](../../../public/imgs/feishuwebhook4.webp) |![](../../../public/imgs/feishuwebhook5.png) |
## 2. 导入编排代码
复制下面配置,点击「高级编排」右上角的导入按键,导入该配置,导入后将飞书提供的接口地址复制到「HTTP 模块」。
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 303.41163758039283,
"y": -552.297639861266
},
"version": "481",
"inputs": [],
"outputs": []
},
{
"nodeId": "workflowStartNodeId",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 529.3935295017156,
"y": 197.114018410347
},
"version": "481",
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "u6IAOEssxoZT",
"name": "工具调用",
"intro": "通过AI模型自动选择一个或多个功能块进行调用,也可以对插件进行调用。",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 1003.146243538873,
"y": 48.52327869406625
},
"version": "481",
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"description": "最多携带多少轮对话记录",
"required": true,
"min": 0,
"max": 50,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"value": [
"workflowStartNodeId",
"userChatInput"
]
}
],
"outputs": [
{
"id": "answerText",
"key": "answerText",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "fvY5hb0K646V",
"name": "工具调用终止",
"intro": "该模块需配置工具调用使用。当该模块被执行时,本次工具调用将会强制结束,并且不再调用AI针对工具调用结果回答问题。",
"avatar": "/imgs/workflow/toolStop.svg",
"flowNodeType": "stopTool",
"position": {
"x": 2367.838362362707,
"y": 732.355988936165
},
"version": "481",
"inputs": [],
"outputs": []
},
{
"nodeId": "x9rN2a4WnZmt",
"name": "HTTP 请求",
"intro": "向飞书发送一个webhooks通知信息。",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1623.9214305901633,
"y": 22.777089001645862
},
"version": "486",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "text",
"label": "text",
"toolDescription": "发送的消息",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": ""
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\r\n \"msg_type\": \"text\",\r\n \"content\": {\r\n \"text\": \"{{text}}\"\r\n }\r\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "error",
"key": "error",
"label": "请求错误",
"description": "HTTP请求错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "原始响应",
"required": true,
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。",
"valueType": "any",
"type": "static"
}
]
},
{
"nodeId": "aGHGqH2oUupj",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 2350.7077940158674,
"y": 107.32448732713493
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "嘻嘻,发送成功"
}
],
"outputs": []
}
],
"edges": [
{
"source": "workflowStartNodeId",
"target": "u6IAOEssxoZT",
"sourceHandle": "workflowStartNodeId-source-right",
"targetHandle": "u6IAOEssxoZT-target-left"
},
{
"source": "u6IAOEssxoZT",
"target": "x9rN2a4WnZmt",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "x9rN2a4WnZmt",
"target": "fvY5hb0K646V",
"sourceHandle": "x9rN2a4WnZmt-source-right",
"targetHandle": "fvY5hb0K646V-target-left"
},
{
"source": "x9rN2a4WnZmt",
"target": "aGHGqH2oUupj",
"sourceHandle": "x9rN2a4WnZmt-source-right",
"targetHandle": "aGHGqH2oUupj-target-left"
}
],
"chatConfig": {
"variables": [
{
"id": "txq1ca",
"key": "test",
"label": "测试",
"type": "custom",
"required": true,
"maxLen": 50,
"enums": [
{
"value": ""
}
]
}
],
"questionGuide": false,
"scheduledTriggerConfig": {
"cronString": "",
"timezone": "Asia/Shanghai",
"defaultPrompt": ""
},
"_id": "66715d4bf577287d39e35ecf"
}
}
```
</details>
## 3. 流程说明
1. 为工具调用挂载一个HTTP模块,功能描述写上:调用飞书webhook,发送一个通知。
2. HTTP模块的输入参数中,填写飞书机器人的地址,填写发送的通知内容。
3. HTTP模块输出连接上一个工具终止模块,用于强制结束工具调用。不终止的话,会把调用结果返回给模型,模型会继续回答一次问题,浪费 Tokens
4. HTTP模块输出再连上一个指定回复,直接回复一个发送成功,用于替代AI的回答。
---
title: Add Fixed Opening and Closing Content
description: Use Specified Reply modules to add fixed opening and closing messages to responses
---
![](../../../public/imgs/demo-fix-evidence1.jpg)
![](../../../public/imgs/demo-fix-evidence2.jpg)
As shown above, you can use Specified Reply modules to add fixed opening and closing content to your responses.
## Module Configuration
Copy the configuration below, click the import button in the top-right corner of "Advanced Orchestration", and paste it in.
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "7z5g5h",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": -269.50851681351924,
"y": 1657.6123698022448
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "systemInput",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0,
"value": [
"7z5g5h",
"userChatInput"
]
}
],
"outputs": [
{
"id": "userChatInput",
"type": "static",
"key": "userChatInput",
"valueType": "string",
"label": "core.module.input.label.user question"
}
]
},
{
"nodeId": "nlfwkc",
"name": "AI 对话",
"intro": "AI 大模型对话",
"avatar": "/imgs/workflow/AI.png",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 907.2058332478431,
"y": 1348.9992737142143
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"type": "selectLLMModel",
"required": true,
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "gpt-3.5-turbo",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": true,
"valueType": "boolean",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 300,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"value": "",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6,
"type": "numberInput",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "custom",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 0,
"value": [
"7z5g5h",
"userChatInput"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "core.module.Dataset quote.Input description",
"valueType": "datasetQuote",
"type": "target",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 0,
"value": [
"fljhzy",
"quoteQA"
]
}
],
"outputs": [
{
"id": "answerText",
"type": "static",
"key": "answerText",
"valueType": "string",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content"
},
{
"id": "history",
"type": "static",
"key": "history",
"valueType": "chatHistory",
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context"
}
]
},
{
"nodeId": "q9equb",
"name": "core.module.template.App system setting",
"intro": "可以配置应用的系统参数。",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": -275.92529567956024,
"y": 1094.1001488133452
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "你好,我是电影《星际穿越》 AI 助手,有什么可以帮助你的?\\n[导演是谁]\\n[剧情介绍]\\n[票房分析]",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.module.Variable",
"value": [],
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "",
"type": "switch",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": ""
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "tc90wz",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 159.49274056478237,
"y": 1621.4635230667668
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"value": "这是开头\\\\n",
"connected": false,
"selectedTypeIndex": 0
}
],
"outputs": []
},
{
"nodeId": "U5T3dMVY4wj7",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1467.0625486167608,
"y": 1597.346243737531
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "string",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "这是结尾"
}
],
"outputs": []
}
],
"edges": [
{
"source": "7z5g5h",
"target": "tc90wz",
"sourceHandle": "7z5g5h-source-right",
"targetHandle": "tc90wz-target-left"
},
{
"source": "tc90wz",
"target": "nlfwkc",
"sourceHandle": "tc90wz-source-right",
"targetHandle": "nlfwkc-target-left"
},
{
"source": "nlfwkc",
"target": "U5T3dMVY4wj7",
"sourceHandle": "nlfwkc-source-right",
"targetHandle": "U5T3dMVY4wj7-target-left"
}
]
}
```
</details>
---
title: 固定开头和结尾内容
description: 利用指定回复,创建固定的开头和结尾
---
![](../../../public/imgs/demo-fix-evidence1.jpg)
![](../../../public/imgs/demo-fix-evidence2.jpg)
如上图,可以通过指定回复编排一个固定的开头和结尾内容。
## 模块编排
复制下面配置,点击「高级编排」右上角的导入按键,导入该配置。
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "7z5g5h",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": -269.50851681351924,
"y": 1657.6123698022448
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "systemInput",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0,
"value": [
"7z5g5h",
"userChatInput"
]
}
],
"outputs": [
{
"id": "userChatInput",
"type": "static",
"key": "userChatInput",
"valueType": "string",
"label": "core.module.input.label.user question"
}
]
},
{
"nodeId": "nlfwkc",
"name": "AI 对话",
"intro": "AI 大模型对话",
"avatar": "/imgs/workflow/AI.png",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 907.2058332478431,
"y": 1348.9992737142143
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"type": "selectLLMModel",
"required": true,
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "gpt-3.5-turbo",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": true,
"valueType": "boolean",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 300,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"value": "",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6,
"type": "numberInput",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "custom",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 0,
"value": [
"7z5g5h",
"userChatInput"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "core.module.Dataset quote.Input description",
"valueType": "datasetQuote",
"type": "target",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 0,
"value": [
"fljhzy",
"quoteQA"
]
}
],
"outputs": [
{
"id": "answerText",
"type": "static",
"key": "answerText",
"valueType": "string",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content"
},
{
"id": "history",
"type": "static",
"key": "history",
"valueType": "chatHistory",
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context"
}
]
},
{
"nodeId": "q9equb",
"name": "core.module.template.App system setting",
"intro": "可以配置应用的系统参数。",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": -275.92529567956024,
"y": 1094.1001488133452
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "你好,我是电影《星际穿越》 AI 助手,有什么可以帮助你的?\n[导演是谁]\n[剧情介绍]\n[票房分析]",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.module.Variable",
"value": [],
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "",
"type": "switch",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": ""
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "tc90wz",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 159.49274056478237,
"y": 1621.4635230667668
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"value": "这是开头\\n",
"connected": false,
"selectedTypeIndex": 0
}
],
"outputs": []
},
{
"nodeId": "U5T3dMVY4wj7",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1467.0625486167608,
"y": 1597.346243737531
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "string",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "这是结尾"
}
],
"outputs": []
}
],
"edges": [
{
"source": "7z5g5h",
"target": "tc90wz",
"sourceHandle": "7z5g5h-source-right",
"targetHandle": "tc90wz-target-left"
},
{
"source": "tc90wz",
"target": "nlfwkc",
"sourceHandle": "tc90wz-source-right",
"targetHandle": "nlfwkc-target-left"
},
{
"source": "nlfwkc",
"target": "U5T3dMVY4wj7",
"sourceHandle": "nlfwkc-source-right",
"targetHandle": "U5T3dMVY4wj7-target-left"
}
]
}
```
</details>
---
title: Google Search Integration
description: Integrate FastGPT with Google Search
---
| | |
| --------------------- | --------------------- |
| Tool Call Mode ![](../../../public/imgs/google_search_3.webp) | Tool Call Mode ![](../../../public/imgs/google_search_4.webp) |
| Non-Tool Call Mode ![](../../../public/imgs/google_search_1.webp) | Non-Tool Call Mode ![](../../../public/imgs/google_search_2.webp) |
As shown above, using the「HTTP Request」module, you can connect an external search engine as reference material for AI responses. This example uses the Google Search API. Note: This article mainly introduces the「HTTP Request」module. The actual search effectiveness depends on prompts and the search engine, especially the【search engine】—simple search engines cannot retrieve detailed content, which may require more debugging.
## Register Google Search API
[Refer to this article](https://zhuanlan.zhihu.com/p/174666017), which allows 100 free uses per day.
## Write a Google Search Interface
Use [Laf](https://laf.dev/) to quickly implement an interface—write and publish instantly without deployment. Make sure to enable POST request method.
<details>
<summary>Laf Google Search Demo</summary>
```typescript
import cloud from '@lafjs/cloud'
const googleSearchKey = "xxx"
const googleCxId = "3740cxxx"
const baseurl = "https://www.googleapis.com/customsearch/v1"
type RequestType = {
searchKey: string
}
export default async function (ctx: FunctionContext) {
const { searchKey } = ctx.body as RequestType
console.log(ctx.body)
if (!searchKey) {
return {
prompt: ""
}
}
try {
const { data } = await cloud.fetch.get(baseurl, {
params: {
q: searchKey,
cx: googleCxId,
key: googleSearchKey,
c2coff: 1,
start: 1,
end: 20,
dateRestrict: 'm[1]',
}
})
const result = data.items.map((item) => item.snippet).join('\n');
return { prompt: result }
} catch (err) {
console.log(err)
ctx.response.status(500)
return {
message: "Error"
}
}
}
```
</details>
## Workflow Design - Tool Call Mode
Using the tool module, no extra operations are needed—the model decides whether to call Google Search and generates search terms automatically.
Copy the configuration below, enter「Advanced Workflow」, select「Import Configuration」from the "..." in the top right corner, then modify the「HTTP Request」module - Request URL value after importing.
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "System Configuration",
"intro": "Configure application system parameters",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 262.2732338817093,
"y": -476.00241136598146
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "Workflow Start",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 295.8944548701009,
"y": 110.81336038514848
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "User Question",
"required": true,
"toolDescription": "User Question"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "NOgbnBzUwDgT",
"name": "Tool Call",
"intro": "Automatically select one or more function blocks to call through AI model, can also call plugins.",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 1028.8358722416106,
"y": -500.8755882990822
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "FastAI-plus"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "You are a Google search bot. Generate search terms based on the current question and conversation history. You need to determine whether real-time web queries are needed:\n- If a query is needed, generate search terms.\n- If no query is needed, don't return the field."
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "User Question",
"required": true,
"value": [
"448745",
"userChatInput"
]
}
],
"outputs": []
},
{
"nodeId": "GMELVPxHfpg5",
"name": "HTTP Request",
"intro": "Call Google Search to query relevant content",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1013.2159795348916,
"y": 210.8685573380423
},
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "query",
"label": "query",
"toolDescription": "Google search query term",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": "https://xxxxxx.laf.dev/google_search"
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\n \"searchKey\": \"{{query}}\"\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "Raw Response",
"description": "Raw response from HTTP request. Only accepts string or JSON type response data.",
"valueType": "any",
"type": "static"
},
{
"id": "M5YmxaYe8em1",
"type": "dynamic",
"key": "prompt",
"valueType": "string",
"label": "prompt"
}
]
}
],
"edges": [
{
"source": "448745",
"target": "NOgbnBzUwDgT",
"sourceHandle": "448745-source-right",
"targetHandle": "NOgbnBzUwDgT-target-left"
},
{
"source": "NOgbnBzUwDgT",
"target": "GMELVPxHfpg5",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
}
]
}
```
</details>
## Workflow Design - Non-Tool Call Mode
Copy the configuration below, enter「Advanced Workflow」, select「Import Configuration」from the "..." in the top right corner, then modify the「HTTP Request」module - Request URL value after importing.
<details>
<summary>Workflow Configuration</summary>
```json
[Configuration JSON omitted for brevity - same structure as Chinese version with translated labels]
```
</details>
### Workflow Explanation
1. Use the【Content Extraction】module to extract search keywords from the user's question.
2. Pass the search keywords to the【HTTP Request】module to execute Google Search.
3. Use the【Text Processing】module to combine search results and the question, generating a question suitable for the model to answer.
4. Send the new question to the【AI Chat】module to answer based on search results.
---
title: 接入谷歌搜索
description: 将 FastGPT 接入谷歌搜索
---
| | |
| --------------------- | --------------------- |
| 工具调用模式 ![](../../../public/imgs/google_search_3.webp) | 工具调用模式 ![](../../../public/imgs/google_search_4.webp) |
| 非工具调用模式 ![](../../../public/imgs/google_search_1.webp) | 非工具调用模式 ![](../../../public/imgs/google_search_2.webp) |
如上图,利用「HTTP请求」模块,你可以外接一个搜索引擎作为 AI 回复的参考资料。这里以调用 Google Search API 为例。注意:本文主要是为了介绍 「HTTP请求」模块,具体的搜索效果需要依赖提示词和搜索引擎,尤其是【搜索引擎】,简单的搜索引擎无法获取更详细的内容,这部分可能需要更多的调试。
## 注册 Google Search API
[参考这篇文章](https://zhuanlan.zhihu.com/p/174666017),每天可以免费使用 100 次。
## 写一个 Google Search 接口
这里用 [Laf](https://laf.dev/) 快速实现一个接口,即写即发布,无需部署。务必打开 POST 请求方式。
<details>
<summary>Laf 谷歌搜索Demo</summary>
```typescript
import cloud from '@lafjs/cloud'
const googleSearchKey = "xxx"
const googleCxId = "3740cxxx"
const baseurl = "https://www.googleapis.com/customsearch/v1"
type RequestType = {
searchKey: string
}
export default async function (ctx: FunctionContext) {
const { searchKey } = ctx.body as RequestType
console.log(ctx.body)
if (!searchKey) {
return {
prompt: ""
}
}
try {
const { data } = await cloud.fetch.get(baseurl, {
params: {
q: searchKey,
cx: googleCxId,
key: googleSearchKey,
c2coff: 1,
start: 1,
end: 20,
dateRestrict: 'm[1]',
}
})
const result = data.items.map((item) => item.snippet).join('\n');
return { prompt: result }
} catch (err) {
console.log(err)
ctx.response.status(500)
return {
message: "异常"
}
}
}
```
</details>
## 模块编排 - 工具调用模式
利用工具模块,则无需多余的操作,直接由模型决定是否调用谷歌搜索,并生成检索词即可。
复制下面配置,进入「高级编排」,在右上角的 “...” 中选择「导入配置」,导入后修改「HTTP 请求」模块 - 请求地址 的值。
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 262.2732338817093,
"y": -476.00241136598146
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 295.8944548701009,
"y": 110.81336038514848
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "NOgbnBzUwDgT",
"name": "工具调用",
"intro": "通过AI模型自动选择一个或多个功能块进行调用,也可以对插件进行调用。",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 1028.8358722416106,
"y": -500.8755882990822
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "FastAI-plus"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "你是谷歌搜索机器人,根据当前问题和对话记录生成搜索词。你需要自行判断是否需要进行网络实时查询:\n- 如果需查询则生成搜索词。\n- 如果不需要查询则不返回字段。"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"value": [
"448745",
"userChatInput"
]
}
],
"outputs": []
},
{
"nodeId": "GMELVPxHfpg5",
"name": "HTTP 请求",
"intro": "调用谷歌搜索,查询相关内容",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1013.2159795348916,
"y": 210.8685573380423
},
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "query",
"label": "query",
"toolDescription": "谷歌搜索检索词",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": "https://xxxxxx.laf.dev/google_search"
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\n \"searchKey\": \"{{query}}\"\n}",
"label": "",
"required": false
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "原始响应",
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。",
"valueType": "any",
"type": "static"
},
{
"id": "M5YmxaYe8em1",
"type": "dynamic",
"key": "prompt",
"valueType": "string",
"label": "prompt"
}
]
}
],
"edges": [
{
"source": "448745",
"target": "NOgbnBzUwDgT",
"sourceHandle": "448745-source-right",
"targetHandle": "NOgbnBzUwDgT-target-left"
},
{
"source": "NOgbnBzUwDgT",
"target": "GMELVPxHfpg5",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
}
]
}
```
</details>
## 模块编排 - 非工具调用方式
复制下面配置,进入「高级编排」,在右上角的 “...” 中选择「导入配置」,导入后修改「HTTP 请求」模块 - 请求地址 的值。
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": 126.6166221945532,
"y": -456.00079128406236
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "流程开始",
"intro": "",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 189.99351048246606,
"y": 50.36949968375285
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "TWD5BAqIIFaj",
"name": "判断器",
"intro": "根据一定的条件,执行不同的分支。",
"avatar": "/imgs/workflow/ifElse.svg",
"flowNodeType": "ifElseNode",
"showStatus": true,
"position": {
"x": 1187.4821088468154,
"y": -143.83989103517257
},
"inputs": [
{
"key": "condition",
"valueType": "string",
"label": "",
"renderTypeList": [
"hidden"
],
"required": false,
"value": "And"
},
{
"key": "ifElseList",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": [
{
"variable": [
"lG52GzzMm65z",
"6yF19MRD3nuB"
],
"condition": "isEmpty",
"value": ""
}
]
}
],
"outputs": [
{
"id": "IF",
"key": "IF",
"label": "IF",
"valueType": "any",
"type": "source"
},
{
"id": "ELSE",
"key": "ELSE",
"label": "ELSE",
"valueType": "any",
"type": "source"
}
]
},
{
"nodeId": "1ljV0oTq4zeC",
"name": "HTTP 请求",
"intro": "可以发出一个 HTTP 请求,实现更为复杂的操作(联网搜索、数据库查询等)",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1992.0328696814468,
"y": 127.08080019458595
},
"inputs": [
{
"key": "DYNAMIC_INPUT_KEY",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
},
{
"key": "searchKey",
"valueType": "string",
"label": "searchKey",
"renderTypeList": [
"reference"
],
"description": "",
"canEdit": true,
"editField": {
"key": true,
"valueType": true
},
"value": [
"lG52GzzMm65z",
"6yF19MRD3nuB"
]
},
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"value": "https://xxxxxx.laf.dev/google_search"
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\n \"searchKey\": \"{{searchKey}}\"\n}",
"label": "",
"required": false
},
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
}
],
"outputs": [
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "httpRawResponse",
"key": "httpRawResponse",
"label": "原始响应",
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。",
"valueType": "any",
"type": "static"
},
{
"id": "yw0oz9XWFXYf",
"type": "dynamic",
"key": "prompt",
"valueType": "string",
"label": "prompt"
}
]
},
{
"nodeId": "Nc6hBdb3l9Pe",
"name": "AI 对话",
"intro": "AI 大模型对话",
"avatar": "/imgs/workflow/AI.png",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 1982.442841318768,
"y": -664.9716343803625
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": true,
"valueType": "boolean"
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"selectedTypeIndex": 1,
"value": [
"1ljV0oTq4zeC",
"httpRawResponse"
]
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题",
"value": [
"448745",
"userChatInput"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "",
"valueType": "datasetQuote"
}
],
"outputs": [
{
"id": "history",
"key": "history",
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context",
"valueType": "chatHistory",
"type": "static"
},
{
"id": "answerText",
"key": "answerText",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "FYLw1BokYUad",
"name": "文本加工",
"intro": "可对固定或传入的文本进行加工后输出,非字符串类型数据最终会转成字符串类型。",
"avatar": "/imgs/workflow/textEditor.svg",
"flowNodeType": "pluginModule",
"showStatus": false,
"position": {
"x": 2479.5913201989906,
"y": 288.52613614690904
},
"inputs": [
{
"key": "system_addInputParam",
"valueType": "dynamic",
"label": "动态外部数据",
"renderTypeList": [
"addInputParam"
],
"required": false,
"description": "",
"canEdit": false,
"value": "",
"editField": {
"key": true
},
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
},
{
"key": "q",
"valueType": "string",
"label": "q",
"renderTypeList": [
"reference"
],
"required": true,
"description": "",
"canEdit": true,
"editField": {
"key": true
},
"value": [
"448745",
"userChatInput"
]
},
{
"key": "response",
"valueType": "string",
"label": "response",
"renderTypeList": [
"reference"
],
"required": true,
"description": "",
"canEdit": true,
"editField": {
"key": true
},
"value": [
"1ljV0oTq4zeC",
"yw0oz9XWFXYf"
]
},
{
"key": "文本",
"valueType": "string",
"label": "文本",
"renderTypeList": [
"textarea"
],
"required": true,
"description": "",
"canEdit": false,
"value": "请使用下面<data> </data>中的数据作为本次对话的参考。请直接输出答案,不要提及你是从<data> </data>中获取的知识。\n\n当前时间:{{cTime}}\n\n<data>\n{{response}}\n</data>\n\n我的问题:\"{{q}}\"",
"editField": {
"key": true
},
"maxLength": "",
"dynamicParamDefaultValue": {
"inputType": "reference",
"valueType": "string",
"required": true
}
}
],
"outputs": [
{
"id": "text",
"type": "static",
"key": "text",
"valueType": "string",
"label": "text",
"description": ""
}
],
"pluginId": "community-textEditor"
},
{
"nodeId": "EX0g9oK3sCOC",
"name": "AI 对话",
"intro": "AI 大模型对话",
"avatar": "/imgs/workflow/AI.png",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 3199.17223136331,
"y": -100.06379812849427
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": true,
"valueType": "boolean"
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题",
"value": [
"FYLw1BokYUad",
"text"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "",
"valueType": "datasetQuote"
}
],
"outputs": [
{
"id": "history",
"key": "history",
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context",
"valueType": "chatHistory",
"type": "static"
},
{
"id": "answerText",
"key": "answerText",
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "lG52GzzMm65z",
"name": "文本内容提取",
"intro": "可从文本中提取指定的数据,例如:sql语句、搜索关键词、代码等",
"avatar": "/imgs/workflow/extract.png",
"flowNodeType": "contentExtract",
"showStatus": true,
"position": {
"x": 535.331344778598,
"y": -437.1382636373696
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"selectLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"required": true,
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "description",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "string",
"label": "提取要求描述",
"description": "给AI一些对应的背景知识或要求描述,引导AI更好的完成任务。\n该输入框可使用全局变量。",
"placeholder": "例如: \n1. 当前时间为: {{cTime}}。你是一个实验室预约助手,你的任务是帮助用户预约实验室,从文本中获取对应的预约信息。\n2. 你是谷歌搜索助手,需要从文本中提取出合适的搜索词。",
"value": "你是谷歌搜索机器人,根据当前问题和对话记录生成搜索词。你需要自行判断是否需要进行网络实时查询:\n- 如果需查询则生成搜索词。\n- 如果不需要查询则不返回字段。"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "content",
"renderTypeList": [
"reference",
"textarea"
],
"label": "需要提取的文本",
"required": true,
"valueType": "string",
"toolDescription": "需要检索的内容",
"value": [
"448745",
"userChatInput"
]
},
{
"key": "extractKeys",
"renderTypeList": [
"custom"
],
"label": "",
"valueType": "any",
"description": "由 '描述' 和 'key' 组成一个目标字段,可提取多个目标字段",
"value": [
{
"required": false,
"defaultValue": "",
"desc": "搜索词",
"key": "searchKey",
"enum": ""
}
]
}
],
"outputs": [
{
"id": "fields",
"key": "fields",
"label": "完整提取结果",
"description": "一个 JSON 字符串,例如:{\"name:\":\"YY\",\"Time\":\"2023/7/2 18:00\"}",
"valueType": "string",
"type": "static"
},
{
"id": "6yF19MRD3nuB",
"key": "searchKey",
"label": "提取结果-搜索词",
"valueType": "string",
"type": "static"
}
]
}
],
"edges": [
{
"source": "TWD5BAqIIFaj",
"target": "Nc6hBdb3l9Pe",
"sourceHandle": "TWD5BAqIIFaj-source-IF",
"targetHandle": "Nc6hBdb3l9Pe-target-left"
},
{
"source": "1ljV0oTq4zeC",
"target": "FYLw1BokYUad",
"sourceHandle": "1ljV0oTq4zeC-source-right",
"targetHandle": "FYLw1BokYUad-target-left"
},
{
"source": "FYLw1BokYUad",
"target": "EX0g9oK3sCOC",
"sourceHandle": "FYLw1BokYUad-source-right",
"targetHandle": "EX0g9oK3sCOC-target-left"
},
{
"source": "448745",
"target": "lG52GzzMm65z",
"sourceHandle": "448745-source-right",
"targetHandle": "lG52GzzMm65z-target-left"
},
{
"source": "lG52GzzMm65z",
"target": "TWD5BAqIIFaj",
"sourceHandle": "lG52GzzMm65z-source-right",
"targetHandle": "TWD5BAqIIFaj-target-left"
},
{
"source": "TWD5BAqIIFaj",
"target": "1ljV0oTq4zeC",
"sourceHandle": "TWD5BAqIIFaj-source-ELSE",
"targetHandle": "1ljV0oTq4zeC-target-left"
}
]
}
```
</details>
### 流程说明
1. 利用【文本内容提取】模块,将用户的问题提取成搜索关键词。
2. 将搜索关键词传入【HTTP请求】模块,执行谷歌搜索。
3. 利用【文本加工】模块组合搜索结果和问题,生成一个适合模型回答的问题。
4. 将新的问题发给【AI对话】模块,回答搜索结果。
---
title: Lab Appointment System
description: Demonstrates advanced workflow capabilities for database operations
---
import { Alert } from '@/components/docs/Alert';
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/demo-appointment1.webp) | ![](../../../public/imgs/demo-appointment2.webp) |
| ![](../../../public/imgs/demo-appointment3.webp) | ![](../../../public/imgs/demo-appointment4.webp) |
This example demonstrates using tool calls to automatically choose between searching the knowledge base for lab information or calling HTTP modules to perform database CRUD operations.
Using a lab appointment system as an example, users can book, cancel, modify, and query appointments through a conversational interface.
## 1. Using Global Variables
Design a global variable for users to input their name, simulating user identity. In production, you'd typically use embedded tokens to identify users.
## 2. Tool Calling
![](../../../public/imgs/demo-appointment5.png)
In the background knowledge, guide the model to call tools for different operations.
<Alert icon="🤗" context="success">
**Tips:** Add appropriate context here so the model can make decisions based on conversation history.
</Alert>
## 3. HTTP Module
![](../../../public/imgs/demo-appointment6.jpg)
The HTTP module requires 3 tool parameters:
- Appointment action: Can be get, put, post, or delete, corresponding to query, modify, create, and delete operations. You could also create 4 separate HTTP modules to handle each action.
- labname: Lab name. Optional, since it's not needed for queries and deletions.
- time: Appointment time.
# Summary
1. The tool calling module is incredibly powerful and can largely replace question classification and content extraction.
2. By dynamically calling different tools through the tool module, you can decouple complex business logic.
# Attachments
## Workflow Configuration
Copy and import directly into FastGPT.
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "userChatInput",
"name": "流程开始",
"intro": "当用户发送一个内容后,流程将会从这个模块开始执行。",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 309.7143912167367,
"y": 1501.2761754220846
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "systemInput",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0,
"value": [
"userChatInput",
"userChatInput"
]
}
],
"outputs": [
{
"id": "userChatInput",
"type": "static",
"key": "userChatInput",
"valueType": "string",
"label": "core.module.input.label.user question"
}
]
},
{
"nodeId": "eg5upi",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1962.729630445213,
"y": 2295.9791334948304
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 1,
"value": [
"40clf3",
"result"
]
}
],
"outputs": []
},
{
"nodeId": "kge59i",
"name": "用户引导",
"intro": "可以配置应用的系统参数。",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": -327.218389965887,
"y": 1504.8056414948464
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "你好,我是实验室助手,请问有什么可以帮助你的么?如需预约或修改预约实验室,请提供姓名、时间和实验室名称。\\n[实验室介绍]\\n[开放时间]\\n[预约]",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.module.Variable",
"value": [
{
"id": "gt9b23",
"key": "name",
"label": "name",
"type": "input",
"required": true,
"maxLen": 50,
"enums": [
{
"value": ""
}
]
}
],
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "",
"type": "switch",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": {
"type": "model",
"model": "tts-1",
"voice": "alloy"
},
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "40clf3",
"name": "HTTP请求",
"intro": "可以发出一个 HTTP 请求,实现更为复杂的操作(联网搜索、数据库查询等)",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1118.6532653446993,
"y": 1955.886106913907
},
"inputs": [
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true,
"type": "custom",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "action",
"label": "action",
"toolDescription": "预约行为,一共四种:\\nget - 查询预约情况\\nput - 更新预约\\npost - 新增预约\\ndelete - 删除预约",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "labname",
"label": "labname",
"toolDescription": "实验室名称",
"required": false,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "time",
"label": "time",
"toolDescription": "预约时间,按 YYYY/MM/DD HH:mm 格式返回",
"required": false,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "https://d8dns0.laf.dev/appointment-lab",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false,
"type": "custom",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\\r\\n \\\"name\\\": \\\"{{name}}\\\",\\r\\n \\\"time\\\": \\\"{{time}}\\\",\\r\\n \\\"labname\\\": \\\"{{labname}}\\\",\\r\\n \\\"action\\\": \\\"{{action}}\\\"\\r\\n}",
"label": "",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
}
],
"outputs": [
{
"id": "system_addOutputParam",
"type": "dynamic",
"key": "system_addOutputParam",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "result",
"type": "static",
"key": "result",
"valueType": "string",
"label": "result",
"description": "result",
"canEdit": true,
"editField": {
"key": true,
"name": true,
"description": true,
"dataType": true
}
},
{
"id": "httpRawResponse",
"type": "static",
"key": "httpRawResponse",
"valueType": "any",
"label": "原始响应",
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。"
}
]
},
{
"nodeId": "fYxwWym8flYL",
"name": "工具调用",
"intro": "通过AI模型自动选择一个或多个功能块进行调用,也可以对插件进行调用。",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 933.9342354248961,
"y": 1229.3563445150553
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "当前时间为: {{cTime}}\\n你是实验室助手,用户可能会询问实验室相关介绍或预约实验室。\\n请选择合适的工具去帮助他们。"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"value": [
"userChatInput",
"userChatInput"
]
}
],
"outputs": []
},
{
"nodeId": "JSSQtDgwmmbE",
"name": "知识库搜索",
"intro": "调用"语义检索"和"全文检索"能力,从"知识库"中查找实验室介绍和使用规则等信息。",
"avatar": "/imgs/workflow/db.png",
"flowNodeType": "datasetSearchNode",
"showStatus": true,
"position": {
"x": 447.0795498711184,
"y": 1971.5311041711186
},
"inputs": [
{
"key": "datasets",
"renderTypeList": [
"selectDataset",
"reference"
],
"label": "core.module.input.label.Select dataset",
"value": [],
"valueType": "selectDataset",
"list": [],
"required": true
},
{
"key": "similarity",
"renderTypeList": [
"selectDatasetParamsModal"
],
"label": "",
"value": 0.4,
"valueType": "number"
},
{
"key": "limit",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 1500,
"valueType": "number"
},
{
"key": "searchMode",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": "embedding"
},
{
"key": "usingReRank",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "boolean",
"value": false
},
{
"key": "datasetSearchUsingExtensionQuery",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "boolean",
"value": false
},
{
"key": "datasetSearchExtensionModel",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "datasetSearchExtensionBg",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": ""
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "需要检索的内容"
}
],
"outputs": [
{
"id": "quoteQA",
"key": "quoteQA",
"label": "core.module.Dataset quote.label",
"description": "特殊数组格式,搜索结果为空时,返回空数组。",
"type": "static",
"valueType": "datasetQuote"
}
]
},
{
"nodeId": "IdntVQiTopHT",
"name": "工具调用终止",
"intro": "该模块需配置工具调用使用。当该模块被执行时,本次工具调用将会强制结束,并且不再调用AI针对工具调用结果回答问题。",
"avatar": "/imgs/workflow/toolStop.svg",
"flowNodeType": "stopTool",
"position": {
"x": 1969.73331750207,
"y": 2650.0258908119413
},
"inputs": [],
"outputs": []
}
],
"edges": [
{
"source": "40clf3",
"target": "eg5upi",
"sourceHandle": "40clf3-source-right",
"targetHandle": "eg5upi-target-left"
},
{
"source": "userChatInput",
"target": "fYxwWym8flYL",
"sourceHandle": "userChatInput-source-right",
"targetHandle": "fYxwWym8flYL-target-left"
},
{
"source": "fYxwWym8flYL",
"target": "40clf3",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "fYxwWym8flYL",
"target": "JSSQtDgwmmbE",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "40clf3",
"target": "IdntVQiTopHT",
"sourceHandle": "40clf3-source-right",
"targetHandle": "IdntVQiTopHT-target-left"
}
]
}
```
</details>
## Laf Cloud Function Code
You can quickly build HTTP endpoints in [Laf](https://laf.dev/).
<details>
<summary>Function Code</summary>
```ts
import cloud from '@lafjs/cloud'
const db = cloud.database()
type RequestType = {
name: string;
time?: string;
labname?: string;
action: 'post' | 'delete' | 'put' | 'get'
}
export default async function (ctx: FunctionContext) {
try {
const { action,...body } = ctx.body as RequestType
if (action === 'get') {
return await getRecord(ctx.body)
}
if (action === 'post') {
return await createRecord(ctx.body)
}
if (action === 'put') {
return await putRecord(ctx.body)
}
if (action === 'delete') {
return await removeRecord(ctx.body)
}
return {
result: "异常"
}
} catch (err) {
return {
result: "异常"
}
}
}
async function putRecord({ name, time, labname }: RequestType) {
const missData = []
if (!name) missData.push("你的姓名")
if (missData.length > 0) {
return {
result: `请提供: ${missData.join("、")}`
}
}
const { data: record } = await db.collection("LabAppointment").where({
name, status: "unStart"
}).getOne()
if (!record) {
return {
result: `${name} 还没有预约记录`
}
}
const updateWhere = {
name,
time: time || record.time,
labname: labname || record.labname
}
await db.collection("LabAppointment").where({
name, status: "unStart"
}).update(updateWhere)
return {
result: `修改预约成功。
姓名:${name}·
时间: ${updateWhere.time}
实验室名: ${updateWhere.labname}
` }
}
async function getRecord({ name }: RequestType) {
if (!name) {
return {
result: "请提供你的姓名"
}
}
const { data } = await db.collection('LabAppointment').where({ name, status: "unStart" }).getOne()
if (!data) {
return {
result: `${name} 没有预约中的记录`
}
}
return {
result: `${name} 有一条预约记录:
姓名:${data.name}
时间: ${data.time}
实验室名: ${data.labname}
`
}
}
async function removeRecord({ name }: RequestType) {
if (!name) {
return {
result: "请提供你的姓名"
}
}
const { deleted } = await db.collection('LabAppointment').where({ name, status: "unStart" }).remove()
if (deleted > 0) {
return {
result: `取消预约记录成功: ${name}`
}
}
return {
result: ` ${name} 没有预约中的记录`
}
}
async function createRecord({ name, time, labname }: RequestType) {
const missData = []
if (!name) missData.push("你的姓名")
if (!time) missData.push("需要预约的时间")
if (!labname) missData.push("实验室名名称")
if (missData.length > 0) {
return {
result: `请提供: ${missData.join("、")}`
}
}
const { data: record } = await db.collection("LabAppointment").where({
name, status: "unStart"
}).getOne()
if (record) {
return {
result: `您已经有一个预约记录了:
姓名:${record.name}
时间: ${record.time}
实验室名: ${record.labname}
每人仅能同时预约一个实验室名。
`
}
}
await db.collection("LabAppointment").add({
name, time, labname, status: "unStart"
})
return {
result: `预约成功。
姓名:${name}
时间: ${time}
实验室名: ${labname}
` }
}
```
</details>
---
title: 实验室预约
description: 展示高级编排操作数据库的能力
---
import { Alert } from '@/components/docs/Alert';
| | |
| --------------------- | --------------------- |
| ![](../../../public/imgs/demo-appointment1.webp) | ![](../../../public/imgs/demo-appointment2.webp) |
| ![](../../../public/imgs/demo-appointment3.webp) | ![](../../../public/imgs/demo-appointment4.webp) |
本示例演示了利用工具调用,自动选择调用知识库搜索实验室相关内容,或调用 HTTP 模块实现数据库的 CRUD 操作。
以一个实验室预约为例,用户可以通过对话系统预约、取消、修改预约和查询预约记录。
## 1. 全局变量使用
通过设计一个全局变量,让用户输入姓名,模拟用户身份信息。实际使用过程中,通常是直接通过嵌入 Token 来标记用户身份。
## 2. 工具调用
![](../../../public/imgs/demo-appointment5.png)
背景知识中,引导模型调用工具去执行不通的操作。
<Alert icon="🤗" context="success">
**Tips:** 这里需要增加适当的上下文,方便模型结合历史记录进行判断和决策~
</Alert>
## 3. HTTP 模块
![](../../../public/imgs/demo-appointment6.jpg)
HTTP模块中,需要设置 3 个工具参数:
- 预约行为:可取 get, put, post, delete 四个值,分别对应查询、修改、新增、删除操作。当然,你也可以写4个HTTP模块,来分别处理。
- labname: 实验室名。非必填,因为查询和删除时候,不需要。
- time: 预约时间。
# 总结
1. 工具调用模块是非常强大的功能,可以在一定程度上替代问题分类和内容提取。
2. 通过工具模块,动态的调用不同的工具,可以将复杂业务解耦。
# 附件
## 编排配置
可直接复制,导入到 FastGPT 中。
<details>
<summary>编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userChatInput",
"name": "流程开始",
"intro": "当用户发送一个内容后,流程将会从这个模块开始执行。",
"avatar": "/imgs/workflow/userChatInput.svg",
"flowNodeType": "workflowStart",
"position": {
"x": 309.7143912167367,
"y": 1501.2761754220846
},
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "问题输入",
"required": true,
"toolDescription": "用户问题",
"type": "systemInput",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0,
"value": [
"userChatInput",
"userChatInput"
]
}
],
"outputs": [
{
"id": "userChatInput",
"type": "static",
"key": "userChatInput",
"valueType": "string",
"label": "core.module.input.label.user question"
}
]
},
{
"nodeId": "eg5upi",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "/imgs/workflow/reply.png",
"flowNodeType": "answerNode",
"position": {
"x": 1962.729630445213,
"y": 2295.9791334948304
},
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"type": "textarea",
"showTargetInApp": true,
"showTargetInPlugin": true,
"connected": true,
"selectedTypeIndex": 1,
"value": [
"40clf3",
"result"
]
}
],
"outputs": []
},
{
"nodeId": "kge59i",
"name": "用户引导",
"intro": "可以配置应用的系统参数。",
"avatar": "/imgs/workflow/userGuide.png",
"flowNodeType": "userGuide",
"position": {
"x": -327.218389965887,
"y": 1504.8056414948464
},
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "你好,我是实验室助手,请问有什么可以帮助你的么?如需预约或修改预约实验室,请提供姓名、时间和实验室名称。\n[实验室介绍]\n[开放时间]\n[预约]",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.module.Variable",
"value": [
{
"id": "gt9b23",
"key": "name",
"label": "name",
"type": "input",
"required": true,
"maxLen": 50,
"enums": [
{
"value": ""
}
]
}
],
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "",
"type": "switch",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": {
"type": "model",
"model": "tts-1",
"voice": "alloy"
},
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "40clf3",
"name": "HTTP请求",
"intro": "可以发出一个 HTTP 请求,实现更为复杂的操作(联网搜索、数据库查询等)",
"avatar": "/imgs/workflow/http.png",
"flowNodeType": "httpRequest468",
"showStatus": true,
"position": {
"x": 1118.6532653446993,
"y": 1955.886106913907
},
"inputs": [
{
"key": "system_httpMethod",
"renderTypeList": [
"custom"
],
"valueType": "string",
"label": "",
"value": "POST",
"required": true,
"type": "custom",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "action",
"label": "action",
"toolDescription": "预约行为,一共四种:\nget - 查询预约情况\nput - 更新预约\npost - 新增预约\ndelete - 删除预约",
"required": true,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "labname",
"label": "labname",
"toolDescription": "实验室名称",
"required": false,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"valueType": "string",
"renderTypeList": [
"reference"
],
"key": "time",
"label": "time",
"toolDescription": "预约时间,按 YYYY/MM/DD HH:mm 格式返回",
"required": false,
"canEdit": true,
"editField": {
"key": true,
"description": true
}
},
{
"key": "system_httpReqUrl",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "",
"description": "core.module.input.description.Http Request Url",
"placeholder": "https://api.ai.com/getInventory",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"value": "https://d8dns0.laf.dev/appointment-lab",
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpHeader",
"renderTypeList": [
"custom"
],
"valueType": "any",
"value": [],
"label": "",
"description": "core.module.input.description.Http Request Header",
"placeholder": "core.module.input.description.Http Request Header",
"required": false,
"type": "custom",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpParams",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": [],
"label": "",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_httpJsonBody",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"value": "{\r\n \"name\": \"{{name}}\",\r\n \"time\": \"{{time}}\",\r\n \"labname\": \"{{labname}}\",\r\n \"action\": \"{{action}}\"\r\n}",
"label": "",
"required": false,
"type": "hidden",
"showTargetInApp": false,
"showTargetInPlugin": false,
"connected": false,
"selectedTypeIndex": 0
},
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "core.module.input.description.HTTP Dynamic Input",
"editField": {
"key": true,
"valueType": true
}
}
],
"outputs": [
{
"id": "system_addOutputParam",
"type": "dynamic",
"key": "system_addOutputParam",
"valueType": "dynamic",
"label": "",
"editField": {
"key": true,
"valueType": true
}
},
{
"id": "result",
"type": "static",
"key": "result",
"valueType": "string",
"label": "result",
"description": "result",
"canEdit": true,
"editField": {
"key": true,
"name": true,
"description": true,
"dataType": true
}
},
{
"id": "httpRawResponse",
"type": "static",
"key": "httpRawResponse",
"valueType": "any",
"label": "原始响应",
"description": "HTTP请求的原始响应。只能接受字符串或JSON类型响应数据。"
}
]
},
{
"nodeId": "fYxwWym8flYL",
"name": "工具调用",
"intro": "通过AI模型自动选择一个或多个功能块进行调用,也可以对插件进行调用。",
"avatar": "/imgs/workflow/tool.svg",
"flowNodeType": "tools",
"showStatus": true,
"position": {
"x": 933.9342354248961,
"y": 1229.3563445150553
},
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 0,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 2000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "当前时间为: {{cTime}}\n你是实验室助手,用户可能会询问实验室相关介绍或预约实验室。\n请选择合适的工具去帮助他们。"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"required": true,
"min": 0,
"max": 30,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"value": [
"userChatInput",
"userChatInput"
]
}
],
"outputs": []
},
{
"nodeId": "JSSQtDgwmmbE",
"name": "知识库搜索",
"intro": "调用“语义检索”和“全文检索”能力,从“知识库”中查找实验室介绍和使用规则等信息。",
"avatar": "/imgs/workflow/db.png",
"flowNodeType": "datasetSearchNode",
"showStatus": true,
"position": {
"x": 447.0795498711184,
"y": 1971.5311041711186
},
"inputs": [
{
"key": "datasets",
"renderTypeList": [
"selectDataset",
"reference"
],
"label": "core.module.input.label.Select dataset",
"value": [],
"valueType": "selectDataset",
"list": [],
"required": true
},
{
"key": "similarity",
"renderTypeList": [
"selectDatasetParamsModal"
],
"label": "",
"value": 0.4,
"valueType": "number"
},
{
"key": "limit",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 1500,
"valueType": "number"
},
{
"key": "searchMode",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": "embedding"
},
{
"key": "usingReRank",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "boolean",
"value": false
},
{
"key": "datasetSearchUsingExtensionQuery",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "boolean",
"value": false
},
{
"key": "datasetSearchExtensionModel",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": "gpt-3.5-turbo"
},
{
"key": "datasetSearchExtensionBg",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string",
"value": ""
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "需要检索的内容"
}
],
"outputs": [
{
"id": "quoteQA",
"key": "quoteQA",
"label": "core.module.Dataset quote.label",
"description": "特殊数组格式,搜索结果为空时,返回空数组。",
"type": "static",
"valueType": "datasetQuote"
}
]
},
{
"nodeId": "IdntVQiTopHT",
"name": "工具调用终止",
"intro": "该模块需配置工具调用使用。当该模块被执行时,本次工具调用将会强制结束,并且不再调用AI针对工具调用结果回答问题。",
"avatar": "/imgs/workflow/toolStop.svg",
"flowNodeType": "stopTool",
"position": {
"x": 1969.73331750207,
"y": 2650.0258908119413
},
"inputs": [],
"outputs": []
}
],
"edges": [
{
"source": "40clf3",
"target": "eg5upi",
"sourceHandle": "40clf3-source-right",
"targetHandle": "eg5upi-target-left"
},
{
"source": "userChatInput",
"target": "fYxwWym8flYL",
"sourceHandle": "userChatInput-source-right",
"targetHandle": "fYxwWym8flYL-target-left"
},
{
"source": "fYxwWym8flYL",
"target": "40clf3",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "fYxwWym8flYL",
"target": "JSSQtDgwmmbE",
"sourceHandle": "selectedTools",
"targetHandle": "selectedTools"
},
{
"source": "40clf3",
"target": "IdntVQiTopHT",
"sourceHandle": "40clf3-source-right",
"targetHandle": "IdntVQiTopHT-target-left"
}
]
}
```
</details>
## Laf 云函数代码
可以在 [Laf](https://laf.dev/) 中快速构建 HTTP 接口。
<details>
<summary>函数代码</summary>
```ts
import cloud from '@lafjs/cloud'
const db = cloud.database()
type RequestType = {
name: string;
time?: string;
labname?: string;
action: 'post' | 'delete' | 'put' | 'get'
}
export default async function (ctx: FunctionContext) {
try {
const { action,...body } = ctx.body as RequestType
if (action === 'get') {
return await getRecord(ctx.body)
}
if (action === 'post') {
return await createRecord(ctx.body)
}
if (action === 'put') {
return await putRecord(ctx.body)
}
if (action === 'delete') {
return await removeRecord(ctx.body)
}
return {
result: "异常"
}
} catch (err) {
return {
result: "异常"
}
}
}
async function putRecord({ name, time, labname }: RequestType) {
const missData = []
if (!name) missData.push("你的姓名")
if (missData.length > 0) {
return {
result: `请提供: ${missData.join("、")}`
}
}
const { data: record } = await db.collection("LabAppointment").where({
name, status: "unStart"
}).getOne()
if (!record) {
return {
result: `${name} 还没有预约记录`
}
}
const updateWhere = {
name,
time: time || record.time,
labname: labname || record.labname
}
await db.collection("LabAppointment").where({
name, status: "unStart"
}).update(updateWhere)
return {
result: `修改预约成功。
姓名:${name}·
时间: ${updateWhere.time}
实验室名: ${updateWhere.labname}
` }
}
async function getRecord({ name }: RequestType) {
if (!name) {
return {
result: "请提供你的姓名"
}
}
const { data } = await db.collection('LabAppointment').where({ name, status: "unStart" }).getOne()
if (!data) {
return {
result: `${name} 没有预约中的记录`
}
}
return {
result: `${name} 有一条预约记录:
姓名:${data.name}
时间: ${data.time}
实验室名: ${data.labname}
`
}
}
async function removeRecord({ name }: RequestType) {
if (!name) {
return {
result: "请提供你的姓名"
}
}
const { deleted } = await db.collection('LabAppointment').where({ name, status: "unStart" }).remove()
if (deleted > 0) {
return {
result: `取消预约记录成功: ${name}`
}
}
return {
result: ` ${name} 没有预约中的记录`
}
}
async function createRecord({ name, time, labname }: RequestType) {
const missData = []
if (!name) missData.push("你的姓名")
if (!time) missData.push("需要预约的时间")
if (!labname) missData.push("实验室名名称")
if (missData.length > 0) {
return {
result: `请提供: ${missData.join("、")}`
}
}
const { data: record } = await db.collection("LabAppointment").where({
name, status: "unStart"
}).getOne()
if (record) {
return {
result: `您已经有一个预约记录了:
姓名:${record.name}
时间: ${record.time}
实验室名: ${record.labname}
每人仅能同时预约一个实验室名。
`
}
}
await db.collection("LabAppointment").add({
name, time, labname, status: "unStart"
})
return {
result: `预约成功。
姓名:${name}
时间: ${time}
实验室名: ${labname}
` }
}
```
</details>
{
"title": "Application Building Cases",
"description": "FastGPT application scenarios and feature implementation building cases",
"pages": [
"submit_application_template",
"translate-subtitle-using-gpt",
"multi_turn_translation_bot",
"english_essay_correction_bot",
"fixingEvidence",
"lab_appointment",
"dalle3",
"google_search",
"feishu_webhook"
]
}
{
"title": "应用搭建案例",
"description": "FastGPT 应用场景及功能实现的搭建案例",
"pages": ["submit_application_template","translate-subtitle-using-gpt","multi_turn_translation_bot","english_essay_correction_bot","fixingEvidence","lab_appointment","dalle3","google_search","feishu_webhook"]
}
\ No newline at end of file
---
title: Multi-turn Translation Bot
description: How to use FastGPT to build a multi-turn translation bot with continuous conversation translation functionality
---
Professor Andrew Ng proposed a reflective translation workflow for large language models (LLM)—[GitHub - andrewyng/translation-agent](https://github.com/andrewyng/translation-agent). The workflow is as follows:
1. Prompt an LLM to translate text from `source_language` to `target_language`;
2. Have the LLM reflect on the translation and provide constructive improvement suggestions;
3. Use these suggestions to improve the translation.
This translation process is a relatively new approach that uses LLM self-reflection to achieve better translation results.
The project demonstrates how to chunk long texts and process each chunk with reflective translation, breaking through LLM token limits to achieve efficient, high-quality translation of long texts.
The project also achieves more precise translation by specifying regions (e.g., American English vs. British English) and proposes optimizations like creating glossaries for terms the LLM hasn't trained on, further improving translation accuracy.
All of this can be easily implemented through Fastgpt workflows. This article will guide you step-by-step on how to replicate Professor Andrew Ng's translation-agent.
# Single Text Block Reflective Translation
Let's start simple—translating a single text block that doesn't exceed LLM token limits.
## Initial Translation
First, have the LLM perform an initial translation of the source text block (translation prompts are available in the source project).
![](../../../public/imgs/translate1.png)
Use the `Text Concatenation` module to reference three parameters: source language, target language, and source text. Generate a prompt and pass it to the LLM for the first translation version.
## Reflection
Then have the LLM provide modification suggestions for the initial translation—this is called reflection.
![](../../../public/imgs/translate2.png)
The prompt now receives 5 parameters: source text, initial translation, source language, target language, and regional constraints. The LLM will provide numerous modification suggestions to prepare for translation improvement.
## Improved Translation
![](../../../public/imgs/translate3.png)
After generating the initial translation and reflection, input both into a third LLM translation to get a high-quality translation result.
The complete workflow is as follows:
![](../../../public/imgs/translate4.png)
## Results
Considering future reuse of this reflective translation, I created a plugin. Below, I directly call this plugin to use reflective translation. Results:
Randomly selected a Harry Potter passage:
![](../../../public/imgs/translate5.png)
![](../../../public/imgs/translate61.png)
The reflective translation shows significant improvement. The reflection output:
![](../../../public/imgs/translate7.png)
# Long Text Reflective Translation
After mastering short text block reflective translation, we can easily implement long text (multiple text blocks) reflective translation through chunking and looping.
The overall logic: First, check the token count of the input text. If it doesn't exceed the token limit, directly call single text block reflective translation. If it exceeds the limit, split it into reasonable sizes and process each with reflective translation.
## Calculate Tokens
![](../../../public/imgs/translate8.png)
First, I used the Laf function module to calculate tokens for the input text.
Laf functions are simple to use—just create an application in laf, install the tiktoken dependency, and import this code:
```typescript
const { Tiktoken } = require("tiktoken/lite");
const cl100k_base = require("tiktoken/encoders/cl100k_base.json");
interface IRequestBody {
str: string
}
interface RequestProps extends IRequestBody {
systemParams: {
appId: string,
variables: string,
histories: string,
cTime: string,
chatId: string,
responseChatItemId: string
}
}
interface IResponse {
message: string;
tokens: number;
}
export default async function (ctx: FunctionContext): Promise<IResponse> {
const { str = "" }: RequestProps = ctx.body
const encoding = new Tiktoken(
cl100k_base.bpe_ranks,
cl100k_base.special_tokens,
cl100k_base.pat_str
);
const tokens = encoding.encode(str);
encoding.free();
return {
message: 'ok',
tokens: tokens.length
};
}
```
Back in Fastgpt, click "Sync Parameters", connect the source text, and you can calculate token count.
## Calculate Single Text Block Size
![](../../../public/imgs/translate9.png)
Since no third-party packages are involved—just data processing—use the Code Execution module directly:
```typescript
function main({tokenCount, tokenLimit}){
const numChunks = Math.ceil(tokenCount / tokenLimit);
let chunkSize = Math.floor(tokenCount / numChunks);
const remainingTokens = tokenCount % tokenLimit;
if (remainingTokens > 0) {
chunkSize += Math.floor(remainingTokens / numChunks);
}
return {chunkSize};
}
```
This code calculates a reasonable single text block size that doesn't exceed the token limit.
## Get Split Source Text Blocks
![](../../../public/imgs/translate10.png)
Using the single text block size and source text, write a function calling langchain's textsplitters package to implement text chunking:
```typescript
import cloud from '@lafjs/cloud'
import { TokenTextSplitter } from "@langchain/textsplitters";
interface IRequestBody {
text: string
chunkSize: number
}
interface RequestProps extends IRequestBody {
systemParams: {
appId: string,
variables: string,
histories: string,
cTime: string,
chatId: string,
responseChatItemId: string
}
}
interface IResponse {
output: string[];
}
export default async function (ctx: FunctionContext): Promise<IResponse>{
const { text = '', chunkSize=1000 }: RequestProps = ctx.body;
const splitter = new TokenTextSplitter({
encodingName:"gpt2",
chunkSize: Number(chunkSize),
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
return {
output
}
}
```
Now we have the split text. The next operations are similar to single text block reflective translation.
## Multiple Text Block Translation
You can't directly call the previous single text block reflective translation here because the prompts involve context handling (or you can modify the plugin to pass more parameters).
The details are similar to before—just replace some prompts and do simple data processing. Overall effect:
### Multiple Text Block Initial Translation
![](../../../public/imgs/translate11.png)
### Multiple Text Block Reflection
![](../../../public/imgs/translate12.png)
### Multiple Text Block Improved Translation
![](../../../public/imgs/translate13.png)
## Batch Execution
A key part of long text reflective translation is looping through multiple text blocks for reflective translation.
Fastgpt provides workflow loop functionality, so we can write a simple judgment function to determine whether to end or continue:
![](../../../public/imgs/translate14.png)
By checking if the current text block is the last one, we determine whether to continue execution. This achieves long text reflective translation.
Complete workflow:
![](../../../public/imgs/translate15.png)
## Results
First, input global settings:
![](../../../public/imgs/translate16.png)
Then input the text to translate. I chose a Harry Potter chapter in English. OpenAI's token count:
![](../../../public/imgs/translate17.png)
Actual results:
![](../../../public/imgs/translate18.png)
It meets reading requirements well.
# Further Optimization
## Prompt Optimization
In the source project, the system prompts for AI are relatively brief. We can use more comprehensive prompts to encourage the LLM to return better translations, further improving quality.
For example, in initial translation:
```typescript
# Role: Senior Translation Expert
## Background:
You are an experienced translation expert, proficient in {{source_lang}} and {{target_lang}} translation, especially skilled at translating {{source_lang}} articles into fluent, understandable {{target_lang}}. You've led teams to complete large translation projects with widely acclaimed results.
## Attention:
- Always adhere to the principles of "faithfulness, expressiveness, and elegance" during translation, with "expressiveness" being especially important
- Translations should conform to {{target_lang}} expression habits, be easy to understand, coherent and fluent
- Avoid overly formal expressions and obscure allusions
## Constraints:
- Must strictly follow the four-round translation process: literal translation, free translation, proofreading, finalization
- Translations must be faithful to the original, accurate, without omissions or misinterpretations
## Goals:
- Through the four-round translation process, translate {{source_lang}} original text into high-quality {{target_lang}} translation
- Translations should accurately convey the original meaning, with language expression that's easy to understand and flows naturally
- Moderately use idioms, colloquialisms, popular internet terms, etc., to enhance translation appeal
- Based on literal translation, provide at least 2 different style free translation versions for selection
## Skills:
- Proficient in both {{source_lang}} and {{target_lang}}, with solid language foundation and rich translation experience
- Skilled at converting {{source_lang}} expression habits into natural {{target_lang}}
- Keen insight into contemporary {{target_lang}} language development, good at grasping language trends
## Workflow:
1. First round literal translation: Faithfully translate word by word, sentence by sentence, without omitting any information
2. Second round free translation: Based on literal translation, use fluent {{target_lang}} to freely translate the original, providing at least 2 different style versions
3. Third round proofreading: Carefully review the translation, eliminate deviations and deficiencies, making the translation more natural and understandable
4. Fourth round finalization: Select the best, repeatedly revise and polish, finally producing a concise, smooth translation that conforms to public reading habits
## OutputFormat:
- Only output the fourth round finalization answer
## Suggestions:
- In literal translation, strive to be faithful to the original, but don't be too rigid word by word
- In free translation, express the original meaning accurately using the most plain {{target_lang}}
- In proofreading, focus on whether the translation conforms to {{target_lang}} expression habits and is easy to understand
- In finalization, moderately use idioms, proverbs, internet slang, etc., to make the translation more down-to-earth
- Leverage {{target_lang}}'s flexibility, use different expressions to present the same content, improving translation readability
```
This returns more accurate, higher-quality initial translations. Subsequent reflection and improved translation can also use more accurate prompts:
![](../../../public/imgs/translate19.png)
Let's look at the results:
![](../../../public/imgs/translate20.png)
Testing with the same passage as before shows significant improvement. For example, the red box section—the previous translation:
![](../../../public/imgs/translate21.png)
Changed from the biased "让你的猫头鹰给我写信" (have your owl write to me) to the more accurate "给我写信,你的猫头鹰会知道怎么找到我" (write to me, your owl will know how to find me).
## Other Optimizations
For example, constraint optimization—the source project demonstrates adding regional constraints, which testing shows provides significant improvement.
Thanks to LLM's excellent capabilities, we can obtain different translation results by setting different prompts—easily achieving specific, more precise translations through special constraints.
For terms beyond LLM understanding, you can also use Fastgpt's knowledge base functionality for expansion, further improving the translation bot's capabilities.
---
title: 多轮翻译机器人
description: 如何使用 FastGPT 构建一个多轮翻译机器人,实现连续的对话翻译功能
---
吴恩达老师提出了一种反思翻译的大语言模型(LLM)翻译工作流程——[GitHub - andrewyng/translation-agent](https://github.com/andrewyng/translation-agent),具体工作流程如下:
1. 提示一个 LLM 将文本从 `source_language` 翻译到 `target_language`;
2. 让 LLM 反思翻译结果并提出建设性的改进建议;
3. 使用这些建议来改进翻译。
这个翻译流程应该是目前比较新的一种翻译方式,利用 LLM 对自己的翻译结果进行改进来获得较好的翻译效果
项目中展示了可以利用对长文本进行分片,然后分别进行反思翻译处理,以突破 LLM 对 tokens 数量的限制,真正实现长文本一键高效率高质量翻译。
项目还通过给大模型限定国家地区,已实现更精确的翻译,如美式英语、英式英语之分;同时提出一些可能能带来更好效果的优化,如对于一些 LLM 未曾训练到的术语(或有多种翻译方式的术语)建立术语表,进一步提升翻译的精确度等等
而这一切都能通过 Fastgpt 工作流轻松实现,本文将手把手教你如何复刻吴恩达老师的 translation-agent
# 单文本块反思翻译
先从简单的开始,即不超出 LLM tokens 数量限制的单文本块翻译
## 初始翻译
第一步先让 LLM 对源文本块进行初始翻译(翻译的提示词在源项目中都有)
![](../../../public/imgs/translate1.png)
通过`文本拼接`模块引用 源语言、目标语言、源文本这三个参数,生成提示词,传给 LLM,让它给出第一版的翻译
## 反思
然后让 LLM 对第一步生成的初始翻译给出修改建议,称之为 反思
![](../../../public/imgs/translate2.png)
这时的提示词接收 5 个参数,源文本、初始翻译、源语言、目标语言 以及限定词地区国家,这样 LLM 会对前面生成的翻译提出相当多的修改建议,为后续的提升翻译作准备
## 提升翻译
![](../../../public/imgs/translate3.png)
在前文生成了初始翻译以及相应的反思后,将这二者输入给第三次 LLM 翻译,这样我们就能获得一个比较高质量的翻译结果
完整的工作流如下
![](../../../public/imgs/translate4.png)
## 运行效果
由于考虑之后对这个反思翻译的复用,所以创建了一个插件,那么在下面我直接调用这个插件就能使用反思翻译,效果如下
随机挑选了一段哈利波特的文段
![](../../../public/imgs/translate5.png)
![](../../../public/imgs/translate61.png)
可以看到反思翻译后的效果还是好上不少的,其中反思的输出如下
![](../../../public/imgs/translate7.png)
# 长文反思翻译
在掌握了对短文本块的反思翻译后,我们能轻松的通过分片和循环,实现对长文本也即多文本块的反思翻译
整体的逻辑是,首先对传入文本的 tokens数量做判断,如果不超过设置的 tokens 限制,那么直接调用单文本块反思翻译,如果超过设置的 tokens限制,那么切割为合理的大小,再分别进行对应的反思翻译处理
## 计算 tokens
![](../../../public/imgs/translate8.png)
首先,我使用了 Laf函数 模块来实现对输入文本的 tokens 的计算
laf函数的使用相当简单,即开即用,只需要在 laf 创建个应用,然后安装 tiktoken 依赖,导入如下代码即可
```typescript
const { Tiktoken } = require("tiktoken/lite");
const cl100k_base = require("tiktoken/encoders/cl100k_base.json");
interface IRequestBody {
str: string
}
interface RequestProps extends IRequestBody {
systemParams: {
appId: string,
variables: string,
histories: string,
cTime: string,
chatId: string,
responseChatItemId: string
}
}
interface IResponse {
message: string;
tokens: number;
}
export default async function (ctx: FunctionContext): Promise<IResponse> {
const { str = "" }: RequestProps = ctx.body
const encoding = new Tiktoken(
cl100k_base.bpe_ranks,
cl100k_base.special_tokens,
cl100k_base.pat_str
);
const tokens = encoding.encode(str);
encoding.free();
return {
message: 'ok',
tokens: tokens.length
};
}
```
再回到 Fastgpt,点击“同步参数”,再连线将源文本传入,即可计算 tokens 数量
## 计算单文本块大小
![](../../../public/imgs/translate9.png)
由于不涉及第三方包,只是一些数据处理,所以直接使用 代码运行 模块处理即可
```typescript
function main({tokenCount, tokenLimit}){
const numChunks = Math.ceil(tokenCount / tokenLimit);
let chunkSize = Math.floor(tokenCount / numChunks);
const remainingTokens = tokenCount % tokenLimit;
if (remainingTokens > 0) {
chunkSize += Math.floor(remainingTokens / numChunks);
}
return {chunkSize};
}
```
通过上面的代码,我们就能算出不超过 token限制的合理单文本块大小是多少了
## 获得切分后源文本块
![](../../../public/imgs/translate10.png)
通过单文本块大小和源文本,我们再编写一个函数调用 langchain 的 textsplitters 包来实现文本分片,具体代码如下
```typescript
import cloud from '@lafjs/cloud'
import { TokenTextSplitter } from "@langchain/textsplitters";
interface IRequestBody {
text: string
chunkSize: number
}
interface RequestProps extends IRequestBody {
systemParams: {
appId: string,
variables: string,
histories: string,
cTime: string,
chatId: string,
responseChatItemId: string
}
}
interface IResponse {
output: string[];
}
export default async function (ctx: FunctionContext): Promise<IResponse>{
const { text = '', chunkSize=1000 }: RequestProps = ctx.body;
const splitter = new TokenTextSplitter({
encodingName:"gpt2",
chunkSize: Number(chunkSize),
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
return {
output
}
}
```
这样我们就获得了切分好的文本,接下去的操作就类似单文本块反思翻译
## 多文本块翻译
这里应该还是不能直接调用前面的单文本块反思翻译,因为提示词中会涉及一些上下文的处理(或者可以修改下前面写好的插件,多传点参数进去)
详细的和前面类似,就是提示词进行一些替换,以及需要做一些很简单的数据处理,整体效果如下
### 多文本块初始翻译
![](../../../public/imgs/translate11.png)
### 多文本块反思
![](../../../public/imgs/translate12.png)
### 多文本块提升翻译
![](../../../public/imgs/translate13.png)
## 批量运行
长文反思翻译比较关键的一个部分,就是对多个文本块进行循环反思翻译
Fastgpt 提供了工作流线路可以返回去执行的功能,所以我们可以写一个很简单的判断函数,来判断结束或是接着执行
![](../../../public/imgs/translate14.png)
也就是通过判断当前处理的这个文本块,是否是最后一个文本块,从而判断是否需要继续执行,就这样,我们实现了长文反思翻译的效果
完整工作流如下
![](../../../public/imgs/translate15.png)
## 运行效果
首先输入全局设置
![](../../../public/imgs/translate16.png)
然后输入需要翻译的文本,这里我选择了一章哈利波特的英文原文来做翻译,其文本长度通过 openai 对 tokens 数量的判断如下
![](../../../public/imgs/translate17.png)
实际运行效果如下
![](../../../public/imgs/translate18.png)
可以看到还是能满足阅读需求的
# 进一步调优
## 提示词调优
在源项目中,给 AI 的系统提示词还是比较的简略的,我们可以通过比较完善的提示词,来督促 LLM 返回更合适的翻译,进一步提升翻译的质量
比如初始翻译中,
```typescript
# Role: 资深翻译专家
## Background:
你是一位经验丰富的翻译专家,精通{{source_lang}}和{{target_lang}}互译,尤其擅长将{{source_lang}}文章译成流畅易懂的{{target_lang}}。你曾多次带领团队完成大型翻译项目,译文广受好评。
## Attention:
- 翻译过程中要始终坚持"信、达、雅"的原则,但"达"尤为重要
- 译文要符合{{target_lang}}的表达习惯,通俗易懂,连贯流畅
- 避免使用过于文绉绉的表达和晦涩难懂的典故引用
## Constraints:
- 必须严格遵循四轮翻译流程:直译、意译、校审、定稿
- 译文要忠实原文,准确无误,不能遗漏或曲解原意
## Goals:
- 通过四轮翻译流程,将{{source_lang}}原文译成高质量的{{target_lang}}译文
- 译文要准确传达原文意思,语言表达力求浅显易懂,朗朗上口
- 适度使用一些熟语俗语、流行网络用语等,增强译文的亲和力
- 在直译的基础上,提供至少2个不同风格的意译版本供选择
## Skills:
- 精通{{source_lang}} {{target_lang}}两种语言,具有扎实的语言功底和丰富的翻译经验
- 擅长将{{source_lang}}表达习惯转换为地道自然的{{target_lang}}
- 对当代{{target_lang}}语言的发展变化有敏锐洞察,善于把握语言流行趋势
## Workflow:
1. 第一轮直译:逐字逐句忠实原文,不遗漏任何信息
2. 第二轮意译:在直译的基础上用通俗流畅的{{target_lang}}意译原文,至少提供2个不同风格的版本
3. 第三轮校审:仔细审视译文,消除偏差和欠缺,使译文更加地道易懂
4. 第四轮定稿:择优选取,反复修改润色,最终定稿出一个简洁畅达、符合大众阅读习惯的译文
## OutputFormat:
- 只需要输出第四轮定稿的回答
## Suggestions:
- 直译时力求忠实原文,但不要过于拘泥逐字逐句
- 意译时在准确表达原意的基础上,用最朴实无华的{{target_lang}}来表达
- 校审环节重点关注译文是否符合{{target_lang}}表达习惯,是否通俗易懂
- 定稿时适度采用一些熟语谚语、网络流行语等,使译文更接地气- 善于利用{{target_lang}}的灵活性,用不同的表述方式展现同一内容,提高译文的可读性
```
从而返回更准确更高质量的初始翻译,后续的反思和提升翻译也可以修改更准确的提示词,如下
![](../../../public/imgs/translate19.png)
然后再让我们来看看运行效果
![](../../../public/imgs/translate20.png)
给了和之前相同的一段文本进行测试,测试效果还是比较显著的,就比如红框部分,之前的翻译如下
![](../../../public/imgs/translate21.png)
从“让你的猫头鹰给我写信”这样有失偏颇的翻译,变成“给我写信,你的猫头鹰会知道怎么找到我”这样较为准确的翻译
## 其他调优
比如限定词调优,源项目中已经做了示范,就是加上国家地区这个限定词,实测确实会有不少提升
出于 LLM 的卓越能力,我们能够通过设置不同的prompt来获取不同的翻译结果,也就是可以很轻松地通过设置特殊的限定词,来实现特定的,更精确的翻译
而对于一些超出 LLM 理解的术语等,也可以利用 Fastgpt 的知识库功能进行相应扩展,进一步完善翻译机器人的功能
---
title: How to Submit Application Templates
description: "Guide: How to submit application templates to FastGPT"
---
## Which Templates Can Be Merged
Currently, application templates merged into the repository are displayed to all users in the "Template Market".
To maintain template quality and avoid clutter from too many options, not all templates will be merged into the open-source repository. You can submit a PR in advance to discuss the template content with us.
We estimate the final total will be around 50 templates — half from the FastGPT Team and half from community contributors.
## How to Write an Application Template
### 1. Set Up FastGPT and FastGPT-plugin Development Environments
The following operations need to be performed in a dev environment.
Refer to these two guides to run the FastGPT and FastGPT-plugin development environments locally:
- [FastGPT | Quick Start Local Development](../../self-host/dev.en.mdx)
- [How to Develop System Plugins](../../guide/build/tools/system-plugins/dev_system_tool.en.mdx)
### 2. Create an Application Template
In the FastGPT-plugin project, application templates are located in the `modules/workflow/templates` directory.
1. Create a new `.json` file
2. Copy the following content and paste it into the newly created `.json` file
```json
{
"name": "Template Name",
"intro": "Template description, displayed on the template market page",
"author": "Your name",
"avatar": "Template avatar — place the image file in the same folder and fill in the corresponding path",
"tags": ["Template tags"], // writing (text creation), image-generation (image generation), web-search (web search),
// roleplay (role-playing), office-services (office services) — currently 5 categories, choose the appropriate tag
"type": "Template category", // simple (simple app), advanced (workflow), plugin (plugin)
"workflow": {
// Leave this object empty for now — we'll paste the exported workflow later
"nodes": [],
"edges": [],
"chatConfig": {}
}
}
```
### 3. Complete Template Orchestration and Testing
1. Build the workflow in FastGPT (either in the cloud service version or a locally deployed version).
### 4. Copy Configuration to template.json
Hover your mouse over the application avatar and name in the top-left corner. A dropdown menu will appear with an option to export the workflow configuration.
The exported configuration is automatically copied to the clipboard. Paste it directly into the template.json file, replacing the **workflow** value from step 2.
![](../../../public/imgs/template_submission3.png)
### 5. Verify the Template Loads Successfully
Refresh the page, open the Template Market, check if it loads successfully, and click "Use" to test its functionality.
![](../../../public/imgs/template_submission4.png)
### 6. Deploy and Use
After completing the above steps, you can package the fastgpt-plugin image for deployment. Currently, templates do not support hot updates — all templates are packaged within the image.
If you prefer not to repackage the fastgpt-plugin image every time you update templates, you can mount the `.json` file to the `/app/workflows/` directory inside the container using Docker volume mounting.
### 7. Submit a PR
If you believe your template should be included in the open-source repository, you can submit it via a PR.
- Clearly describe the template's purpose and functionality
- Include screenshots showing the template in action
- Explain template parameter configuration in the PR. For example, if the template requires applying for a key from a provider, include the corresponding URL and tutorial — we will add it to the documentation later.
---
title: 如何提交应用模板
description: 指南:如何向 FastGPT 提交应用模板
---
## 什么模板可以合并
目前合并进仓库的应用模板,会在「模板市场」中全部展示给用户。
为了控制模板的质量以及避免数量过多带来的繁琐,并不是所有的模板都会被合并到开源仓库中,你可以提前 PR 与我们沟通模板的内容。
预估最后总体的数量不会很多,控制在 50 个左右,一半来自 FastGPT Team,一半来自社区用户。
## 如何写一个应用模板
### 1. 跑通 FastGPT 开发环境和 FastGPT-plugin 开发环境
需要在 dev 环境下执行下面的操作。
可参照下面两篇文档在本地运行 FastGPT 开发环境和 FastGPT-plugin 开发环境
- [FastGPT|快速开始本地开发](../../self-host/dev.mdx)
- [如何开发系统插件](../../guide/build/tools/system-plugins/dev_system_tool.mdx)
### 2. 创建应用模版
在 FastGPT-plugin 项目中,应用模版都在 `modules/workflow/templates` 目录下。
1. 创建一个新的 `.json` 文件
2. 复制如下内容并粘贴在刚刚创建的 `.json` 文件中
```json
{
"name": "模板名",
"intro": "模板描述,会展示在模板市场的展示页",
"author": "填写你的名字",
"avatar": "模板头像,可以将图片文件放在同一个文件夹中,然后填写相应路径",
"tags": ["模板标签"], // writing(文本创作),image-generation(图片生成),web-search(联网搜索),
// roleplay(角色扮演), office-services(办公服务) 暂时分为 5 类,从中选择相应的标签
"type": "模板类别", // simple(简易应用), advanced(工作流), plugin(插件)
"workflow": {
// 这个对象先不管,待会直接粘贴导出的工作流即可
"nodes": [],
"edges": [],
"chatConfig": {}
}
}
```
### 3. 完成模版的编排和测试
1. 在 FastGPT 中(可以在云服务版或本地部署的版本中进行)编排工作流。
### 4. 复制配置到 template.json
鼠标放置在左上角应用的头像和名称上,会出现对于下拉框操作,可以导出工作流配置。
导出的配置,会自动复制到剪切板,可以直接到 template.json 文件中粘贴使用,替换步骤 2 中,**workflow** 的值。
![](../../../public/imgs/template_submission3.png)
### 5. 验证模板是否加载成功
刷新页面,打开模板市场,看其是否成功加载,并点击「使用」测试其功能。
![](../../../public/imgs/template_submission4.png)
### 6. 部署使用
完成上述操作后,可以打包 fastgpt-plugin 镜像使用 目前模版不支持热更新机制,所有模版都会打包在镜像内。
如果您不希望每次更新模版都要重新打包 fastgpt-plugin 镜像,可以选择通过 docker 存储卷挂载的方式将 .json 文件挂载到容器内的 `/app/workflows/` 目录下。
### 7. 提交 PR
如果你觉得你的模板需要提交到开源仓库,可以通过 PR 形式向我们提交。
- 写清楚模板的介绍和功能
- 配上模板运行的效果图
- 模板参数填写说明,需要在 PR 中写清楚。例如,有些模板需要去某个提供商申请 key,需要附上对应的地址和教程,后续我们会加入到文档中。
---
title: Long Subtitle Translation
description: Use AI self-reflection to improve translation quality while leveraging iterative workflow execution to overcome LLM token limits, creating an efficient long subtitle translation bot.
---
Using LLMs directly to translate long subtitles presents several challenges that AI alone can't effectively handle:
1. **Token Limits**: This is the most obvious obstacle. Large language models (LLMs) typically have output token limits, meaning **for long texts, without special workflows, you'd need to manually segment the text, translate each segment separately, and then manually stitch the results together**. This process is not only tedious but also error-prone.
2. **Preserving Subtitle Format**: For subtitles, timeline information is crucial. However, AI models sometimes "hallucinate," generating or modifying information that doesn't exist. In subtitle translation, this can cause the AI to incorrectly modify timelines, making subtitles out of sync with audio.
3. **Translation Quality**: Simple machine translation often fails to meet audience needs. Even with large language models, single-pass translation quality is frequently unsatisfactory. For subtitles, translation quality directly impacts viewing experience—poor translation severely disrupts audience immersion.
This case study demonstrates how to effectively solve these problems by combining FastGPT workflow code with LLMs. Our approach not only overcomes technical limitations but also significantly improves translation quality.
## Extract Subtitle Information
A major advantage of workflows is the ability to combine additional operations, enabling AI to process information more precisely. In subtitle translation, we can **first separate the components of an SRT subtitle file, then have the LLM translate only the text portion**. This approach saves tokens and ensures timeline information isn't mistakenly altered.
Implementation:
1. Use a code execution module to parse the input raw subtitle text.
2. Classify subtitle information into three parts: time information, sequence numbers, and text information.
3. Keep only the text information for subsequent AI translation.
![](../../../public/imgs/extract-subtitle.png)
This preprocessing step greatly improves the efficiency and accuracy of the entire translation process.
## Split Text
To further optimize the translation process, we need to reorganize the extracted text information. The goal of this step is to **split the text into sizes suitable for LLM processing while maintaining contextual coherence**.
In this example, we use the following strategy:
1. Split the text into groups of 40 sentences each. This number is a balance point determined through multiple tests—it ensures translation quality without exceeding the LLM's processing capacity.
2. Use `<T>` tags to separate each sentence. This marking method facilitates subsequent reassembly while providing clear sentence boundaries for the AI model.
![](../../../public/imgs/cut-text.png)
This splitting method considers both the AI model's capability limits and ensures translation coherence. By maintaining appropriate context, we can achieve more accurate and natural translation results.
## Format Original Text
In this step, we construct the final source text to input to the LLM. The key is how to provide sufficient context information while controlling token count. We use the following strategy:
1. **Pass in all text as background context. This ensures the AI understands the context of the entire conversation**.
2. Use `<TRANSLATE_THIS>` tags to clearly indicate the segment that currently needs translation. This method controls the AI's output scope without losing overall context.
![](../../../public/imgs/format-original-text.png)
This formatting method enables the AI to focus on translating specific parts while understanding the global context, thereby improving translation accuracy and coherence.
## LLM Translation
This is the most critical step in the entire process. We leverage the LLM's powerful capabilities to achieve high-quality translation. In this step, we integrate the previously mentioned "initial translation → reflection → improved translation" process into a single prompt.
This process includes the following stages:
1. First round literal translation: Require the AI to strictly translate sentence by sentence according to `<T>` tags, ensuring accuracy.
![](../../../public/imgs/ai-translate-1.png)
2. Second round free translation: Allow the AI to freely modify and optimize the first round results.
3. Third round reflection: The AI evaluates its own translation and proposes improvement suggestions from multiple angles.
![](../../../public/imgs/ai-translate-2.png)
4. Final round modification: Based on suggestions from the reflection stage, the AI makes final adjustments and optimizations to the translation.
![](../../../public/imgs/ai-translate-3.png)
This multi-round translation and reflection method significantly improves translation quality. It not only captures the accurate meaning of the original text but also makes the translation more fluent and natural.
It's worth noting that this method's effectiveness is comparable to direct step-by-step execution, but the workflow is more concise and efficient.
## Combine Subtitles
After completing the translation, we need to recombine all information into a complete subtitle file. This step includes:
1. Integrate the previously separated sequence number and time information.
2. Match the translated text with the original text.
3. Use a code execution module to automatically complete the assembly process.
![](../../../public/imgs/combine-subtitle.png)
This process not only improves efficiency but also minimizes the possibility of human error.
## Batch Execution
To process the entire long subtitle file, we need a batch execution mechanism. This is implemented through a simple but effective judgment module:
1. Check if the currently translated text block is the last one.
2. If not, redirect the workflow to the format original text block node.
3. Extract the next segment of text that needs translation and restart the translation and stitching process.
![](../../../public/imgs/loop-execution.png)
This loop mechanism ensures the entire long subtitle file can be fully processed, regardless of how long the subtitles are.
## Practical Application Example
To verify the effectiveness of this method, we selected an English subtitle segment from "Game of Thrones" and translated it into Simplified Chinese. You can see that our method not only accurately translates the content but also preserves the subtitle format and timeline information.
![](../../../public/imgs/gpt-translate-example.png)
## Attachments
The complete workflow configuration is below. Copy and import directly into FastGPT.
<details>
<summary>Workflow Configuration</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "core/workflow/template/systemConfig",
"flowNodeType": "userGuide",
"position": {
"x": -1453.0815298642474,
"y": 269.10239463914263
},
"version": "481",
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "流程开始",
"intro": "",
"avatar": "core/workflow/template/workflowStart",
"flowNodeType": "workflowStart",
"position": {
"x": -1458.2511936623089,
"y": 1218.2790943636066
},
"version": "481",
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"type": "static",
"valueType": "string"
}
]
},
{
"nodeId": "yjFO3YcM7KG2",
"name": "LLM 翻译",
"intro": "AI 大模型对话",
"avatar": "core/workflow/template/aiChat",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 2569.420973631976,
"y": 909.4127366971411
},
"version": "481",
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"selectedTypeIndex": 0,
"value": "claude-3-5-sonnet-20240620"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 3,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 4000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": false,
"valueType": "boolean"
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "# Role: 资深字幕翻译专家\n\n## Background:\n你是一位经验丰富的{{source_lang}}和{{target_lang}}字幕翻译专家,精通{{source_lang}}和{{target_lang}}互译,尤其擅长将{{source_lang}}字幕译成流畅易懂的{{target_lang}}字幕。你曾多次带领团队完成大型商业电影的字幕翻译项目,所翻译的字幕广受好评。\n\n## Attention:\n- 翻译过程中要始终坚持\"信、达、雅\"的原则,但\"达\"尤为重要\n- 翻译的字幕要符合{{target_lang}}的表达习惯,通俗易懂,连贯流畅\n- 避免使用过于文绉绉的表达和晦涩难懂的典故引用 \n- 诗词歌词等内容需按原文换行和节奏分行,不破坏原排列格式 \n- 翻译对象是字幕,请进入整段文本的语境中对需要翻译的文本段进行翻译\n- <T>是标识每一帧字幕的标签,请严格按照<T>对文本的分割逐帧翻译,每一帧字幕末尾不要加 \\n 回车标识,且第一帧字幕开头不需要加<T>标识\n\n## Constraints:\n- 必须严格遵循四轮翻译流程:直译、意译、反思、提升\n- 译文要忠实原文,准确无误,不能遗漏或曲解原意\n- 最终译文使用Markdown的代码块呈现,但是不用输出markdown这个单词\n- <T>是标识每一帧字幕的标签,请严格按照<T>对文本的分割逐帧翻译,每一帧字幕末尾不要加 \\n 回车标识,且第一帧字幕开头不需要加<T>标识\n\n## Goals:\n- 通过四轮翻译流程,将{{source_lang}}字幕译成高质量的{{target_lang}}字幕\n- 翻译的字幕要准确传达原字幕意思,语言表达力求浅显易懂,朗朗上口 \n\n## Workflow:\n1. 第一轮直译:严格按照<T>逐句翻译,不遗漏任何信息\n2. 第二轮意译:在直译的基础上用通俗流畅的{{target_lang}}意译原文,逐句翻译,保留<T>标识标签\n3. 第三轮反思:仔细审视译文,分点列出一份建设性的批评和有用的建议清单以改进翻译,对每一句话提出建议,从以下四个角度展开\n (i) 准确性(纠正添加、误译、遗漏或未翻译的文本错误),\n (ii) 流畅性(应用{{target_lang}}的语法、拼写和标点规则,并确保没有不必要的重复),\n (iii) 风格(确保翻译反映源文本的风格并考虑其文化背景),\n (iv) 术语(确保术语使用一致且反映源文本所在领域,注意确保使用{{target_lang}}中的等效习语)\n4. 第四轮提升:严格遵循第三轮提出的建议对翻译修改,定稿出一个简洁畅达、符合大众观影习惯的字幕译文,保留<T>标识标签\n\n## OutputFormat:\n- 每一轮前用【思考】说明该轮要点\n- 第一轮和第二轮翻译后用【翻译】呈现译文\n- 第三轮输出建议清单,分点列出,在每一点前用*xxx*标识这条建议对应的要点,如*风格*;建议前用【思考】说明该轮要点,建议后用【建议】呈现建议\n- 第四轮在\\`\\`\\`代码块中展示最终{{target_lang}}字幕文件内容,如\\`\\`\\`xxx\\`\\`\\`\n\n## Suggestions:\n- 直译时力求忠实原文,但注意控制每帧字幕的字数,必要时进行精简压缩\n- 意译时在准确表达原意的基础上,用最朴实无华的{{target_lang}}来表达\n- 反思环节重点关注译文是否符合{{target_lang}}表达习惯,是否通俗易懂,是否准确流畅,是否术语一致\n- 提升环节采用反思环节的建议对意译环节的翻译进行修改,适度采用一些口语化的表达、网络流行语等,增强字幕的亲和力\n- 注意<T>是很重要的标识标签,请确保标签能在正确位置输出"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"description": "最多携带多少轮对话记录",
"required": true,
"min": 0,
"max": 50,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题",
"value": [
"bxz97Vg4Omux",
"system_text"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "",
"valueType": "datasetQuote"
}
],
"outputs": [
{
"id": "history",
"key": "history",
"required": true,
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context",
"valueType": "chatHistory",
"type": "static"
},
{
"id": "answerText",
"key": "answerText",
"required": true,
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "bxz97Vg4Omux",
"name": "LLM 翻译提示词",
"intro": "可对固定或传入的文本进行加工后输出,非字符串类型数据最终会转成字符串类型。",
"avatar": "core/workflow/template/textConcat",
"flowNodeType": "textEditor",
"position": {
"x": 1893.11421220213,
"y": 1065.1299598362698
},
"version": "486",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "可以引用其他节点的输出,作为文本拼接的变量,通过 {{字段名}} 来引用变量",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
}
},
{
"key": "system_textareaInput",
"renderTypeList": [
"textarea"
],
"valueType": "string",
"required": true,
"label": "拼接文本",
"placeholder": "可通过 {{字段名}} 来引用变量",
"value": "你的任务是将文本从{{source_lang}}翻译成{{target_lang}}\n\n源文本如下,由XML标签<SOURCE_TEXT>和</SOURCE_TEXT>分隔:\n\n<SOURCE_TEXT>\n\n{{tagged_text}}\n\n</SOURCE_TEXT>\n\n仅翻译源文本中由<TRANSLATE_THIS>和</TRANSLATE_THIS>分隔的部分,将其余的源文本作为上下文\n\n重申一下,你应该只翻译文本的这一部分,这里再次显示在<TRANSLATE_THIS>和</TRANSLATE_THIS>之间:\n\n<TRANSLATE_THIS>\n\n{{chunk_to_translate}}\n\n</TRANSLATE_THIS>"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "tagged_text",
"label": "tagged_text",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"required": true,
"value": [
"quYZgsW32ApA",
"xhXu6sdEWBnF"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "chunk_to_translate",
"label": "chunk_to_translate",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
}
],
"outputs": [
{
"id": "system_text",
"key": "system_text",
"label": "拼接结果",
"type": "static",
"valueType": "string"
}
]
},
{
"nodeId": "w4heEpNflz59",
"name": "判断是否执行结束",
"intro": "根据一定的条件,执行不同的分支。",
"avatar": "core/workflow/template/ifelse",
"flowNodeType": "ifElseNode",
"showStatus": true,
"position": {
"x": 5625.495682697096,
"y": 1199.9313115831496
},
"version": "481",
"inputs": [
{
"key": "ifElseList",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": [
{
"condition": "AND",
"list": [
{
"variable": [
"a2lqxASWi1vb",
"nmBmGaARbKkl"
],
"condition": "equalTo",
"value": "true"
}
]
}
]
}
],
"outputs": [
{
"id": "ifElseResult",
"key": "ifElseResult",
"label": "判断结果",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "a2lqxASWi1vb",
"name": "判断是否执行结束",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 5099.256084679105,
"y": 1102.1518590433243
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({chunks, currentChunk}){\n const findIndex = chunks.findIndex((item) => item === currentChunk)\n\n return {\n isEnd: chunks.length-1 === findIndex,\n i: findIndex + 1,\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "chunks",
"label": "chunks",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"y3WEYOQ09CGC",
"qLUQfhG0ILRX"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "currentChunk",
"label": "currentChunk",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "nmBmGaARbKkl",
"valueType": "boolean",
"type": "dynamic",
"key": "isEnd",
"label": "isEnd"
},
{
"id": "nqB98uKpq6Ig",
"valueType": "number",
"type": "dynamic",
"key": "i",
"label": "i"
}
]
},
{
"nodeId": "quYZgsW32ApA",
"name": "格式化源文本块",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 1251.2839737092052,
"y": 991.619268503857
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({source_text_chunks, i=0}){\n let before = source_text_chunks.slice(0, i).join(\"\");\n let current = \" <TRANSLATE_THIS>\" + source_text_chunks[i] + \"</TRANSLATE_THIS>\";\n let after = source_text_chunks.slice(i + 1).join(\"\");\n let tagged_text = before + current + after;\n\n return {\n tagged_text,\n chunk_to_translate: source_text_chunks[i],\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "number",
"canEdit": true,
"key": "i",
"label": "i",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"a2lqxASWi1vb",
"nqB98uKpq6Ig"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "source_text_chunks",
"label": "source_text_chunks",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"y3WEYOQ09CGC",
"qLUQfhG0ILRX"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "xhXu6sdEWBnF",
"valueType": "string",
"type": "dynamic",
"key": "tagged_text",
"label": "tagged_text"
},
{
"id": "eCp73lztAEGK",
"valueType": "string",
"type": "dynamic",
"key": "chunk_to_translate",
"label": "chunk_to_translate"
}
]
},
{
"nodeId": "izsNX8FXGD1t",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": 6399.439691374053,
"y": 1204.4024103331792
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "\n\n*** 字幕反思翻译完成!***"
}
],
"outputs": []
},
{
"nodeId": "vlNHndpNuFXB",
"name": "取出 LLM 翻译第四轮文本",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 3284.6375352131763,
"y": 950.1100995985583
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"editField": {
"key": true,
"valueType": true
},
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({data1}){\n const result = data1.split(\"```\").filter(item => !!item.trim())\n\n if(result[result.length-1]) {\n return {\n result: result[result.length-1].trim() \n }\n }\n\n return {\n result: '未截取到翻译内容'\n }\n}"
},
{
"key": "data1",
"valueType": "string",
"label": "data1",
"renderTypeList": [
"reference"
],
"description": "",
"canEdit": true,
"editField": {
"key": true,
"valueType": true
},
"value": [
"yjFO3YcM7KG2",
"answerText"
],
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "string",
"label": "result"
},
{
"id": "gR0mkQpJ4Og8",
"type": "dynamic",
"key": "data2",
"valueType": "string",
"label": "data2"
}
]
},
{
"nodeId": "qlt9KJbbS9yJ",
"name": "判断源语言和目标语言是否相同",
"intro": "根据一定的条件,执行不同的分支。",
"avatar": "core/workflow/template/ifelse",
"flowNodeType": "ifElseNode",
"showStatus": true,
"position": {
"x": -648.2730659546055,
"y": 1295.3336516652123
},
"version": "481",
"inputs": [
{
"key": "ifElseList",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": [
{
"condition": "AND",
"list": [
{
"variable": [
"frjbsrlnJJsR",
"qLUQfhG0ILRX"
],
"condition": "equalTo",
"value": "false"
}
]
}
]
}
],
"outputs": [
{
"id": "ifElseResult",
"key": "ifElseResult",
"label": "判断结果",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "frjbsrlnJJsR",
"name": "判断源语言和目标语言是否相同",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": -1142.9562352499165,
"y": 1031.4486788585432
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({source_lang, target_lang}){\n \n return {\n result: source_lang === target_lang\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "source_lang",
"label": "source_lang",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"VARIABLE_NODE_ID",
"source_lang"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "target_lang",
"label": "target_lang",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"VARIABLE_NODE_ID",
"target_lang"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "boolean",
"label": "result"
}
]
},
{
"nodeId": "dFxrGZS3Wmnz",
"name": "提示源语言与目标语言相同",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": -554.7555863373991,
"y": 1727.175384457058
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 0,
"value": "{{source_lang}} 无需再次翻译为 {{target_lang}} ~"
}
],
"outputs": []
},
{
"nodeId": "tqzmK5oPR9BA",
"name": "输出翻译",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": 4378.294585712487,
"y": 1268.975092230105
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 1,
"value": [
"ppPP6o7YYSTJ",
"dYalXmYJ60bj"
]
}
],
"outputs": []
},
{
"nodeId": "kbr342XlxSZR",
"name": "提取字幕信息",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 185.35869756392378,
"y": 1004.6884026918935
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({text}){\n const lines = text.split('\\n');\n const timePattern = /\\d{2}:\\d{2}:\\d{2},\\d{3} --> \\d{2}:\\d{2}:\\d{2},\\d{3}/;\n const numberInfo = [];\n const timeInfo = [];\n const textInfo = [];\n let currentText = [];\n\n // 提取序号、时间戳和文本信息\n lines.forEach(line => {\n if (/^\\d+$/.test(line.trim())) {\n numberInfo.push(line.trim());\n } else if (timePattern.test(line)) {\n timeInfo.push(line);\n if (currentText.length > 0) {\n textInfo.push(currentText.join(' '));\n currentText = [];\n }\n } else if (line.trim() === '') {\n // Skip empty lines\n } else {\n currentText.push(line.trim());\n }\n });\n\n if (currentText.length > 0) {\n textInfo.push(currentText.join(' '));\n }\n\n return { numberInfo, timeInfo, textInfo };\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "text",
"label": "text",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"448745",
"userChatInput"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "h3qVuGhV9HNm",
"valueType": "arrayString",
"type": "dynamic",
"key": "timeInfo",
"label": "timeInfo"
},
{
"id": "zGYRMNA9xGuI",
"valueType": "arrayString",
"type": "dynamic",
"key": "textInfo",
"label": "textInfo"
},
{
"id": "dhzTt6Riz8Dp",
"valueType": "arrayString",
"type": "dynamic",
"key": "numberInfo",
"label": "numberInfo"
}
]
},
{
"nodeId": "ppPP6o7YYSTJ",
"name": "格式化字幕文件",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 3825.553384884565,
"y": 956.4575651844932
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({combinedText, transedText, timeInfo, currentIndex=0,numberInfo}){\n const textLines = combinedText.split('<T>');\n const resultLines = transedText.split('<T>');\n const combinedLines = [];\n\n resultLines.forEach((line, index) => {\n combinedLines.push(numberInfo[currentIndex+index]);\n combinedLines.push(timeInfo[currentIndex+index]);\n combinedLines.push(line)\n combinedLines.push(textLines[index]);\n combinedLines.push('');\n });\n\n const srtContent = combinedLines.join('\\n');\n \n\n return {\n srtContent,\n currentIndex: currentIndex+textLines.length\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "combinedText",
"label": "combinedText",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "transedText",
"label": "transedText",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"vlNHndpNuFXB",
"qLUQfhG0ILRX"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "timeInfo",
"label": "timeInfo",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"h3qVuGhV9HNm"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "number",
"canEdit": true,
"key": "currentIndex",
"label": "currentIndex",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"ppPP6o7YYSTJ",
"u6eqeC0pEPe0"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "numberInfo",
"label": "numberInfo",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"dhzTt6Riz8Dp"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "dYalXmYJ60bj",
"valueType": "string",
"type": "dynamic",
"key": "srtContent",
"label": "srtContent"
},
{
"id": "u6eqeC0pEPe0",
"valueType": "number",
"type": "dynamic",
"key": "currentIndex",
"label": "currentIndex"
}
]
},
{
"nodeId": "y3WEYOQ09CGC",
"name": "切分文本",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 742.138506499589,
"y": 1011.2409789066801
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({textArray}){\n const groupSize = 20\n const delimiter = '<T>'\n\n const result = [];\n\n for (let i = 0; i < textArray.length; i += groupSize) {\n result.push(textArray.slice(i, i + groupSize).join(delimiter));\n }\n\n return {result};\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "textArray",
"label": "textArray",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"zGYRMNA9xGuI"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "arrayString",
"label": "result"
}
]
}
],
"edges": [
{
"source": "bxz97Vg4Omux",
"target": "yjFO3YcM7KG2",
"sourceHandle": "bxz97Vg4Omux-source-right",
"targetHandle": "yjFO3YcM7KG2-target-left"
},
{
"source": "a2lqxASWi1vb",
"target": "w4heEpNflz59",
"sourceHandle": "a2lqxASWi1vb-source-right",
"targetHandle": "w4heEpNflz59-target-left"
},
{
"source": "w4heEpNflz59",
"target": "izsNX8FXGD1t",
"sourceHandle": "w4heEpNflz59-source-IF",
"targetHandle": "izsNX8FXGD1t-target-left"
},
{
"source": "448745",
"target": "frjbsrlnJJsR",
"sourceHandle": "448745-source-right",
"targetHandle": "frjbsrlnJJsR-target-left"
},
{
"source": "frjbsrlnJJsR",
"target": "qlt9KJbbS9yJ",
"sourceHandle": "frjbsrlnJJsR-source-right",
"targetHandle": "qlt9KJbbS9yJ-target-left"
},
{
"source": "tqzmK5oPR9BA",
"target": "a2lqxASWi1vb",
"sourceHandle": "tqzmK5oPR9BA-source-right",
"targetHandle": "a2lqxASWi1vb-target-left"
},
{
"source": "yjFO3YcM7KG2",
"target": "vlNHndpNuFXB",
"sourceHandle": "yjFO3YcM7KG2-source-right",
"targetHandle": "vlNHndpNuFXB-target-left"
},
{
"source": "ppPP6o7YYSTJ",
"target": "tqzmK5oPR9BA",
"sourceHandle": "ppPP6o7YYSTJ-source-right",
"targetHandle": "tqzmK5oPR9BA-target-left"
},
{
"source": "kbr342XlxSZR",
"target": "y3WEYOQ09CGC",
"sourceHandle": "kbr342XlxSZR-source-right",
"targetHandle": "y3WEYOQ09CGC-target-left"
},
{
"source": "y3WEYOQ09CGC",
"target": "quYZgsW32ApA",
"sourceHandle": "y3WEYOQ09CGC-source-right",
"targetHandle": "quYZgsW32ApA-target-left"
},
{
"source": "quYZgsW32ApA",
"target": "bxz97Vg4Omux",
"sourceHandle": "quYZgsW32ApA-source-right",
"targetHandle": "bxz97Vg4Omux-target-left"
},
{
"source": "w4heEpNflz59",
"target": "quYZgsW32ApA",
"sourceHandle": "w4heEpNflz59-source-ELSE",
"targetHandle": "quYZgsW32ApA-target-left"
},
{
"source": "qlt9KJbbS9yJ",
"target": "kbr342XlxSZR",
"sourceHandle": "qlt9KJbbS9yJ-source-IF",
"targetHandle": "kbr342XlxSZR-target-left"
},
{
"source": "qlt9KJbbS9yJ",
"target": "dFxrGZS3Wmnz",
"sourceHandle": "qlt9KJbbS9yJ-source-ELSE",
"targetHandle": "dFxrGZS3Wmnz-target-right"
},
{
"source": "vlNHndpNuFXB",
"target": "ppPP6o7YYSTJ",
"sourceHandle": "vlNHndpNuFXB-source-right",
"targetHandle": "ppPP6o7YYSTJ-target-left"
}
],
"chatConfig": {
"welcomeText": "你好,欢迎使用长字幕反思翻译机器人。\n\n在完成下方设置后,可以直接输入需要翻译的文本",
"variables": [
{
"id": "v98n5b",
"key": "source_lang",
"label": "源语言",
"type": "select",
"required": true,
"maxLen": 50,
"enums": [
{
"value": "简体中文"
},
{
"value": "繁體中文"
},
{
"value": "English"
},
{
"value": "Español"
},
{
"value": "Français"
},
{
"value": "Deutsch"
},
{
"value": "Italiano"
},
{
"value": "日本語"
},
{
"value": "한국어"
},
{
"value": "Русский"
},
{
"value": "العربية"
},
{
"value": "Bahasa Indonesia"
},
{
"value": "Polski"
}
],
"icon": "core/app/variable/select"
},
{
"id": "c3tvge",
"key": "target_lang",
"label": "目标语言",
"type": "select",
"required": true,
"maxLen": 50,
"enums": [
{
"value": "简体中文"
},
{
"value": "繁體中文"
},
{
"value": "English"
},
{
"value": "Español"
},
{
"value": "Français"
},
{
"value": "Deutsch"
},
{
"value": "Italiano"
},
{
"value": "日本語"
},
{
"value": "한국어"
},
{
"value": "Русский"
},
{
"value": "العربية"
},
{
"value": "Bahasa Indonesia"
},
{
"value": "Polski"
}
],
"icon": "core/app/variable/select"
}
],
"scheduledTriggerConfig": {
"cronString": "",
"timezone": "Asia/Shanghai",
"defaultPrompt": ""
},
"_id": "6688b45317c65410d61d58aa"
}
}
```
</details>
---
title: 长字幕翻译
description: 利用 AI 自我反思提升翻译质量,同时循环迭代执行 AI 工作流来突破 LLM tokens 限制,实现一个高效的长字幕翻译机器人。
---
直接使用 LLM 来翻译长字幕会遇到很多难点,这些难点也正是直接使用 AI 无法有效处理的问题:
1. **Tokens 限制**:这是最明显的障碍。大语言模型 (LLM) 通常有输出 tokens 的限制,这意味着**对于长文本,如果不使用特殊的工作流,可能需要手动将文本分段,逐段输入 AI 进行翻译,然后再手动拼接结果**。这个过程不仅繁琐,还容易出错。
2. **字幕格式的保持**:对于字幕来说,时间轴信息至关重要。然而,AI 模型有时会产生 “幻觉”,即无中生有地修改或生成不存在的信息。在字幕翻译中,这可能导致 AI 错误地修改时间轴,使字幕与音频不同步。
3. **翻译质量**:简单的机器翻译往往无法满足观众的需求。即使是大语言模型,单轮翻译的质量也常常不尽如人意。对于字幕来说,翻译质量直接影响观看体验,糟糕的翻译会严重影响观众的沉浸感。
本案例将展示如何利用 FastGPT 工作流代码结合 LLM 来有效解决这些问题。我们的方法不仅能克服技术限制,还能显著提升翻译质量。
## 提取字幕信息
工作流的一大优势在于可以结合额外的操作,使 AI 能更精准地处理信息。在字幕翻译中,我们可以**先分离 SRT 字幕文件的各个组成部分,然后只让 LLM 翻译文本部分**。这种方法既节约了 token 使用,又确保了时间轴信息不被误改。
具体实现如下:
1. 使用代码执行模块,对输入的原始字幕文本进行解析。
2. 将字幕信息分类为三部分:时间信息、序号信息和文本信息。
3. 只保留文本信息用于后续的 AI 翻译。
![](../../../public/imgs/extract-subtitle.png)
这种预处理步骤大大提高了整个翻译过程的效率和准确性。
## 切分文本
为了进一步优化翻译过程,我们需要将提取出的文本信息重新组织。这一步的目的是**将文本分割成适合 LLM 处理的大小,同时保持上下文的连贯性**。
在本例中,我们采用以下策略:
1. 将文本按照每 40 句为一组进行切分。这个数字是经过多次测试后得出的平衡点,既能保证翻译质量,又不会超出 LLM 的处理能力。
2. 使用 `<T>` 标签分割每句文本。这种标记方法便于后续的重新组装,同时也为 AI 模型提供了清晰的句子边界。
![](../../../public/imgs/cut-text.png)
这种切分方法既考虑了 AI 模型的能力限制,又保证了翻译的连贯性。通过保持适当的上下文,我们可以得到更加准确和自然的翻译结果。
## 格式化原文本
在这一步,我们构建了最终输入给 LLM 的原文本。这个步骤的关键在于如何在控制 tokens 数量的同时,为 AI 提供足够的上下文信息。我们采用了以下策略:
1. **传入所有文本作为背景上下文。这确保 AI 能理解整段对话的语境**。
2. 使用`<TRANSLATE_THIS>`标签明确指出当前需要翻译的片段。这种方法既能控制 AI 的输出范围,又不会丢失整体语境。
![](../../../public/imgs/format-original-text.png)
这种格式化方法使得 AI 能在理解全局的基础上,专注于翻译特定部分,从而提高翻译的准确性和连贯性。
## LLM 翻译
这是整个过程中最关键的一步。我们利用 LLM 的强大能力来实现高质量翻译。在这一步中,我们将之前提到的 “初始翻译 -> 反思 -> 提升翻译” 的过程整合到了同一个提示词中。
这个过程包括以下几个阶段:
1. 第一轮直译:要求 AI 严格按照 `<T>` 标签逐句翻译,保证准确性。
![](../../../public/imgs/ai-translate-1.png)
2. 第二轮意译:允许 AI 自主发挥,对第一轮的结果进行修改和优化。
3. 第三轮反思:AI 对自己的翻译进行评价,从多个角度提出改进建议。
![](../../../public/imgs/ai-translate-2.png)
4. 最后一轮修改:根据反思阶段的建议,AI 对翻译进行最后的调整和优化。
![](../../../public/imgs/ai-translate-3.png)
这种多轮翻译和反思的方法显著提高了翻译质量。它不仅能捕捉原文的准确含义,还能使翻译更加流畅自然。
值得注意的是,这种方法的效果与直接分步执行相当,但工作流更加简洁高效。
## 整合字幕
完成翻译后,我们需要将所有信息重新组合成完整的字幕文件。这一步骤包括:
1. 整合之前分离的序号信息和时间信息。
2. 将翻译好的文本与原文本对应。
3. 使用代码执行模块自动完成组装过程。
![](../../../public/imgs/combine-subtitle.png)
这个过程不仅提高了效率,还最大限度地减少了人为错误的可能性。
## 批量运行
为了处理整个长字幕文件,我们需要一个批量运行机制。这是通过一个简单但有效的判断模块实现的:
1. 检查当前翻译的文本块是否为最后一个。
2. 如果不是,则将工作流重定向到格式化原文本块节点。
3. 取出下一段需要翻译的文本,重新开始翻译和拼接过程。
![](../../../public/imgs/loop-execution.png)
这种循环机制确保了整个长字幕文件能被完整处理,无论字幕有多长。
## 实际应用示例
为了验证这个方法的有效性,我们选取了一段《权力的游戏》的英文字幕,将其翻译成简体中文。可以看出我们的方法不仅能准确翻译内容,还能保持字幕的格式和时间轴信息。
![](../../../public/imgs/gpt-translate-example.png)
## 附件
本工作流完整配置如下,可直接复制,导入到 FastGPT 中。
<details>
<summary>工作流编排配置</summary>
```json
{
"nodes": [
{
"nodeId": "userGuide",
"name": "系统配置",
"intro": "可以配置应用的系统参数",
"avatar": "core/workflow/template/systemConfig",
"flowNodeType": "userGuide",
"position": {
"x": -1453.0815298642474,
"y": 269.10239463914263
},
"version": "481",
"inputs": [
{
"key": "welcomeText",
"renderTypeList": [
"hidden"
],
"valueType": "string",
"label": "core.app.Welcome Text",
"value": ""
},
{
"key": "variables",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "core.app.Chat Variable",
"value": []
},
{
"key": "questionGuide",
"valueType": "boolean",
"renderTypeList": [
"hidden"
],
"label": "core.app.Question Guide",
"value": false
},
{
"key": "tts",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"type": "web"
}
},
{
"key": "whisper",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": {
"open": false,
"autoSend": false,
"autoTTSResponse": false
}
},
{
"key": "scheduleTrigger",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": null
}
],
"outputs": []
},
{
"nodeId": "448745",
"name": "流程开始",
"intro": "",
"avatar": "core/workflow/template/workflowStart",
"flowNodeType": "workflowStart",
"position": {
"x": -1458.2511936623089,
"y": 1218.2790943636066
},
"version": "481",
"inputs": [
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题"
}
],
"outputs": [
{
"id": "userChatInput",
"key": "userChatInput",
"label": "core.module.input.label.user question",
"type": "static",
"valueType": "string"
}
]
},
{
"nodeId": "yjFO3YcM7KG2",
"name": "LLM 翻译",
"intro": "AI 大模型对话",
"avatar": "core/workflow/template/aiChat",
"flowNodeType": "chatNode",
"showStatus": true,
"position": {
"x": 2569.420973631976,
"y": 909.4127366971411
},
"version": "481",
"inputs": [
{
"key": "model",
"renderTypeList": [
"settingLLMModel",
"reference"
],
"label": "core.module.input.label.aiModel",
"valueType": "string",
"selectedTypeIndex": 0,
"value": "claude-3-5-sonnet-20240620"
},
{
"key": "temperature",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 3,
"valueType": "number",
"min": 0,
"max": 10,
"step": 1
},
{
"key": "maxToken",
"renderTypeList": [
"hidden"
],
"label": "",
"value": 4000,
"valueType": "number",
"min": 100,
"max": 4000,
"step": 50
},
{
"key": "isResponseAnswerText",
"renderTypeList": [
"hidden"
],
"label": "",
"value": false,
"valueType": "boolean"
},
{
"key": "quoteTemplate",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "quotePrompt",
"renderTypeList": [
"hidden"
],
"label": "",
"valueType": "string"
},
{
"key": "systemPrompt",
"renderTypeList": [
"textarea",
"reference"
],
"max": 3000,
"valueType": "string",
"label": "core.ai.Prompt",
"description": "core.app.tip.chatNodeSystemPromptTip",
"placeholder": "core.app.tip.chatNodeSystemPromptTip",
"value": "# Role: 资深字幕翻译专家\n\n## Background:\n你是一位经验丰富的{{source_lang}}和{{target_lang}}字幕翻译专家,精通{{source_lang}}和{{target_lang}}互译,尤其擅长将{{source_lang}}字幕译成流畅易懂的{{target_lang}}字幕。你曾多次带领团队完成大型商业电影的字幕翻译项目,所翻译的字幕广受好评。\n\n## Attention:\n- 翻译过程中要始终坚持\"信、达、雅\"的原则,但\"达\"尤为重要\n- 翻译的字幕要符合{{target_lang}}的表达习惯,通俗易懂,连贯流畅\n- 避免使用过于文绉绉的表达和晦涩难懂的典故引用 \n- 诗词歌词等内容需按原文换行和节奏分行,不破坏原排列格式 \n- 翻译对象是字幕,请进入整段文本的语境中对需要翻译的文本段进行翻译\n- <T>是标识每一帧字幕的标签,请严格按照<T>对文本的分割逐帧翻译,每一帧字幕末尾不要加 \\n 回车标识,且第一帧字幕开头不需要加<T>标识\n\n## Constraints:\n- 必须严格遵循四轮翻译流程:直译、意译、反思、提升\n- 译文要忠实原文,准确无误,不能遗漏或曲解原意\n- 最终译文使用Markdown的代码块呈现,但是不用输出markdown这个单词\n- <T>是标识每一帧字幕的标签,请严格按照<T>对文本的分割逐帧翻译,每一帧字幕末尾不要加 \\n 回车标识,且第一帧字幕开头不需要加<T>标识\n\n## Goals:\n- 通过四轮翻译流程,将{{source_lang}}字幕译成高质量的{{target_lang}}字幕\n- 翻译的字幕要准确传达原字幕意思,语言表达力求浅显易懂,朗朗上口 \n\n## Workflow:\n1. 第一轮直译:严格按照<T>逐句翻译,不遗漏任何信息\n2. 第二轮意译:在直译的基础上用通俗流畅的{{target_lang}}意译原文,逐句翻译,保留<T>标识标签\n3. 第三轮反思:仔细审视译文,分点列出一份建设性的批评和有用的建议清单以改进翻译,对每一句话提出建议,从以下四个角度展开\n (i) 准确性(纠正添加、误译、遗漏或未翻译的文本错误),\n (ii) 流畅性(应用{{target_lang}}的语法、拼写和标点规则,并确保没有不必要的重复),\n (iii) 风格(确保翻译反映源文本的风格并考虑其文化背景),\n (iv) 术语(确保术语使用一致且反映源文本所在领域,注意确保使用{{target_lang}}中的等效习语)\n4. 第四轮提升:严格遵循第三轮提出的建议对翻译修改,定稿出一个简洁畅达、符合大众观影习惯的字幕译文,保留<T>标识标签\n\n## OutputFormat:\n- 每一轮前用【思考】说明该轮要点\n- 第一轮和第二轮翻译后用【翻译】呈现译文\n- 第三轮输出建议清单,分点列出,在每一点前用*xxx*标识这条建议对应的要点,如*风格*;建议前用【思考】说明该轮要点,建议后用【建议】呈现建议\n- 第四轮在\\`\\`\\`代码块中展示最终{{target_lang}}字幕文件内容,如\\`\\`\\`xxx\\`\\`\\`\n\n## Suggestions:\n- 直译时力求忠实原文,但注意控制每帧字幕的字数,必要时进行精简压缩\n- 意译时在准确表达原意的基础上,用最朴实无华的{{target_lang}}来表达\n- 反思环节重点关注译文是否符合{{target_lang}}表达习惯,是否通俗易懂,是否准确流畅,是否术语一致\n- 提升环节采用反思环节的建议对意译环节的翻译进行修改,适度采用一些口语化的表达、网络流行语等,增强字幕的亲和力\n- 注意<T>是很重要的标识标签,请确保标签能在正确位置输出"
},
{
"key": "history",
"renderTypeList": [
"numberInput",
"reference"
],
"valueType": "chatHistory",
"label": "core.module.input.label.chat history",
"description": "最多携带多少轮对话记录",
"required": true,
"min": 0,
"max": 50,
"value": 6
},
{
"key": "userChatInput",
"renderTypeList": [
"reference",
"textarea"
],
"valueType": "string",
"label": "用户问题",
"required": true,
"toolDescription": "用户问题",
"value": [
"bxz97Vg4Omux",
"system_text"
]
},
{
"key": "quoteQA",
"renderTypeList": [
"settingDatasetQuotePrompt"
],
"label": "",
"debugLabel": "知识库引用",
"description": "",
"valueType": "datasetQuote"
}
],
"outputs": [
{
"id": "history",
"key": "history",
"required": true,
"label": "core.module.output.label.New context",
"description": "core.module.output.description.New context",
"valueType": "chatHistory",
"type": "static"
},
{
"id": "answerText",
"key": "answerText",
"required": true,
"label": "core.module.output.label.Ai response content",
"description": "core.module.output.description.Ai response content",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "bxz97Vg4Omux",
"name": "LLM 翻译提示词",
"intro": "可对固定或传入的文本进行加工后输出,非字符串类型数据最终会转成字符串类型。",
"avatar": "core/workflow/template/textConcat",
"flowNodeType": "textEditor",
"position": {
"x": 1893.11421220213,
"y": 1065.1299598362698
},
"version": "486",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "可以引用其他节点的输出,作为文本拼接的变量,通过 {{字段名}} 来引用变量",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
}
},
{
"key": "system_textareaInput",
"renderTypeList": [
"textarea"
],
"valueType": "string",
"required": true,
"label": "拼接文本",
"placeholder": "可通过 {{字段名}} 来引用变量",
"value": "你的任务是将文本从{{source_lang}}翻译成{{target_lang}}\n\n源文本如下,由XML标签<SOURCE_TEXT>和</SOURCE_TEXT>分隔:\n\n<SOURCE_TEXT>\n\n{{tagged_text}}\n\n</SOURCE_TEXT>\n\n仅翻译源文本中由<TRANSLATE_THIS>和</TRANSLATE_THIS>分隔的部分,将其余的源文本作为上下文\n\n重申一下,你应该只翻译文本的这一部分,这里再次显示在<TRANSLATE_THIS>和</TRANSLATE_THIS>之间:\n\n<TRANSLATE_THIS>\n\n{{chunk_to_translate}}\n\n</TRANSLATE_THIS>"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "tagged_text",
"label": "tagged_text",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"required": true,
"value": [
"quYZgsW32ApA",
"xhXu6sdEWBnF"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "chunk_to_translate",
"label": "chunk_to_translate",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
}
],
"outputs": [
{
"id": "system_text",
"key": "system_text",
"label": "拼接结果",
"type": "static",
"valueType": "string"
}
]
},
{
"nodeId": "w4heEpNflz59",
"name": "判断是否执行结束",
"intro": "根据一定的条件,执行不同的分支。",
"avatar": "core/workflow/template/ifelse",
"flowNodeType": "ifElseNode",
"showStatus": true,
"position": {
"x": 5625.495682697096,
"y": 1199.9313115831496
},
"version": "481",
"inputs": [
{
"key": "ifElseList",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": [
{
"condition": "AND",
"list": [
{
"variable": [
"a2lqxASWi1vb",
"nmBmGaARbKkl"
],
"condition": "equalTo",
"value": "true"
}
]
}
]
}
],
"outputs": [
{
"id": "ifElseResult",
"key": "ifElseResult",
"label": "判断结果",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "a2lqxASWi1vb",
"name": "判断是否执行结束",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 5099.256084679105,
"y": 1102.1518590433243
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({chunks, currentChunk}){\n const findIndex = chunks.findIndex((item) => item === currentChunk)\n\n return {\n isEnd: chunks.length-1 === findIndex,\n i: findIndex + 1,\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "chunks",
"label": "chunks",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"y3WEYOQ09CGC",
"qLUQfhG0ILRX"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "currentChunk",
"label": "currentChunk",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "nmBmGaARbKkl",
"valueType": "boolean",
"type": "dynamic",
"key": "isEnd",
"label": "isEnd"
},
{
"id": "nqB98uKpq6Ig",
"valueType": "number",
"type": "dynamic",
"key": "i",
"label": "i"
}
]
},
{
"nodeId": "quYZgsW32ApA",
"name": "格式化源文本块",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 1251.2839737092052,
"y": 991.619268503857
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({source_text_chunks, i=0}){\n let before = source_text_chunks.slice(0, i).join(\"\");\n let current = \" <TRANSLATE_THIS>\" + source_text_chunks[i] + \"</TRANSLATE_THIS>\";\n let after = source_text_chunks.slice(i + 1).join(\"\");\n let tagged_text = before + current + after;\n\n return {\n tagged_text,\n chunk_to_translate: source_text_chunks[i],\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "number",
"canEdit": true,
"key": "i",
"label": "i",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"a2lqxASWi1vb",
"nqB98uKpq6Ig"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "source_text_chunks",
"label": "source_text_chunks",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"y3WEYOQ09CGC",
"qLUQfhG0ILRX"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "xhXu6sdEWBnF",
"valueType": "string",
"type": "dynamic",
"key": "tagged_text",
"label": "tagged_text"
},
{
"id": "eCp73lztAEGK",
"valueType": "string",
"type": "dynamic",
"key": "chunk_to_translate",
"label": "chunk_to_translate"
}
]
},
{
"nodeId": "izsNX8FXGD1t",
"name": "指定回复",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": 6399.439691374053,
"y": 1204.4024103331792
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"value": "\n\n*** 字幕反思翻译完成!***"
}
],
"outputs": []
},
{
"nodeId": "vlNHndpNuFXB",
"name": "取出 LLM 翻译第四轮文本",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 3284.6375352131763,
"y": 950.1100995985583
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"editField": {
"key": true,
"valueType": true
},
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({data1}){\n const result = data1.split(\"```\").filter(item => !!item.trim())\n\n if(result[result.length-1]) {\n return {\n result: result[result.length-1].trim() \n }\n }\n\n return {\n result: '未截取到翻译内容'\n }\n}"
},
{
"key": "data1",
"valueType": "string",
"label": "data1",
"renderTypeList": [
"reference"
],
"description": "",
"canEdit": true,
"editField": {
"key": true,
"valueType": true
},
"value": [
"yjFO3YcM7KG2",
"answerText"
],
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "string",
"label": "result"
},
{
"id": "gR0mkQpJ4Og8",
"type": "dynamic",
"key": "data2",
"valueType": "string",
"label": "data2"
}
]
},
{
"nodeId": "qlt9KJbbS9yJ",
"name": "判断源语言和目标语言是否相同",
"intro": "根据一定的条件,执行不同的分支。",
"avatar": "core/workflow/template/ifelse",
"flowNodeType": "ifElseNode",
"showStatus": true,
"position": {
"x": -648.2730659546055,
"y": 1295.3336516652123
},
"version": "481",
"inputs": [
{
"key": "ifElseList",
"renderTypeList": [
"hidden"
],
"valueType": "any",
"label": "",
"value": [
{
"condition": "AND",
"list": [
{
"variable": [
"frjbsrlnJJsR",
"qLUQfhG0ILRX"
],
"condition": "equalTo",
"value": "false"
}
]
}
]
}
],
"outputs": [
{
"id": "ifElseResult",
"key": "ifElseResult",
"label": "判断结果",
"valueType": "string",
"type": "static"
}
]
},
{
"nodeId": "frjbsrlnJJsR",
"name": "判断源语言和目标语言是否相同",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": -1142.9562352499165,
"y": 1031.4486788585432
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({source_lang, target_lang}){\n \n return {\n result: source_lang === target_lang\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "source_lang",
"label": "source_lang",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"VARIABLE_NODE_ID",
"source_lang"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "target_lang",
"label": "target_lang",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"VARIABLE_NODE_ID",
"target_lang"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "boolean",
"label": "result"
}
]
},
{
"nodeId": "dFxrGZS3Wmnz",
"name": "提示源语言与目标语言相同",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": -554.7555863373991,
"y": 1727.175384457058
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 0,
"value": "{{source_lang}} 无需再次翻译为 {{target_lang}} ~"
}
],
"outputs": []
},
{
"nodeId": "tqzmK5oPR9BA",
"name": "输出翻译",
"intro": "该模块可以直接回复一段指定的内容。常用于引导、提示。非字符串内容传入时,会转成字符串进行输出。",
"avatar": "core/workflow/template/reply",
"flowNodeType": "answerNode",
"position": {
"x": 4378.294585712487,
"y": 1268.975092230105
},
"version": "481",
"inputs": [
{
"key": "text",
"renderTypeList": [
"textarea",
"reference"
],
"valueType": "any",
"required": true,
"label": "core.module.input.label.Response content",
"description": "core.module.input.description.Response content",
"placeholder": "core.module.input.description.Response content",
"selectedTypeIndex": 1,
"value": [
"ppPP6o7YYSTJ",
"dYalXmYJ60bj"
]
}
],
"outputs": []
},
{
"nodeId": "kbr342XlxSZR",
"name": "提取字幕信息",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 185.35869756392378,
"y": 1004.6884026918935
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({text}){\n const lines = text.split('\\n');\n const timePattern = /\\d{2}:\\d{2}:\\d{2},\\d{3} --> \\d{2}:\\d{2}:\\d{2},\\d{3}/;\n const numberInfo = [];\n const timeInfo = [];\n const textInfo = [];\n let currentText = [];\n\n // 提取序号、时间戳和文本信息\n lines.forEach(line => {\n if (/^\\d+$/.test(line.trim())) {\n numberInfo.push(line.trim());\n } else if (timePattern.test(line)) {\n timeInfo.push(line);\n if (currentText.length > 0) {\n textInfo.push(currentText.join(' '));\n currentText = [];\n }\n } else if (line.trim() === '') {\n // Skip empty lines\n } else {\n currentText.push(line.trim());\n }\n });\n\n if (currentText.length > 0) {\n textInfo.push(currentText.join(' '));\n }\n\n return { numberInfo, timeInfo, textInfo };\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "text",
"label": "text",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"448745",
"userChatInput"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "h3qVuGhV9HNm",
"valueType": "arrayString",
"type": "dynamic",
"key": "timeInfo",
"label": "timeInfo"
},
{
"id": "zGYRMNA9xGuI",
"valueType": "arrayString",
"type": "dynamic",
"key": "textInfo",
"label": "textInfo"
},
{
"id": "dhzTt6Riz8Dp",
"valueType": "arrayString",
"type": "dynamic",
"key": "numberInfo",
"label": "numberInfo"
}
]
},
{
"nodeId": "ppPP6o7YYSTJ",
"name": "格式化字幕文件",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 3825.553384884565,
"y": 956.4575651844932
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({combinedText, transedText, timeInfo, currentIndex=0,numberInfo}){\n const textLines = combinedText.split('<T>');\n const resultLines = transedText.split('<T>');\n const combinedLines = [];\n\n resultLines.forEach((line, index) => {\n combinedLines.push(numberInfo[currentIndex+index]);\n combinedLines.push(timeInfo[currentIndex+index]);\n combinedLines.push(line)\n combinedLines.push(textLines[index]);\n combinedLines.push('');\n });\n\n const srtContent = combinedLines.join('\\n');\n \n\n return {\n srtContent,\n currentIndex: currentIndex+textLines.length\n }\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "combinedText",
"label": "combinedText",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"quYZgsW32ApA",
"eCp73lztAEGK"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "string",
"canEdit": true,
"key": "transedText",
"label": "transedText",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"vlNHndpNuFXB",
"qLUQfhG0ILRX"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "timeInfo",
"label": "timeInfo",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"h3qVuGhV9HNm"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "number",
"canEdit": true,
"key": "currentIndex",
"label": "currentIndex",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"ppPP6o7YYSTJ",
"u6eqeC0pEPe0"
]
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "numberInfo",
"label": "numberInfo",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"dhzTt6Riz8Dp"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "dYalXmYJ60bj",
"valueType": "string",
"type": "dynamic",
"key": "srtContent",
"label": "srtContent"
},
{
"id": "u6eqeC0pEPe0",
"valueType": "number",
"type": "dynamic",
"key": "currentIndex",
"label": "currentIndex"
}
]
},
{
"nodeId": "y3WEYOQ09CGC",
"name": "切分文本",
"intro": "执行一段简单的脚本代码,通常用于进行复杂的数据处理。",
"avatar": "core/workflow/template/codeRun",
"flowNodeType": "code",
"showStatus": true,
"position": {
"x": 742.138506499589,
"y": 1011.2409789066801
},
"version": "482",
"inputs": [
{
"key": "system_addInputParam",
"renderTypeList": [
"addInputParam"
],
"valueType": "dynamic",
"label": "",
"required": false,
"description": "这些变量会作为代码的运行的输入参数",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
}
},
{
"key": "codeType",
"renderTypeList": [
"hidden"
],
"label": "",
"value": "js"
},
{
"key": "code",
"renderTypeList": [
"custom"
],
"label": "",
"value": "function main({textArray}){\n const groupSize = 20\n const delimiter = '<T>'\n\n const result = [];\n\n for (let i = 0; i < textArray.length; i += groupSize) {\n result.push(textArray.slice(i, i + groupSize).join(delimiter));\n }\n\n return {result};\n}"
},
{
"renderTypeList": [
"reference"
],
"valueType": "arrayString",
"canEdit": true,
"key": "textArray",
"label": "textArray",
"customInputConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": true
},
"required": true,
"value": [
"kbr342XlxSZR",
"zGYRMNA9xGuI"
]
}
],
"outputs": [
{
"id": "system_rawResponse",
"key": "system_rawResponse",
"label": "完整响应数据",
"valueType": "object",
"type": "static"
},
{
"id": "error",
"key": "error",
"label": "运行错误",
"description": "代码运行错误信息,成功时返回空",
"valueType": "object",
"type": "static"
},
{
"id": "system_addOutputParam",
"key": "system_addOutputParam",
"type": "dynamic",
"valueType": "dynamic",
"label": "",
"customFieldConfig": {
"selectValueTypeList": [
"string",
"number",
"boolean",
"object",
"arrayString",
"arrayNumber",
"arrayBoolean",
"arrayObject",
"any",
"chatHistory",
"datasetQuote",
"dynamic",
"selectApp",
"selectDataset"
],
"showDescription": false,
"showDefaultValue": false
},
"description": "将代码中 return 的对象作为输出,传递给后续的节点。变量名需要对应 return 的 key"
},
{
"id": "qLUQfhG0ILRX",
"type": "dynamic",
"key": "result",
"valueType": "arrayString",
"label": "result"
}
]
}
],
"edges": [
{
"source": "bxz97Vg4Omux",
"target": "yjFO3YcM7KG2",
"sourceHandle": "bxz97Vg4Omux-source-right",
"targetHandle": "yjFO3YcM7KG2-target-left"
},
{
"source": "a2lqxASWi1vb",
"target": "w4heEpNflz59",
"sourceHandle": "a2lqxASWi1vb-source-right",
"targetHandle": "w4heEpNflz59-target-left"
},
{
"source": "w4heEpNflz59",
"target": "izsNX8FXGD1t",
"sourceHandle": "w4heEpNflz59-source-IF",
"targetHandle": "izsNX8FXGD1t-target-left"
},
{
"source": "448745",
"target": "frjbsrlnJJsR",
"sourceHandle": "448745-source-right",
"targetHandle": "frjbsrlnJJsR-target-left"
},
{
"source": "frjbsrlnJJsR",
"target": "qlt9KJbbS9yJ",
"sourceHandle": "frjbsrlnJJsR-source-right",
"targetHandle": "qlt9KJbbS9yJ-target-left"
},
{
"source": "tqzmK5oPR9BA",
"target": "a2lqxASWi1vb",
"sourceHandle": "tqzmK5oPR9BA-source-right",
"targetHandle": "a2lqxASWi1vb-target-left"
},
{
"source": "yjFO3YcM7KG2",
"target": "vlNHndpNuFXB",
"sourceHandle": "yjFO3YcM7KG2-source-right",
"targetHandle": "vlNHndpNuFXB-target-left"
},
{
"source": "ppPP6o7YYSTJ",
"target": "tqzmK5oPR9BA",
"sourceHandle": "ppPP6o7YYSTJ-source-right",
"targetHandle": "tqzmK5oPR9BA-target-left"
},
{
"source": "kbr342XlxSZR",
"target": "y3WEYOQ09CGC",
"sourceHandle": "kbr342XlxSZR-source-right",
"targetHandle": "y3WEYOQ09CGC-target-left"
},
{
"source": "y3WEYOQ09CGC",
"target": "quYZgsW32ApA",
"sourceHandle": "y3WEYOQ09CGC-source-right",
"targetHandle": "quYZgsW32ApA-target-left"
},
{
"source": "quYZgsW32ApA",
"target": "bxz97Vg4Omux",
"sourceHandle": "quYZgsW32ApA-source-right",
"targetHandle": "bxz97Vg4Omux-target-left"
},
{
"source": "w4heEpNflz59",
"target": "quYZgsW32ApA",
"sourceHandle": "w4heEpNflz59-source-ELSE",
"targetHandle": "quYZgsW32ApA-target-left"
},
{
"source": "qlt9KJbbS9yJ",
"target": "kbr342XlxSZR",
"sourceHandle": "qlt9KJbbS9yJ-source-IF",
"targetHandle": "kbr342XlxSZR-target-left"
},
{
"source": "qlt9KJbbS9yJ",
"target": "dFxrGZS3Wmnz",
"sourceHandle": "qlt9KJbbS9yJ-source-ELSE",
"targetHandle": "dFxrGZS3Wmnz-target-right"
},
{
"source": "vlNHndpNuFXB",
"target": "ppPP6o7YYSTJ",
"sourceHandle": "vlNHndpNuFXB-source-right",
"targetHandle": "ppPP6o7YYSTJ-target-left"
}
],
"chatConfig": {
"welcomeText": "你好,欢迎使用长字幕反思翻译机器人。\n\n在完成下方设置后,可以直接输入需要翻译的文本",
"variables": [
{
"id": "v98n5b",
"key": "source_lang",
"label": "源语言",
"type": "select",
"required": true,
"maxLen": 50,
"enums": [
{
"value": "简体中文"
},
{
"value": "繁體中文"
},
{
"value": "English"
},
{
"value": "Español"
},
{
"value": "Français"
},
{
"value": "Deutsch"
},
{
"value": "Italiano"
},
{
"value": "日本語"
},
{
"value": "한국어"
},
{
"value": "Русский"
},
{
"value": "العربية"
},
{
"value": "Bahasa Indonesia"
},
{
"value": "Polski"
}
],
"icon": "core/app/variable/select"
},
{
"id": "c3tvge",
"key": "target_lang",
"label": "目标语言",
"type": "select",
"required": true,
"maxLen": 50,
"enums": [
{
"value": "简体中文"
},
{
"value": "繁體中文"
},
{
"value": "English"
},
{
"value": "Español"
},
{
"value": "Français"
},
{
"value": "Deutsch"
},
{
"value": "Italiano"
},
{
"value": "日本語"
},
{
"value": "한국어"
},
{
"value": "Русский"
},
{
"value": "العربية"
},
{
"value": "Bahasa Indonesia"
},
{
"value": "Polski"
}
],
"icon": "core/app/variable/select"
}
],
"scheduledTriggerConfig": {
"cronString": "",
"timezone": "Asia/Shanghai",
"defaultPrompt": ""
},
"_id": "6688b45317c65410d61d58aa"
}
}
```
</details>
---
title: Use Cases
description: FastGPT Use Cases
---
import { Redirect } from '@/components/docs/Redirect';
<Redirect to="/use-cases/app-cases/submit_application_template" />
---
title: 使用案例
description: FastGPT 使用案例
---
import { Redirect } from '@/components/docs/Redirect';
<Redirect to="/use-cases/app-cases/submit_application_template" />
{
"title": "Use Cases",
"description": "More information about FastGPT practical use cases",
"root": true,
"pages": [
"...app-cases"
]
}
{
"title": "使用案例",
"description": "有关 FastGPT 其他实践案例的更多信息",
"root": true,
"pages": [
"...app-cases"
]
}
......@@ -274,7 +274,7 @@
"content/self-host/upgrading/4-14/4149.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-14/4149.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/4-15/4150.mdx": "2026-05-09T16:13:01+08:00",
"content/self-host/upgrading/4-15/41502.mdx": "2026-05-14T17:34:48+08:00",
"content/self-host/upgrading/4-15/41502.mdx": "2026-05-17T18:56:43+08:00",
"content/self-host/upgrading/outdated/40.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/40.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/outdated/41.en.mdx": "2026-04-26T21:08:47+08:00",
......@@ -416,25 +416,5 @@
"content/self-host/upgrading/upgrade-intruction.en.mdx": "2026-04-26T21:08:47+08:00",
"content/self-host/upgrading/upgrade-intruction.mdx": "2026-04-26T21:08:47+08:00",
"content/toc.en.mdx": "2026-05-14T17:58:58+08:00",
"content/toc.mdx": "2026-05-14T17:58:58+08:00",
"content/use-cases/app-cases/dalle3.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/dalle3.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/english_essay_correction_bot.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/english_essay_correction_bot.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/feishu_webhook.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/feishu_webhook.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/fixingEvidence.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/fixingEvidence.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/google_search.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/google_search.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/lab_appointment.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/lab_appointment.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/multi_turn_translation_bot.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/multi_turn_translation_bot.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/submit_application_template.en.mdx": "2026-05-07T15:06:40+08:00",
"content/use-cases/app-cases/submit_application_template.mdx": "2026-05-07T15:06:40+08:00",
"content/use-cases/app-cases/translate-subtitle-using-gpt.en.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/app-cases/translate-subtitle-using-gpt.mdx": "2026-04-26T21:08:47+08:00",
"content/use-cases/index.en.mdx": "2026-05-07T15:06:40+08:00",
"content/use-cases/index.mdx": "2026-05-07T15:06:40+08:00"
"content/toc.mdx": "2026-05-14T17:58:58+08:00"
}
\ No newline at end of file
......@@ -2,7 +2,7 @@
"guide": "Guide",
"version": "Editions",
"api_reference": "API Reference",
"use-cases": "Use Cases",
"selfHost": "Self-Host",
"businessConsultation": "Business Inquiry",
"faq": "FAQ"
}
......@@ -2,7 +2,7 @@
"guide": "使用指南",
"version": "版本介绍",
"api_reference": "API 文档",
"use-cases": "使用场景",
"selfHost": "自部署",
"businessConsultation": "商业咨询",
"faq": "常见问题"
}
......@@ -54,7 +54,7 @@ const exactMap: Record<string, string> = {
// Navbar redirects.
'/guide': defaultHomePath,
'/use-cases': '/use-cases/app-cases/submit_application_template',
'/use-cases': defaultHomePath,
'/self-host': '/self-host/deploy/docker',
'/openapi': '/openapi/intro',
'/faq': '/faq/app'
......
......@@ -6,7 +6,6 @@ const fg = require('fast-glob');
// 黑名单路径(不带语言前缀)
const blacklist = [
'use-cases/index',
'protocol/index',
'api/index',
'faq/index',
......
import type { NextApiResponse } from 'next';
import type { IncomingMessage } from 'node:http';
type ResponseWithWritableAborted = NextApiResponse & {
writableAborted?: boolean;
const getErrorCode = (error: unknown) => {
if (typeof error !== 'object' || error === null || !('code' in error)) {
return '';
}
return String((error as { code?: unknown }).code);
};
const isClientResetSocketError = (error: unknown) => {
const code = getErrorCode(error);
return code === 'ECONNRESET' || code === 'EPIPE';
};
export const createClientAbortTracker = ({
......@@ -13,51 +22,62 @@ export const createClientAbortTracker = ({
res?: NextApiResponse;
}) => {
let clientAborted = false;
let requestAborted = !!req?.aborted;
let responseCompleted = !!(res?.writableEnded || res?.writableFinished);
let responseError = !!res?.errored;
let serverSocketError = false;
// For workflow stopping, "client aborted" means the current response can no longer be written.
// It is intentionally broader than a strict user-initiated cancel audit signal.
/**
* v1 工作流只在客户端主动断开当前响应时停止。
*
* `socket.destroyed`、`res.destroyed`、`writableAborted` 这类快照过宽,不能单独证明用户取消。
* `req.aborted` 是首选信号;但 Next API 运行时下 fetch abort 可能只稳定落到未 finish 的
* `res.close`,因此把 close 作为 fallback。服务端 response/socket error 会屏蔽该 fallback,
* 但客户端 reset 类 socket error 仍属于断开信号,不能抢先屏蔽后续 `req.aborted`/`res.close`。
*/
const responseFinished = () =>
responseCompleted || !!(res?.writableEnded || res?.writableFinished);
const responseWritableAborted = () =>
!!(res as ResponseWithWritableAborted | undefined)?.writableAborted;
const hasExplicitAbort = () => !!(req?.aborted || responseWritableAborted());
const hasBrokenConnection = () => !!(req?.socket?.destroyed || res?.destroyed || res?.errored);
const isAbortedSnapshot = () => {
// A normal completed response may also emit close later. Do not treat that as abort.
if (responseFinished()) return false;
return hasExplicitAbort() || hasBrokenConnection();
};
const responseErrored = () => responseError || serverSocketError || !!res?.errored;
const canAcceptRequestAbort = () => !responseFinished() && !responseErrored();
const isRequestAbortedSnapshot = () =>
(requestAborted || !!req?.aborted) && canAcceptRequestAbort();
const markResponseCompleted = () => {
responseCompleted = true;
};
const markResponseError = () => {
responseError = true;
};
const markSocketError = (error: unknown) => {
if (!isClientResetSocketError(error)) {
serverSocketError = true;
}
};
const markClientAborted = () => {
if (!responseFinished()) {
requestAborted = true;
if (canAcceptRequestAbort()) {
clientAborted = true;
}
};
const markClientAbortedIfConnectionBroken = () => {
if (!responseFinished() && (hasExplicitAbort() || hasBrokenConnection())) {
const markResponseClosed = () => {
if (canAcceptRequestAbort()) {
clientAborted = true;
}
};
req?.on('aborted', markClientAborted);
// close itself is too broad; only stop when paired with explicit abort or a broken connection.
req?.socket?.on('close', markClientAbortedIfConnectionBroken);
req?.socket?.on('error', markSocketError);
res?.on('finish', markResponseCompleted);
res?.on('close', markClientAbortedIfConnectionBroken);
res?.on('error', markClientAborted);
res?.on('error', markResponseError);
res?.on('close', markResponseClosed);
return {
isClientAborted: () => clientAborted || isAbortedSnapshot(),
isClientAborted: () => canAcceptRequestAbort() && (clientAborted || isRequestAbortedSnapshot()),
cleanup: () => {
req?.off('aborted', markClientAborted);
req?.socket?.off('close', markClientAbortedIfConnectionBroken);
req?.socket?.off('error', markSocketError);
res?.off('finish', markResponseCompleted);
res?.off('close', markClientAbortedIfConnectionBroken);
res?.off('error', markClientAborted);
res?.off('error', markResponseError);
res?.off('close', markResponseClosed);
}
};
};
import { describe, expect, it } from 'vitest';
import { EventEmitter } from 'node:events';
import { createServer } from 'node:http';
import type { AddressInfo } from 'node:net';
import { FlowNodeTypeEnum } from '@fastgpt/global/core/workflow/node/constant';
import { WorkflowQueue } from '@fastgpt/service/core/workflow/dispatch/index';
import { createClientAbortTracker } from '@fastgpt/service/core/workflow/dispatch/utils/clientAbort';
import { createNode, createEdge } from '../utils';
const waitWithTimeout = async <T>(promise: Promise<T>, timeoutMs: number, label: string) => {
let timer: ReturnType<typeof setTimeout> | undefined;
try {
return await Promise.race([
promise,
new Promise<never>((_, reject) => {
timer = setTimeout(() => {
reject(new Error(`${label} timed out after ${timeoutMs}ms`));
}, timeoutMs);
})
]);
} finally {
if (timer) {
clearTimeout(timer);
}
}
};
describe('createClientAbortTracker', () => {
const mockRes = (overrides: Record<string, any> = {}) => {
const res = new EventEmitter() as any;
......@@ -28,6 +49,8 @@ describe('createClientAbortTracker', () => {
return req;
};
const mockSocketError = (code: string) => Object.assign(new Error(code), { code });
it('响应正常结束后 close,不应判定为客户端 abort', () => {
const req = mockReq();
const res = mockRes({ writableEnded: true, writableFinished: true });
......@@ -40,18 +63,18 @@ describe('createClientAbortTracker', () => {
tracker.cleanup();
});
it('响应未结束但只有 close,不应判定为客户端 abort', () => {
it('响应未正常结束且无服务端错误时 close,应作为客户端 abort fallback', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.emit('close');
expect(tracker.isClientAborted()).toBe(false);
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('响应未结束且连接已断开时 close,应判定为客户端 abort', () => {
it('响应未结束且连接已断开时 close,应作为客户端 abort fallback', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
......@@ -63,15 +86,14 @@ describe('createClientAbortTracker', () => {
tracker.cleanup();
});
it('响应 writableAborted 时 close,应判定为客户端 abort', () => {
it('响应 writableAborted 但没有 close,不应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.writableAborted = true;
res.emit('close');
expect(tracker.isClientAborted()).toBe(true);
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
......@@ -97,6 +119,114 @@ describe('createClientAbortTracker', () => {
tracker.cleanup();
});
it('请求 aborted 后响应再 close,仍应保持用户主动 abort 状态', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
req.emit('aborted');
res.destroyed = true;
res.emit('close');
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('响应 destroyed 后再观察到请求 aborted,仍应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes({ destroyed: true });
const tracker = createClientAbortTracker({ req, res });
req.emit('aborted');
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('socket error 后触发请求 aborted,不应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
req.socket.emit('error', new Error('server socket error'));
req.emit('aborted');
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('客户端 reset 类 socket error 后触发请求 aborted,应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
req.socket.emit('error', mockSocketError('ECONNRESET'));
req.emit('aborted');
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('客户端 reset 类 socket error 后响应 close,应作为客户端 abort fallback', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
req.socket.emit('error', mockSocketError('EPIPE'));
res.emit('close');
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('响应 close 后再触发服务端 socket error,应回滚客户端 abort fallback', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.emit('close');
req.socket.emit('error', new Error('server socket error'));
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('响应错误触发请求 aborted,不应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.emit('error', new Error('server response error'));
req.emit('aborted');
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('响应 close 后再触发响应 error,应回滚客户端 abort fallback', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.emit('close');
res.emit('error', new Error('server response error'));
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('响应错误后 close,不应判定为用户主动 abort', () => {
const req = mockReq();
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
res.emit('error', new Error('server response error'));
res.emit('close');
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('响应 finish 后 close,不应受 closed 状态误判', () => {
const req = mockReq();
const res = mockRes();
......@@ -119,15 +249,129 @@ describe('createClientAbortTracker', () => {
tracker.cleanup();
});
it('创建 tracker 前连接已经断开,应通过快照判定为客户端 abort', () => {
it('创建 tracker 前连接已经断开,不应通过快照判定为用户主动 abort', () => {
const req = mockReq();
req.socket.destroyed = true;
const res = mockRes({ closed: true });
const tracker = createClientAbortTracker({ req, res });
expect(tracker.isClientAborted()).toBe(false);
tracker.cleanup();
});
it('创建 tracker 前请求已 aborted,应通过快照判定为用户主动 abort', () => {
const req = mockReq();
req.aborted = true;
const res = mockRes();
const tracker = createClientAbortTracker({ req, res });
expect(tracker.isClientAborted()).toBe(true);
tracker.cleanup();
});
it('fetch 使用 AbortController 中断 SSE 后,应让 checkIsStopping 变为 true', async () => {
let resolveServerAbort!: (value: boolean) => void;
const serverAbort = new Promise<boolean>((resolve) => {
resolveServerAbort = resolve;
});
const server = createServer((req, res) => {
const tracker = createClientAbortTracker({ req, res: res as any });
const checkIsStopping = () => tracker.isClientAborted();
res.writeHead(200, {
Connection: 'keep-alive',
'Content-Type': 'text/event-stream;charset=utf-8',
'Cache-Control': 'no-cache, no-transform'
});
res.write('data: first\n\n');
res.on('close', () => {
const aborted = checkIsStopping();
tracker.cleanup();
resolveServerAbort(aborted);
});
});
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
const controller = new AbortController();
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
const response = await fetch(`http://127.0.0.1:${port}/sse`, {
signal: controller.signal
});
reader = response.body?.getReader();
expect(reader).toBeDefined();
const firstChunk = await reader!.read();
expect(firstChunk.done).toBe(false);
controller.abort();
await reader!.read().catch(() => undefined);
expect(await waitWithTimeout(serverAbort, 3000, 'server abort signal')).toBe(true);
} finally {
await reader?.cancel().catch(() => undefined);
server.closeAllConnections();
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
});
it('服务端 socket 异常关闭长连接时,不应让 checkIsStopping 误判为 true', async () => {
let resolveServerAbort!: (value: boolean) => void;
const serverAbort = new Promise<boolean>((resolve) => {
resolveServerAbort = resolve;
});
const server = createServer((req, res) => {
const tracker = createClientAbortTracker({ req, res: res as any });
const checkIsStopping = () => tracker.isClientAborted();
res.writeHead(200, {
Connection: 'keep-alive',
'Content-Type': 'text/event-stream;charset=utf-8',
'Cache-Control': 'no-cache, no-transform'
});
res.write('data: first\n\n');
const destroyTimer = setTimeout(() => {
req.socket.destroy(new Error('server socket unstable close'));
}, 10);
res.on('close', () => {
clearTimeout(destroyTimer);
const aborted = checkIsStopping();
tracker.cleanup();
resolveServerAbort(aborted);
});
});
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
let reader: ReadableStreamDefaultReader<Uint8Array> | undefined;
try {
const response = await fetch(`http://127.0.0.1:${port}/sse`);
reader = response.body?.getReader();
expect(reader).toBeDefined();
const firstChunk = await reader!.read();
expect(firstChunk.done).toBe(false);
await reader!.read().catch(() => undefined);
expect(await waitWithTimeout(serverAbort, 3000, 'server abort signal')).toBe(false);
} finally {
await reader?.cancel().catch(() => undefined);
server.closeAllConnections();
await new Promise<void>((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
});
}
});
});
describe('WorkflowQueue', () => {
......
Subproject commit aa93e7b38d8564d3592c561dd9e76709265a4ed5
Subproject commit cde23cd5f0cda7d89aa8b9ea66b51fa2f0d4fa2d
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment