LangChain 中的运行时超参数调优

发布: (2026年2月10日 GMT+8 01:45)
3 分钟阅读
原文: Dev.to

Source: Dev.to

概览

在构建 AI 代理时,temperaturetop_p 等参数通常在应用启动时就被固定。然而,不同的请求可能需要不同的行为:

  • 代码生成 – 需要 temperature=0.0(严格)
  • 创意写作 – 需要 temperature=0.8(富有创意)

LangChain 的 configurable_fields 允许你在运行时修改 LLM 的内部属性。Streamlit UI 通过滑块捕获用户输入;这些元数据被存储在一个 Configuration 对象中,并随同提示一起在链中传递。

graph LR
    User -->|Slides Temp to 0.9| Streamlit
    Streamlit -->|Constructs Config| Config["config = {configurable: {llm_temperature: 0.9}}"]

    subgraph LangChain Runtime
        Prompt --> Chain
        Config --> Chain
        Chain -->|Injects Params| LLM[Ollama LLM]
    end

    LLM --> Output

你不需要将 LLM 包装在专门的路由器中——只需暴露其内部字段即可。

使用默认值设置 LLM

from langchain_ollama import OllamaLLM
from langchain.schema import ConfigurableField

# 1. 使用默认参数初始化 LLM
llm = OllamaLLM(model="llama3.2", temperature=0.5)

为运行时配置暴露 temperature 字段

# 2. 使 temperature 在运行时可配置
configurable_llm = llm.configurable_fields(
    temperature=ConfigurableField(
        id="llm_temperature",
        name="LLM Temperature",
        description="The creativity of the model"
    )
)

使用新温度调用链

# 3. 在调用时传入新的 temperature 值
chain.invoke(
    {"input": "Write a poem"},
    config={"configurable": {"llm_temperature": 0.9}}
)

实际场景

  • 多租户应用 – 用户 A 想要一个富有创意的机器人,而用户 B 更倾向于严格的机器人。相同的后端实例可以通过为每个请求调整 temperature 来同时服务两者。
  • 自适应代理 – 代理可能先使用 temperature=0.0 提取数据,然后再使用 temperature=0.7 进行创意摘要。
  • 测试与调优 – 无需重启脚本即可快速迭代提示设置的“最佳点”。

仓库

完整示例代码已在 GitHub 仓库中提供:

https://github.com/harishkotra/langchain-ollama-cookbook/tree/main/02_temp_tuner_agent

0 浏览
Back to Blog

相关文章

阅读更多 »

解锁笔记本电脑 GPU 的隐藏力量

概述:大多数现代笔记本电脑都配备了强大的 GPU,但往往未被充分利用。无论你是运行本地 LLM 的软件工程师,还是数据科学家……