如何从Databricks模型服务端点返回生成器实现流式输出?
解决方案
1. 启用MLflow服务的流式支持
部署模型服务时必须显式开启流式响应,否则服务会默认以非流式方式处理,导致predict_stream的生成器无法正确返回。使用mlflow models serve命令时添加--enable-streaming参数:
mlflow models serve -m models:/stream_model/latest --enable-streaming -p 5001
如果是基于Kubernetes等容器化部署,需确保服务的HTTP配置支持chunked transfer encoding,这是流式响应的基础。
2. 规范predict_stream方法实现
确保生成器返回的每个元素是可序列化的基础类型(字符串、字典等),同时将前置的块检索等同步逻辑放在流式生成前执行:
import mlflow from openai import OpenAI class StreamableRAGModel(mlflow.pyfunc.PythonModel): def predict_stream(self, context, model_input, params=None): # 执行前置同步流程:查询改写、意图识别、块检索(耗时3-4秒) rewritten_query = self._rewrite_query(model_input[0]) intent = self._recognize_intent(rewritten_query) retrieved_chunks = self._retrieve_chunks(rewritten_query, intent) # 启动OpenAI流式生成 client = OpenAI() stream = client.chat.completions.create( model="gpt-3.5-turbo", messages=[ {"role": "system", "content": f"基于以下检索到的内容回答用户问题:{retrieved_chunks}"}, {"role": "user", "content": rewritten_query} ], stream=True ) # 逐个yield生成的内容块 for chunk in stream: content = chunk.choices[0].delta.content if content: yield content # 以下为自定义业务逻辑示例 def _rewrite_query(self, raw_query): # 你的查询改写实现 return raw_query def _recognize_intent(self, query): # 你的意图识别实现 return "qa_intent" def _retrieve_chunks(self, query, intent): # 你的块检索实现 return "检索到的相关文档内容..."
注意:如果需要返回结构化数据,可将内容序列化为JSON字符串后yield,确保MLflow能正确处理。
3. 使用流式兼容的请求方式调用服务
调用服务时必须使用支持流式响应的请求方式,避免普通同步请求导致的响应异常:
- 用curl调用:
curl -X POST --no-buffer http://localhost:5001/invocations -H "Content-Type: application/json" -d '{"data": ["如何优化MLflow流式响应?"]}'
- 用Python调用:
import requests response = requests.post( "http://localhost:5001/invocations", json={"data": ["如何优化MLflow流式响应?"]}, headers={"Content-Type": "application/json"}, stream=True ) for chunk in response.iter_content(chunk_size=None, decode_unicode=True): if chunk: print(chunk, end="")
4. 确保MLflow版本兼容性
流式PyFunc模型支持从MLflow 2.8.0版本开始引入,建议使用2.8.0及以上版本:
# 检查当前版本 mlflow --version # 升级到最新稳定版 pip install --upgrade mlflow
内容的提问来源于stack exchange,提问作者silenthunter25
相关产品推荐
相关产品推荐

