V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
TyCoding
V2EX  ›  机器学习

同问,如何限制 LLM 响应结构

  •  
  •   TyCoding · 16 天前 · 444 次点击
    其实即便不是 JSON 这种复杂的结构化数据,即使我在 prompt 中限定 “不要返回任何其他解释文字”,再一定概率上仍然会返回解释文字内容,

    例如我只是想实现一个 auto suggestion 的需求,返回给我一个[]数组即可,测试中用 gpt-4o 也无法避免会返回解释文字

    Prompt:
    You need to summarize my previous chat and give 6 similar [questions] that users may ask. Please answer in the array format of ["answer","answer"...], and the [answer] is limited to 20 characters.

    Response:
    An astrolabe is an ancient tool used by astronomers and navigators to measure the altitude of celestial bodies and calculate their positions in the sky.

    ["What is a sextant?","How does a compass work?","What is a sundial?","Explain an armillary sphere.","Define an orrery.","What is a quadrant?"]

    这种情况可能我直接手动处理一下就好了,

    但是同样如果我想要实现复杂的需求,例如我想让 gpt 生成 echarts 的 js 代码,用于直接渲染图表,这种成本就很高了,如果我在 prompt 中写大量的限制可能也没有预期效果并且很浪费 token
    5 条回复    2024-06-03 19:12:32 +08:00
    frankyzf
        1
    frankyzf  
       16 天前
    试试让大模型用 markdown 格式返回代码或 JSON ,然会只处理 markdown 里面的代码或 JSON 会不会好些
    neteroster
        2
    neteroster  
       16 天前
    其实如果用开源模型的话有很多方法可以做到。

    例如说 llama.cpp 就可以用 grammar ,这是直接从采样器上面做限制的,效果会很好。除此之位还有一众更强大的推理约束工具,例如 guidance ( https://github.com/guidance-ai/guidance ), outline ( https://github.com/outlines-dev/outlines ), sglang ( https://github.com/sgl-project/sglang ),它们不止可以限制 json 输出,甚至可以限制输出满足特定的正则表达式 / 形式文法。

    对于在线模型,如果不是复杂的结构,有一些办法,比如 Anthropic 的 API 支持先填充 LLM 响应的前面一部分,对于你这个例子来说,你可以指定前面部分就是 "[",这样模型就会立即开始输出,然后 stop 序列设置成 "]",就会在输出到 "]" 立即截断并返回。
    neteroster
        3
    neteroster  
       16 天前
    @neteroster 对了,在线 API 还有一点忘记提了,就是做 few-shot 。如果你的任务文本不太长,可以先用前面的对话给 LLM 一些例子
    TyCoding
        4
    TyCoding  
    OP
       16 天前
    @frankyzf @neteroster ok 我目前只是先考虑 json_object 这种方式,但是估计对其他模型无效,我看看还是用 function call 或者简化一下 llm 的返回内容,让他尽可能专注于某一项的处理
    frankyzf
        5
    frankyzf  
       16 天前
    @TyCoding 如果是开源的模型,实在不行还可以用 ORPO 来 fine-tuning 模型 [Supported Training Approaches]( https://github.com/hiyouga/LLaMA-Factory?tab=readme-ov-file#supported-training-approaches)
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1039 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 19:27 · PVG 03:27 · LAX 12:27 · JFK 15:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.