|
- import 'dart:convert';
- import 'package:http/http.dart' as http;
-
- // 假设这是一个包含聊天方法的类
- class Doubao {
- final String apiKey;
- final String modelId;
- Doubao({required this.apiKey, required this.modelId});
-
- Stream<String> chat(String userMessage) async* {
- final client = http.Client();
- final url =
- Uri.parse('https://ark.cn-beijing.volces.com/api/v3/chat/completions');
-
- final headers = {
- 'Content-Type': 'application/json',
- 'Authorization': 'Bearer $apiKey',
- };
-
- final requestBody = {
- "model": modelId,
- "messages": [
- {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手."},
- {"role": "user", "content": userMessage}
- ],
- "stream": true,
- };
-
- try {
- final request = http.Request('POST', url)
- ..headers.addAll(headers)
- ..body = jsonEncode(requestBody);
-
- final response = await client.send(request);
- //流式处理响应数据
- await for (final chunk in response.stream
- .transform(utf8.decoder)
- .transform(const LineSplitter())) {
- if (chunk.isEmpty) continue;
-
- // 假设豆包API使用类似OpenAI的流式格式(data: {...})
- if (chunk.startsWith('data:')) {
- final jsonStr = chunk.substring(5).trim();
- if (jsonStr == '[DONE]') break; // 流结束标志
-
- try {
- final data = jsonDecode(jsonStr);
- final content = data['choices'][0]['delta']['content'] ?? '';
- if (content.isNotEmpty) {
- yield content; // 逐块返回生成的文本
- }
- } catch (e) {
- print('JSON解析错误: $e');
- }
- print('请求成功: $jsonStr');
- }
- }
- } catch (e) {
- print('请求异常: $e');
- }
- }
- }
|