You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Ollama流式输出Mistral7b响应时首段多余空格的移除方法

移除Ollama流式返回Mistral7b响应开头的多余空格

当使用Ollama流式调用Mistral7b模型时,首个返回片段左侧会出现多余空格,导致输出内容开头有额外空格。原代码如下:

import ollama

stream = ollama.chat(
  model='mistral',
  messages=[{'role': 'user', 'content': 'Name an engineer that passes the vibe check'}],
  stream=True
)

for chunk in stream:
  print(chunk['message']['content'], end='', flush=True)

可以通过以下两种方式解决:

  • 精准处理首个片段(推荐):添加标记变量判断是否为首个返回片段,仅对其执行左空格移除操作,不影响后续片段的正常内容:
import ollama

stream = ollama.chat(
  model='mistral',
  messages=[{'role': 'user', 'content': 'Name an engineer that passes the vibe check'}],
  stream=True
)

is_first_chunk = True
for chunk in stream:
    content = chunk['message']['content']
    if is_first_chunk:
        content = content.lstrip()
        is_first_chunk = False
    print(content, end='', flush=True)
  • 全局移除所有片段左空格:此方式会移除所有返回片段左侧的空格,仅适合确认后续片段不存在合法开头空格的场景:
import ollama

stream = ollama.chat(
  model='mistral',
  messages=[{'role': 'user', 'content': 'Name an engineer that passes the vibe check'}],
  stream=True
)

for chunk in stream:
    print(chunk['message']['content'].lstrip(), end='', flush=True)

内容的提问来源于stack exchange,提问作者noocoder777

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 20:32:05