|
|
发表于 2025-7-27 14:41:40
|
显示全部楼层
- stream = client.chat.completions.create(
- model="deepseek-ai/DeepSeek-R1",
- messages=messages,
- stream=True,
- stream_options={"include_usage": True}
- )
- print("\nDeepSeek:", end="", flush=True)
- assistant_response = ""
- has_printed_thinking = False # 控制是否显示思考过程分隔线
- has_printed_answer = False # 控制正式回答分隔线
- for chunk in stream:
- if chunk.choices:
- # 如果需要显示思考过程,可根据 delta 内容判断
- if hasattr(chunk.choices[0].delta, 'reasoning_content'):
- reasoning = chunk.choices[0].delta.reasoning_content or ""
- if not has_printed_thinking and reasoning.strip():
- print("\n-------- Think -------->\n")
- has_printed_thinking = True
- # 如果不希望实时打印思考过程,可以注释下面这一行
- print(reasoning, end="", flush=True)
- if hasattr(chunk.choices[0].delta, 'content'):
- content = chunk.choices[0].delta.content or ""
- if not has_printed_answer and content.strip():
- print("\n<------- Answer ---------\n")
- has_printed_answer = True
- assistant_response += content
- print(content, end="", flush=True)
- if chunk.usage:
- # 打印消耗的 tokens 信息
- print("\n======= 消耗信息 =======")
- print(f"本次消耗:prompt_tokens -> {chunk.usage.prompt_tokens}, completion_tokens -> {chunk.usage.completion_tokens}, total_tokens -> {chunk.usage.total_tokens}")
- print("========================")
复制代码 |
|