共计 1591 个字符,预计需要花费 4 分钟才能阅读完成。
移动端集成 LLM 的典型痛点
开发移动端 AI 应用时,我们常遇到三个核心挑战:

- 网络抖动问题 :移动网络环境不稳定,导致 API 调用失败率显著高于 PC 端
- 会话状态管理 :App 切换后台后进程容易被系统回收,对话上下文丢失
- 性能开销 :大模型响应可能包含数千 token,直接渲染会导致 UI 卡顿
技术方案选型对比
原生 SDK 方案
- 优点:
- 内置网络重试和缓存机制
- 提供平台专属优化(如 Android 的 WorkManager)
- 缺点:
- 跨平台一致性差
- 依赖特定版本可能引发冲突
REST API 方案
- 优点:
- 跨平台统一接口
- 灵活控制请求逻辑
- 注意事项:
- 必须实现指数退避重试
- 需要处理流式响应分块
核心实现代码
带指数退避的 API 重试
Future<Response> _retryRequest(Future<Response> Function() request,
{int maxRetries = 3}) async {
int attempt = 0;
while (true) {
try {return await request();
} catch (e) {if (++attempt > maxRetries) rethrow;
await Future.delayed(Duration(seconds: pow(2, attempt).toInt()));
}
}
}
流式消息解析
final client = Client();
final streamedResponse = await client.send(Request('POST', Uri.parse('https://api.openai.com/v1/chat/completions'))
..headers.addAll({'Authorization': 'Bearer $apiKey'})
..body = jsonEncode({
'model': 'gpt-3.5-turbo',
'stream': true,
'messages': [/*...*/]
}));
await for (var chunk in streamedResponse.stream
.transform(utf8.decoder)
.transform(const LineSplitter())) {if (chunk.startsWith('data:')) {
try {final data = jsonDecode(chunk.substring(6));
if (data['choices'] != null) {yield data['choices'][0]['delta']['content'] ?? '';
}
} catch (e) {debugPrint('Parse error: $e');
}
}
}
避坑指南
敏感数据存储
- 使用 flutter_secure_storage 保存 API 密钥
- Android 配置 KeyStore,iOS 启用 Keychain
保持后台运行
// Android
void setupForegroundService() {
const AndroidNotificationDetails notificationDetails = /*...*/;
FlutterForegroundTask.init(
androidNotificationOptions: notificationDetails,
foregroundTaskOptions: const ForegroundTaskOptions());
}
// iOS
await UIApplication.shared.beginBackgroundTask();
性能优化数据
| 方案 | 首屏响应 (3G) | 流量消耗 (1000token) |
|---|---|---|
| 非流式 | 2.8s | 12KB |
| 流式 | 1.2s | 8KB |
延伸思考
移动端上下文管理需要解决:
1. 进程回收时的状态恢复
2. 多设备同步时的冲突解决
3. 本地缓存与云端的版本控制
可以考虑采用 SQLite 存储对话树 + 操作日志的方案,各位开发者有什么更好的建议?
正文完
