LangChain에서 런타임 하이퍼파라미터 튜닝
Source: Dev.to
개요
AI 에이전트를 구축할 때 temperature나 top_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"
)
)
새로운 Temperature 값으로 체인 호출하기
# 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