You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
1 year ago | |
|---|---|---|
| .. | ||
| android | 1 year ago | |
| lib | 1 year ago | |
| README.md | 1 year ago | |
| pubspec.yaml | 1 year ago | |
README.md
OpenAI API 与 MCP 集成插件
这个 Flutter 插件提供了 OpenAI API 的访问能力和 Model Context Protocol (MCP) 工具调用功能的集成。
功能特点
- 使用官方 OpenAI Java SDK 进行异步通信
- 集成官方 MCP Kotlin SDK,使用 SSE 模式
- 支持流式输出响应
- 支持工具调用和结果处理
- 支持带图片的多模态对话
MCP 集成
本插件使用 MCP 官方 Kotlin SDK 实现与 MCP 服务器的通信。通过 SSE(Server-Sent Events)模式连接,能够:
- 获取 MCP 服务器提供的所有工具定义
- 动态调用远程工具并获取结果
- 支持本地工具的注册和调用
- 在 OpenAI API 请求中无缝集成工具调用功能
安装
在项目的 pubspec.yaml 中添加本地插件依赖:
dependencies:
open_ai:
path: local_plugins/open_ai
使用方法
初始化
import 'package:open_ai/open_ai.dart';
final openAI = OpenAI();
await openAI.initialize(
apiKey: 'your-api-key',
baseUrl: 'https://api.example.com', // 可选,默认为 OpenAI 官方 API
model: 'gpt-3.5-turbo', // 可选,默认为 gpt-3.5-turbo
mcpServer: 'https://mcp.example.com', // MCP 服务器 SSE 端点地址
);
创建消息
// 创建系统消息
final systemMessage = await openAI.createSystemMessage('你是一个助手');
// 创建用户消息
final userMessage = await openAI.createUserMessage('你好,请帮我解释一下量子力学');
// 创建助手消息
final assistantMessage = await openAI.createAssistantMessage('我可以帮你解释量子力学');
// 创建带图片的用户消息
final imageBase64 = '...'; // base64编码的图片数据
final userImageMessage = await openAI.createUserMessageWithImage(
'这张图片中的物体是什么?',
imageBase64
);
发送消息(非流式输出)
final messages = [systemMessage, userMessage];
final response = await openAI.sendMessage(messages);
print('AI回复: $response');
发送消息(流式输出)
final messages = [systemMessage, userMessage];
final callback = StreamCallback(
onToken: (token) {
// 处理单个令牌
print('收到令牌: $token');
},
onComplete: () {
// 处理完成事件
print('响应完成');
},
onError: (error) {
// 处理错误
print('发生错误: $error');
},
onFunctionCall: (functionCall) {
// 处理函数调用
print('函数调用: $functionCall');
},
onFunctionCallResult: (functionCall, result) {
// 处理函数调用结果
print('函数调用结果: $result');
},
);
final streamId = await openAI.sendMessageStream(messages, callback);
取消当前流式请求
final success = await openAI.cancelCurrentStream();
释放资源
await openAI.dispose();
异常处理
该插件会在操作失败时抛出异常,请使用 try-catch 块捕获它们:
try {
final response = await openAI.sendMessage(messages);
} catch (e) {
print('发生错误: $e');
}
注意事项
- 初始化插件时必须提供有效的 API 密钥
- 使用流式响应时,请确保在完成后调用
dispose()方法释放资源 - MCP 功能需要有效的 MCP 服务器 SSE 端点地址才能工作