通过vllm部署大语言模型并进行流式输出推理结果
1、启动vllm的命令:
python -m vllm.entrypoints.openai.api_server \
--model /home/zhangfanxp/aiproject/Phi-4-mini-instruct \
--gpu-memory-utilization 0.85 \
--max-num-seqs 8 \
--tensor-parallel-size 1 \
--max-model-len 4096 \
--dtype float16 \
--host 127.0.0.1 \
--port 5000
---------------------------------------------------------
2、执行推理的python代码,test.py:
import openai
client = openai.OpenAI(
base_url="http://localhost:5000/v1",
api_key="no-key-required"
)
def stream_generation(prompt):
response = client.chat.completions.create(
model="/home/zhangfanxp/aiproject/Phi-4-mini-instruct",
messages=[{"role": "user", "content": prompt}],
temperature=0.3,
max_tokens=2048,
stream=True,
)
for chunk in response:
if chunk.choices and chunk.choices[0].delta.content:
yield chunk.choices[0].delta.content
# 测试不同类别的问题
questions = [
"为什么冬天会冷?",
]
for idx, q in enumerate(questions):
print(f"问题 {idx+1}: {q}")
print("回答: ", end="", flush=True) # 不换行并立即刷新缓冲区
full_response = ""
for word in stream_generation(q):
print(word, end="", flush=True) # 逐字打印不换行
full_response += word
print("\n" + "="*50 + "\n") # 最后换行加分隔线
---------------------------------------------------
3、在安装了openai库的虚拟环境中运行python代码:
python test.py
python test.py
评论
发表评论