Flutter服务代理插件lite_agent_core_dart_server的使用
Flutter服务代理插件lite_agent_core_dart_server的使用
特性
- 支持纯文本代理,无需JSON Spec。
- 支持OpenAPI/OpenRPC/OpenModbus/OpenTool JSON Spec。
- 支持LLM函数调用到HTTP API/json-rpc 2.0 over HTTP/Modbus等自定义工具。
- HTTP服务器包装器Lite Agent核心Dart。
- 基于Lite Agent核心AgentService(包含DTO),添加Controller、Router,包装为HTTP/WS API。
使用
1. 准备
- 需要一些OpenSpec json文件,根据
/example/json/open*/*.json
文件进行调用。 - 运行你的工具服务器,这些信息在json文件中描述。
- 在
example
文件夹中添加.env
文件,并在.env
文件中添加以下内容:baseUrl = https://xxx.xxx.com # LLM API BaseURL apiKey = sk-xxxxxxxxxxxxxxxxxxxx # LLM API ApiKey
2. 开发运行服务器
- 在调试模式或运行模式下运行
/bin/server.dart
文件的main()
方法。
3. HTTP/WS API
- HTTP API
- WebSocket API
- 典型交互
3.1 HTTP API
- 会话控制命令,包括:
/version
:获取版本号,确认服务器正在运行。/init
:初始化新会话,服务器返回会话ID。/history
:获取未被清除的会话消息。/stop
:停止会话,当当前消息完成后,不会运行下一个消息。/clear
:清除会话上下文消息,并关闭WebSocket连接。
BaseURL
http://127.0.0.1:9527/api
[GET] /version
- 功能:获取版本号,确认服务器正在运行。
- 请求参数:空
- 响应体示例:
{ "version": "0.3.0" }
[POST] /init
- 功能:初始化新会话代理。
- 请求体:
- LLM配置:baseUrl, apiKey, model
- 系统提示:代理角色,待办事项/不待办事项描述
- 工具描述:(可选)openapi, openrpc, openmodbus Spec。根据Spec中的第三方API设置apiKey或不设置。
- 会话列表:(可选)支持多代理。初始化其他代理,并将它们的会话ID添加到此字段。
- 超时:默认3600秒。当代理停止时,消息上下文将被清除。
- 示例:
{ "llmConfig": { "baseUrl": "<LLM API baseUrl, e.g. https://api.openai.com/v1>", "apiKey": "<LLM API apiKey, e.g. sk-xxxxxxxxxx>", "model": "<LLM API model name, e.g. gpt-3.5-turbo. And temperature、maxTokens、topP can be changed below >", "temperature": 0, "maxTokens": 4096, "topP": 1 }, "systemPrompt": "<System Prompt. LLM character, capabilities, need to help user fixed what problems>", "openSpecList": [ { "openSpec": "<(Optional) tool spec json string, support openapi、openmodbus、openrpc>", "apiKey": { "type": "<basic or bearer>", "apiKey": "<Third APIs apiKey>" }, "protocol": "Support openapi, openmodbus, jsonrpcHttp" }, { "openSpec": "<(Optional) Another spec json string, can be another protocol>", "protocol": "Support openapi, openmodbus, jsonrpcHttp" } ], "sessionList": [ { "id": "<Sub Agent sessionId 1>" }, { "id": "<Sub Agent sessionId 2>" } ], "timeoutSeconds": 3600 }
- 响应体:
- 会话ID,将用于订阅、停止和清除操作。
- 示例:
{ "id": "b2ac9280-70d6-4651-bd3a-45eb81cd8c30" }
[GET] /history?id=<sessionId>
- 响应体:
- 代理消息上下文作为列表。
- 示例:
[ { "sessionId": "b2ac9280-70d6-4651-bd3a-45eb81cd8c30", "from": "system | user | agent | llm | tool", "to": "user | agent | llm | tool | client", "type": "text | imageUrl | functionCallList | toolReturn | contentList", "message": "<need to parse according type>", "completions": { "tokenUsage": { "promptTokens": 100, "completionTokens": 522, "totalTokens": 622 }, "id": "chatcmpl-9bgYkOjpdtLV0o0JugSmnNzGrRFMG", "model": "gpt-3.5-turbo" }, "createTime": "2023-06-18T15:45:30.000+0800" } ]
[GET] /stop?id=<sessionId>
- 响应体:
- 会话ID,以确认会话的操作。
- 示例:
{ "id": "b2ac9280-70d6-4651-bd3a-45eb81cd8c30" }
[GET] /clear?id=<sessionId>
- 响应体:
- 会话ID,以确认会话的操作。
- 示例:
{ "id": "b2ac9280-70d6-4651-bd3a-45eb81cd8c30" }
3.2 WebSocket API
- 发送和订阅会话代理消息。
Endpoint
ws://127.0.0.1:9527/api/chat?id=<sessionId>
3.2.1 alive
- 客户端发送ping到服务器。
- 服务器响应pong给客户端。
3.2.2 客户端发送UserMessageDto列表到服务器
- 客户端([UserMessageDto]) -> 服务器:封装并发送到服务器。
- 示例:
[ { "type": "text", "message": "Get some tool status" } ]
{ "taskId": "Optional. For identify which task AgentMessage from. If NULL, server will create one.", "contentList": [ { "type": "text", "message": "Get some tool status" } ] }
3.2.3 服务器反馈AgentMessage到客户端
- 客户端 <- 服务器(AgentMessage):服务器将持续向客户端发送AgentMessage。
- 示例:
{ "sessionId": "b2ac9280-70d6-4651-bd3a-45eb81cd8c30", "taskId": "0b127f1d-4667-4a52-bbcb-0b636f9a471a", "from": "system | user | agent | llm | tool", "to": "user | agent | llm | tool | client", "type": "text | imageUrl | functionCallList | toolReturn | contentList", "message": "<need to parse according type>", "completions": { "tokenUsage": { "promptTokens": 100, "completionTokens": 522, "totalTokens": 622 }, "id": "chatcmpl-9bgYkOjpdtLV0o0JugSmnNzGrRFMG", "model": "gpt-3.5-turbo" }, "createTime": "2023-06-18T15:45:30.000+0800" }
- 根据
type
解析message
- text、imageUrl:
- 字符串
- 示例:
"Tool result: PASS"
- functionCallList:
- 结构:
[ { "id":"<LLM respond id in function call>", "name":"<function name>", "parameters": "<LLM respond parameters in map>" } ]
- 示例:
[ { "id":"call_z5FK2dAfU8TXzn61IJXzRl5I", "name":"SomeFunction", "parameters": { "operation":"result" } } ]
- toolReturn:
- 结构:
{ "id":"<LLM respond id in function call>", "result": "<JSON Map, different tools in defferent result>" }
- 示例:
{ "id":"call_z5FK2dAfU8TXzn61IJXzRl5I", "result": { "statusCode":200, "body":"{\"code\":200,\"message\":\"PASS\"}" } }
- contentList:
- 结构:
[ { "type":"text | imageUrl", "message":"String" } ]
- 示例:
[ { "type":"text", "message":"What’s in this image?" }, { "type":"imageUrl", "message":"https://www.xxx.com/xxx.jpg" } ]
- text、imageUrl:
- 当to=Client时,消息状态如下:
"[TASK_START]"
:代理收到用户消息,准备运行任务。"[TOOLS_START]"
:准备调用工具。"[TOOLS_DONE]"
:工具返回完成。"[TASK_STOP]"
:代理收到停止或清除命令,停止任务。"[TASK_DONE]"
:代理完成任务。
3.3 典型交互
[/init request] {llmConfig: ..., systemPrompt:..., openSpecList: [...]}
[/init response SessionId] {id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a}
[After /chat connect ws, send userTaskDto] {taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a, contentList: [{type: text, message: Get some tool status}]}
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔗CLIENT: [text] [TASK_START]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 👤USER -> 🤖AGENT: [text] Get some tool status
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 💡LLM: [text] Get some tool status
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 💡LLM -> 🤖AGENT: [functionCallList] [{"id":"call_73xLVZDe70QgLHsURgY5BNT0","name":"SomeFunction","parameters":{"operation":"result"}}]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔧TOOL: [functionCallList] [{"id":"call_73xLVZDe70QgLHsURgY5BNT0","name":"SomeFunction","parameters":{"operation":"result"}}]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔗CLIENT: [text] [TOOLS_START]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🔧TOOL -> 🤖AGENT: [toolReturn] {"id":"call_73xLVZDe70QgLHsURgY5BNT0","result":{"statusCode":200,"body":"{\"code\":200,\"message\":\"FAIL\"}"}}
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 💡LLM: [toolReturn] {"id":"call_73xLVZDe70QgLHsURgY5BNT0","result":{"statusCode":200,"body":"{\"code\":200,\"message\":\"FAIL\"}"}}
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🔧TOOL -> 🤖AGENT: [text] [TOOLS_DONE]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔗CLIENT: [text] [TOOLS_DONE]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 💡LLM -> 🤖AGENT: [text] Tool status: FAIL.
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 👤USER: [text] Tool status: FAIL.
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔗CLIENT: [text] [TASK_DONE]
[ws push] id: eccdacc8-a1a8-463f-b0af-7aebc278c842, taskId: 0b127f1d-4667-4a52-bbcb-0b636f9a471a# 🤖AGENT -> 🔗CLIENT: [text] [TASK_STOP]
[/stop request] {id: eccdacc8-a1a8-463f-b0af-7aebc278c842}
[/clear request] {id: eccdacc8-a1a8-463f-b0af-7aebc278c842}
[ws close] WebSocket connection closed
构建与运行
- 在shell脚本中构建:
dart compile exe bin/server.dart -o build/lite_agent_core_dart_server
- 然后
lite_agent_core_dart_server
文件将在build
文件夹中。 - 将
config
(包含config.json
)文件夹复制到lite_agent_core_dart_server
同一文件夹中。 - 在shell脚本中运行:
./lite_agent_core_dart_server
- 终端将显示:
INFO: 2024-06-24 14:48:05.862057: PID 34567: [HTTP] Start Server - http://0.0.0.0:9527/api
- 服务器运行后,将在文件夹中创建
log
文件夹和agent.log
文件,记录服务器运行日志。
Docker
- 构建镜像,进入项目根目录,然后运行:
docker build -t lite_agent_core_dart_server .
- 运行容器:
docker run -d -p 9527:9527 lite_agent_core_dart_server
- 或者挂载配置和日志文件夹以更新配置并获取日志信息:
docker run -d -p 9527:9527 -v ./log:/app/log -v ./config:/app/config lite_agent_core_dart_server
更多关于Flutter服务代理插件lite_agent_core_dart_server的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复
更多关于Flutter服务代理插件lite_agent_core_dart_server的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,以下是一个关于如何在Flutter项目中使用lite_agent_core_dart_server
插件的代码示例。假设你已经在pubspec.yaml
文件中添加了该插件的依赖,并且已经运行了flutter pub get
来安装它。
1. 添加依赖
首先,确保你的pubspec.yaml
文件中包含了lite_agent_core_dart_server
的依赖:
dependencies:
flutter:
sdk: flutter
lite_agent_core_dart_server: ^最新版本号
2. 导入插件并初始化
在你的Dart文件中导入该插件,并进行初始化。通常,你可能会在main.dart
或者一个专门的服务文件中进行初始化。
import 'package:flutter/material.dart';
import 'package:lite_agent_core_dart_server/lite_agent_core_dart_server.dart';
void main() {
// 初始化服务代理插件
LiteAgentCoreDartServer.init();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
3. 使用服务代理插件功能
假设lite_agent_core_dart_server
插件提供了一些方法来与后端服务进行交互,比如发送请求和接收响应。以下是一个简单的示例,展示如何使用这些功能(注意:这里的方法名和功能是基于假设的,你需要参考插件的实际文档):
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String responseData = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo Home Page'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Response Data:',
),
Text(
responseData,
style: TextStyle(fontSize: 20),
),
SizedBox(height: 20),
ElevatedButton(
onPressed: () async {
// 调用插件提供的方法,发送请求到后端服务
String result = await LiteAgentCoreDartServer.sendRequest(
endpoint: 'https://example.com/api/data',
method: 'GET', // 或者 'POST', 'PUT', 'DELETE' 等
headers: {
'Content-Type': 'application/json',
},
body: null, // 如果是POST请求,这里可以是请求体数据
);
// 更新UI以显示响应数据
setState(() {
responseData = result;
});
},
child: Text('Send Request'),
),
],
),
),
);
}
}
注意事项
- 插件文档:务必参考
lite_agent_core_dart_server
插件的官方文档,因为实际使用中的方法名、参数和返回值可能与上述示例有所不同。 - 错误处理:在实际应用中,应该添加错误处理逻辑,以处理网络请求失败或数据解析错误等情况。
- 依赖管理:确保你的Flutter环境和所有依赖项都是最新的,以避免兼容性问题。
希望这个示例能够帮助你在Flutter项目中有效地使用lite_agent_core_dart_server
插件。如果你有更具体的问题或需要进一步的帮助,请查阅插件的官方文档或提出具体问题。