怎么设置碰到指定文字就停止生成?
查看完整题解
参考回答
直接回答
在 llama-server 的补全请求里可以传 stop 字符串列表。生成流匹配到其中一个字符串时,服务端可以结束并从正文里去掉触发的字符串。不同接口返回的结束标志有差异,原生 /completion 还给出 stopping_word。
讲清原理
停止字符串可以跨多个 token。流式客户端不能只看某一个 token 是否等于停止串,最好交给服务端判断。模型自身的结束 token 和最大生成数也会结束输出。终端补全工具的 --reverse-prompt 还可用来在交互时把输入权交还给用户。
例子与易错点
若希望模型只输出一条记录,可以在约定的下一条记录标记处停止。切忌把普通的逗号设为停止串,否则模型刚答出半句话就没了。下面用微型模型比较有无同一停止串时的返回。
set -eu
python3 - <<'PYTHON'
import json
import socket
import subprocess
import time
from urllib.error import URLError
from urllib.request import Request, urlopen
with socket.socket() as listener:
listener.bind(("127.0.0.1", 0))
port = listener.getsockname()[1]
base = f"http://127.0.0.1:{port}"
args = ["llama-server", "-m", "stories260K.gguf",
"--host", "127.0.0.1", "--port", str(port),
"-c", "128", "-np", "1", "-t", "1", "-ngl", "0", "--no-warmup"]
with subprocess.Popen(args, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) as server:
try:
for _ in range(200):
if server.poll() is not None:
raise RuntimeError("llama-server 提前退出")
try:
with urlopen(base + "/health", timeout=1) as response:
if json.load(response)["status"] == "ok":
break
except URLError:
pass
time.sleep(0.05)
else:
raise RuntimeError("模型未就绪")
def complete(stop):
data = {"prompt": "Once upon a time", "n_predict": 4,
"temperature": 0, "stop": stop, "cache_prompt": False}
request = Request(base + "/completion", json.dumps(data).encode(),
{"Content-Type": "application/json"})
with urlopen(request, timeout=5) as response:
return json.load(response)
plain = complete([])
limited = complete([" there was"])
assert plain["content"] == ", there was a"
assert limited["stopping_word"] == " there was"
assert limited["content"] == ","
print("匹配跨 token 的停止串,正文只留下逗号")
finally:
server.terminate()
try:
server.wait(timeout=5)
except subprocess.TimeoutExpired:
server.kill()
server.wait()
PYTHON
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。