核心问题
Qwen3.5 思考时间过长,关闭思考模式后,
速度提升一个数量级。
重要结论
目前
只有 Ollama 原生协议支持关闭思考。
OpenAI 兼容接口(/v1/chat/completions)
无效。
错误写法(无效)
错误写法 1
def stream_chat(client, messages, model=MODEL, enable_think=DEFAULT_ENABLE_THINK):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
stream=True,
extra_body={
"chat_template_kwargs": {
"enable_thinking": enable_think
}
}
)
except Exception as e:
pass
错误写法 2
def stream_chat(client, messages, model=MODEL, think=DEFAULT_THINK):
try:
response = client.chat.completions.create(
model=model,
messages=messages,
stream=True,
extra_body={
"think": think
}
)
except Exception as e:
pass
以上两种都无效!
正确写法(100% 可用)
1. API 地址(必须用原生)
OLLAMA_API = "http://localhost:11434/api/chat"
2. 正确请求参数
payload = {
"model": model,
"messages": messages,
"stream": True,
"think": enable_think # True=开启思考,False=关闭思考
}
3. 完整可用代码
def stream_chat(messages, model=MODEL, enable_think=True):
payload = {
"model": model,
"messages": messages,
"stream": True,
"think": enable_think
}
try:
response = requests.post(OLLAMA_API, json=payload, stream=True)
response.raise_for_status()
for line in response.iter_lines():
if line:
data = json.loads(line.decode('utf-8'))
# 输出思考内容(灰色)
if 'think' in data and data['think']:
yield f"\033[90m[思考] {data['think']}\033[0m\n"
# 输出正式回答
if 'message' in data and 'content' in data['message']:
yield data['message']['content']
except Exception as e:
print(f"错误:{e}", file=sys.stderr)
sys.exit(1)
关键规则
-
必须使用 Ollama 原生接口
/api/chat -
必须使用原生参数
think: True/False - OpenAI 兼容接口不支持关闭思考
- 实测 Qwen3.5-9B 可用
- 同样适用于 GLM4.7Flash 等带思考模式的模型