找回密码
 立即注册
首页 业界区 安全 应用引入LLM实践-一次性输出和流式输出(思维链) ...

应用引入LLM实践-一次性输出和流式输出(思维链)

篁瞑普 2025-6-1 18:24:28
在大模型应用时,有的场景希望根据prompt要求一次性输出结果,有的场景则希望输出整个思维过程以及最后的结果。
这部分在网上看了一些文章说的都不一样,自己尝试了一下,正确的写法是这样的,记录一下。
一次性输出:
1.gif
2.gif
  1. from openai import OpenAI
  2. def generate_huoshan(prompt):
  3.     client = OpenAI(
  4.     # 从环境变量中读取您的方舟API Key
  5.         api_key="**",
  6.         base_url="https://ark.cn-beijing.volces.com/api/v3",
  7.         # 深度推理模型耗费时间会较长,建议您设置一个较长的超时时间,推荐为30分钟
  8.         timeout=1800,
  9.     )
  10.     response = client.chat.completions.create(
  11.         model="deepseek-r1-250120",
  12.         messages=[
  13.             {"role": "system", "content": "You are a professional market research assistant who needs to accurately obtain retail price information for specified electronic products in a specific market"},
  14.             {"role": "user", "content": prompt},
  15.         ],
  16.         max_tokens=1024,
  17.         temperature=0.6,
  18.         stream=False
  19.     )
  20.     answer = response.choices[0].message.content
  21.     return answer.strip()
复制代码
View Code流式输出:
3.gif
4.gif
  1. from openai import OpenAI
  2. def generate_huoshan(prompt):
  3.     client = OpenAI(
  4.         api_key="*",
  5.         base_url="https://ark.cn-beijing.volces.com/api/v3",
  6.         # 深度推理模型耗费时间会较长,建议您设置一个较长的超时时间,推荐为30分钟
  7.         timeout=1800,
  8.     )
  9.     response = client.chat.completions.create(
  10.     model="deepseek-r1-250120",
  11.     messages=[
  12.     {"role": "system", "content": "You are a professional market research assistant who needs to accurately obtain retail price information for specified electronic products in a specific market"},
  13.     {"role": "user", "content": prompt},
  14.     ],
  15.     max_tokens=1024,
  16.     temperature=0.6,
  17.     stream=True
  18.     )
  19.     for chunk in response:
  20.         delta = chunk.choices[0].delta
  21.         # 优先提取思维链内容
  22.         if hasattr(delta, 'reasoning_content') and delta.reasoning_content:
  23.             yield delta.reasoning_content
  24.             #print(f"[推理过程] {delta.reasoning_content}", end="\n", flush=True)
  25.         # 处理最终回答内容
  26.         elif delta.content:
  27.             yield delta.content
  28.             #print(f"[最终回答] {delta.content}", end="", flush=True)
  29.         else:
  30.             continue
复制代码
View Code外层通过这样返回:
5.gif
6.gif
  1.    def generate_stream():
  2.         try:
  3.             for chunk in generate_text(model_name, prompt):
  4.                 #yield chunk
  5.                 yield json.dumps({"msg": "Success", "code": 200, "data": chunk})+ '\n'
  6.                
  7.         except Exception as e:
  8.                 yield json.dumps({"code": 500, "message": str(e)})+ '\n'  # Yield a JSON string
  9.     headers = {
  10.         'Content-Type':'text/event-stream',
  11.         'Cache-Control': 'no-cache',
  12.         'X-Accel-Buffering':'no',
  13.     }
  14.     return Response(generate_stream(), mimetype='text/event-stream',headers=headers)
复制代码
View Code然后,前端相应做解析即可。

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册