使用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
相关产品推荐
相关产品推荐

