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.
wolfplus 4992fd03d9 add 1 year ago
..
android add 1 year ago
example add 1 year ago
ios add 1 year ago
lib add 1 year ago
IOS_INTEGRATION_LEGACY.md add 1 year ago
LICENSE add 1 year ago
README.md add 1 year ago
SPM_MIGRATION.md add 1 year ago
pubspec.yaml add 1 year ago

README.md

Chat API Plugin

基于 MacPaw OpenAI Swift 库的 Flutter 聊天 API 插件。

功能特性

  • ✅ 支持 OpenAI Chat API 的完整功能
  • ✅ 流式输出支持
  • ✅ 函数调用支持
  • ✅ 多模态支持(文本、图片)
  • ✅ 自定义模型支持
  • ✅ Token 计数估算
  • ✅ 支持自定义 API 端点
  • ✅ 自动 Swift Package Manager (SPM) 集成

安装

1. 启用 Swift Package Manager

确保你的 Flutter 版本 >= 3.24,并启用 SPM 支持:

flutter config --enable-swift-package-manager

2. 添加依赖

在你的 pubspec.yaml 文件中添加:

dependencies:
  chat_api:
    path: ../local_plugins/chat_api

3. iOS 配置

运行以下命令,Flutter 会自动处理 SPM 依赖:

cd your_project
flutter pub get
cd ios
flutter run

首次运行时,Flutter 会自动:

  • 迁移项目到 SPM 结构(如果还没有迁移)
  • 下载并集成 MacPaw OpenAI Swift 包
  • 配置所有必要的依赖

注意:不再需要手动在 Xcode 中添加包依赖!

4. Android 配置

当前 Android 端仅提供占位实现,如需完整功能请使用 iOS 平台。

使用方法

初始化

import 'package:chat_api/chat_api.dart';

final chatApi = ChatApi();

// 初始化
await chatApi.initialize(
  apiKey: 'your-api-key',
  organization: 'your-org-id', // 可选
  model: 'gpt-3.5-turbo', // 默认模型
  baseUrl: 'https://api.openai.com/v1/chat/completions', // 可选,自定义端点
);

发送消息(非流式)

// 创建消息列表
final messages = [
  ChatMessage(
    role: MessageRole.system,
    content: '你是一个有帮助的助手。',
  ),
  ChatMessage(
    role: MessageRole.user,
    content: '你好,请介绍一下你自己。',
  ),
];

// 发送消息
try {
  final response = await chatApi.sendMessage(
    messages: messages,
    temperature: 0.7,
    maxTokens: 1000,
  );
  print('回复: $response');
} catch (e) {
  print('错误: $e');
}

发送消息(流式)

// 监听事件流
chatApi.eventStream.listen((event) {
  switch (event.type) {
    case ChatApiEventType.token:
      // 收到新的token
      print(event.content);
      break;
    case ChatApiEventType.complete:
      // 对话完成
      print('完成');
      break;
    case ChatApiEventType.error:
      // 发生错误
      print('错误: ${event.content}');
      break;
    case ChatApiEventType.functionCall:
      // 函数调用
      print('函数调用: ${event.content}');
      break;
  }
});

// 发送流式消息
await chatApi.sendMessageStream(
  messages: messages,
  temperature: 0.7,
);

函数调用

// 定义函数
final functions = [
  {
    'name': 'get_weather',
    'description': '获取指定位置的天气',
    'parameters': {
      'type': 'object',
      'properties': {
        'location': {
          'type': 'string',
          'description': '城市名称',
        },
      },
      'required': ['location'],
    },
  },
];

// 发送带函数的消息
await chatApi.sendMessageStream(
  messages: messages,
  functions: functions,
);

多模态支持

// 发送带图片的消息
final imageMessage = ChatMessage(
  role: MessageRole.user,
  content: [
    {
      'type': 'text',
      'text': '这张图片里有什么?',
    },
    {
      'type': 'image_url',
      'image_url': {
        'url': 'data:image/jpeg;base64,${base64EncodedImage}',
      },
    },
  ],
);

其他功能

// 获取可用模型列表
final models = await chatApi.getAvailableModels();

// 设置模型
await chatApi.setModel('gpt-4');

// 估算token数量
final tokenCount = await chatApi.countTokens('这是一段测试文本');

// 取消流式请求
await chatApi.cancelStream();

兼容性说明

Swift Package Manager 项目

如果你的项目已启用 SPM(Flutter 3.24+),插件会自动通过 SPM 集成,无需额外配置。

CocoaPods 项目

如果你的项目仍在使用 CocoaPods(或有其他插件未迁移到 SPM),插件会自动降级到 CocoaPods 模式。这种情况下,你需要手动在 Xcode 中添加 OpenAI 包依赖。详见 IOS_INTEGRATION_LEGACY.md。

故障排除

问题:构建失败,提示找不到 OpenAI 模块

解决方案:

  1. 确保已启用 SPM:flutter config --enable-swift-package-manager
  2. 清理并重新构建:
    flutter clean
    cd ios
    rm -rf Pods Podfile.lock
    flutter pub get
    flutter run
    

问题:Xcode 中看不到 Package Dependencies

解决方案: 这可能意味着项目还在使用 CocoaPods 模式。运行 flutter run 应该会自动迁移到 SPM。

注意事项

  1. API 密钥安全:不要将 API 密钥硬编码在代码中,建议使用环境变量或安全存储。
  2. 错误处理:始终使用 try-catch 包装 API 调用以处理可能的错误。
  3. 流式请求:记得在不需要时取消流式请求,避免资源浪费。

许可证

MIT License