test_ai_stream.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import requests
  2. import json
  3. import os
  4. api_key = "a1800657-9212-4afe-9b7c-b49f015c54d3"
  5. api_url = "https://ark.cn-beijing.volces.com/api/v3/responses"
  6. prompt = "你看见了什么?"
  7. image_url = "https://ark-project.tos-cn-beijing.volces.com/doc_image/ark_demo_img_1.png"
  8. payload = {
  9. "model": "doubao-seed-1-8-251228",
  10. "stream": True,
  11. "input": [
  12. {
  13. "role": "user",
  14. "content": [
  15. {
  16. "type": "input_image",
  17. "image_url": image_url
  18. },
  19. {
  20. "type": "input_text",
  21. "text": prompt
  22. }
  23. ]
  24. }
  25. ]
  26. }
  27. headers = {
  28. "Authorization": f"Bearer {api_key}",
  29. "Content-Type": "application/json"
  30. }
  31. print("开始请求 AI 接口...")
  32. try:
  33. with requests.post(api_url, json=payload, headers=headers, stream=True, timeout=30) as r:
  34. print(f"状态码: {r.status_code}")
  35. if r.status_code != 200:
  36. print(f"错误内容: {r.text}")
  37. else:
  38. print("开始接收流式数据:")
  39. for line in r.iter_lines():
  40. if line:
  41. line_str = line.decode('utf-8')
  42. print(f"收到行: {line_str}")
  43. if line_str.startswith('data: '):
  44. json_str = line_str[6:]
  45. if json_str.strip() == '[DONE]':
  46. print("流结束")
  47. break
  48. try:
  49. chunk = json.loads(json_str)
  50. if 'choices' in chunk and len(chunk['choices']) > 0:
  51. delta = chunk['choices'][0].get('delta', {})
  52. if 'content' in delta:
  53. print(f"内容片段: {delta['content']}", end="", flush=True)
  54. except Exception as e:
  55. print(f"\n解析错误: {e}")
  56. print("\n请求完成")
  57. except Exception as e:
  58. print(f"请求发生异常: {e}")