꾸준하게

[LangChain/LangSmith] Agent 작동 방식 본문

LLM

[LangChain/LangSmith] Agent 작동 방식

yeonsikc 2024. 9. 2. 15:52

LangChain Agent

Ollama를 통해 gemma-2-9b 모델을 띄우고, fastAPI를 통해 간단한 엔드포인트를 만들었다. 터미널 출력을 보니 LLM 모델 혼자서 사람처럼 추론하는 모습이 신기해서 작동과정에 궁금증이 생겼다.

 

우선, 이를 Python상에서 디버깅해보니 다음과 같이 프롬프트 형식으로 내용이 들어간다.

 

agent.agent.llm_chain.prompt.template

 

'Answer the following questions as best you can. You have access to the following tools:\n\nget_today(input_text: str) -> str - 오늘 날짜를 반환합다.\n\nUse the following format:\n\nQuestion: the input question you must answer\nThought: you should always think about what to do\nAction: the action to take, should be one of [get_today]\nAction Input: the input to the action\nObservation: the result of the action\n... (this Thought/Action/Action Input/Observation can repeat N times)\nThought: I now know the final answer\nFinal Answer: the final answer to the original input question\n\nBegin!\n\nQuestion: {input}\nThought:{agent_scratchpad}'

 

 

LangSmith

자세한 작동 과정을 파악하기 위해 LangSmith를 사용해보았다.

우선, 앞서 말한 바와 같이 agent를 정의할 때 설정했던대로 AgentType.ZERO_SHOT_REACT_DESCRIPTION의 프롬프트 형식이 반영이 되어서 LLM 모델에 입력된다.

 

모델은 다음 과정(Throught, Action, Action Input, Observation)을 N번 반복하며 추론을 진행한다.

본 예시에서 LLM 모델은 다음과 같은 추론을 진행하였다.

 

 

 

위에서 agent가 선택한 Action인 get_today함수를 실행하고 그 결과값을 반환받는다.

 

 

get_today 함수로 부터 얻은 return값을 프롬프트에 다시 추가하였으며

최종적으로 모델은 답을 출력하게 된다.

 

 

Terminal 출력 결과

 

Postman 출력 결과

 

Code

from langchain_ollama import ChatOllama
from langchain.callbacks.manager import CallbackManager
from langchain.callbacks.streaming_stdout import StreamingStdOutCallbackHandler
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType

from fastapi import FastAPI
from pydantic import BaseModel
from datetime import datetime

from dotenv import load_dotenv

load_dotenv()


# FastAPI 인스턴스 생성
app = FastAPI()

llm_model = ChatOllama(
    model="gemma2-9b",
    temperature=0,
    callback_manager=CallbackManager([StreamingStdOutCallbackHandler()]),
)

# 날짜를 반환하는 함수 정의
def get_today():
    return datetime.now().strftime("%Y-%m-%d")

# LangChain의 Tool로 사용될 함수 정의
def get_today_tool(input_text: str) -> str:
    return f"오늘 날짜는 {get_today()} 입니다."

# Tool 목록에 함수 추가
tools = [
    Tool(
        name="get_today",
        func=get_today_tool,
        description="오늘 날짜를 반환합니다."
    )
]


# 에이전트 생성
agent = initialize_agent(
    tools=tools,
    llm=llm_model,
    agent_type=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
    verbose=True
)

# 입력 데이터 모델 정의
class TextPrompt(BaseModel):
    prompt: str

# POST 요청을 처리하는 엔드포인트 정의
@app.post("/generate/")
async def generate_text(prompt: TextPrompt):
    try:
        response = agent.run(prompt.prompt)
        return {"generated_text": response}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# Uvicorn을 사용해 앱 실행
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=9999)

'LLM' 카테고리의 다른 글

[vLLM] vLLM API Server 구동 방법  (0) 2025.05.07
[instruction tuning] instruction label masking  (1) 2024.10.16
[PEFT] QLoRA Quantization 적용 대상  (0) 2024.10.15
[RAG] Retrieval 평가지표  (1) 2024.06.18