25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 
 
 
 

63 satır
1.8 KiB

  1. import 'dart:convert';
  2. import 'package:http/http.dart' as http;
  3. // 假设这是一个包含聊天方法的类
  4. class Doubao {
  5. final String apiKey;
  6. final String modelId;
  7. Doubao({required this.apiKey, required this.modelId});
  8. Stream<String> chat(String userMessage) async* {
  9. final client = http.Client();
  10. final url =
  11. Uri.parse('https://ark.cn-beijing.volces.com/api/v3/chat/completions');
  12. final headers = {
  13. 'Content-Type': 'application/json',
  14. 'Authorization': 'Bearer $apiKey',
  15. };
  16. final requestBody = {
  17. "model": modelId,
  18. "messages": [
  19. {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手."},
  20. {"role": "user", "content": userMessage}
  21. ],
  22. "stream": true,
  23. };
  24. try {
  25. final request = http.Request('POST', url)
  26. ..headers.addAll(headers)
  27. ..body = jsonEncode(requestBody);
  28. final response = await client.send(request);
  29. //流式处理响应数据
  30. await for (final chunk in response.stream
  31. .transform(utf8.decoder)
  32. .transform(const LineSplitter())) {
  33. if (chunk.isEmpty) continue;
  34. // 假设豆包API使用类似OpenAI的流式格式(data: {...})
  35. if (chunk.startsWith('data:')) {
  36. final jsonStr = chunk.substring(5).trim();
  37. if (jsonStr == '[DONE]') break; // 流结束标志
  38. try {
  39. final data = jsonDecode(jsonStr);
  40. final content = data['choices'][0]['delta']['content'] ?? '';
  41. if (content.isNotEmpty) {
  42. yield content; // 逐块返回生成的文本
  43. }
  44. } catch (e) {
  45. print('JSON解析错误: $e');
  46. }
  47. print('请求成功: $jsonStr');
  48. }
  49. }
  50. } catch (e) {
  51. print('请求异常: $e');
  52. }
  53. }
  54. }