본문 바로가기
강의록~스터디/LangChain

[4주차] ReAct Agent 만들기

by annmunju 2024. 4. 2.

과정 요약

[참고] langchain==0.0.352

 

@tool 데코레이터를 이용한 함수 작성

- Doc string을 도구 설명으로 사용하기 때문에 필히 작성 해야함.

from langchain.tools import tool

@tool
def search(query: str) -> str:
    """Look up things online."""
    return "LangChain"

 

 프롬프트 작성

- 무료 프롬프트 공유 허브 : https://smith.langchain.com/
- 공식 문서 : https://docs.smith.langchain.com/overview 

 

LangSmith

 

 

smith.langchain.com

- 사용 방법

from langchain import hub
obj = hub.pull("{LangSmith에 등록되어 있는 프롬프트의 작성자/제목}")

 

도구(tools)를 사용하는 프롬프트 코드 작성

@tool
def get_text_length(text: str) -> int:
    """Returns the length of a text by characters"""
    return len(text)

def find_tool_by_name(tools: List[Tool], tool_name:str) -> Tool:
    for tool in tools:
        if tool.name == tool_name:
            return tool
    raise ValueError(f"Tool with name {tool_name}.")

if __name__ == "__main__":
    tools = [get_text_length] 
    template = obj.template.replace("{agent_scratchpad}", "")
    prompt = PromptTemplate.from_template(template=template).partial(
        tools=render.render_text_description(tools), tool_names=", ".join([t.name for t in tools])
    )

    llm = ChatOpenAI(temperature=0, model_kwargs={"stop": ["\nObservation"]})
    agent = {"input": lambda x: x["input"]} | prompt | llm | ReActSingleInputOutputParser() # LCEL 
    
    agent_step: Union[AgentAction, AgentFinish] = agent.invoke({"input" : "What is the length in characters of the text DOG?"})
    
    if isinstance(agent_step, AgentAction):
        tool_name = agent_step.tool
        tool_to_use = find_tool_by_name(tools, tool_name)
        tool_input = agent_step.tool_input
        
        observation = tool_to_use.func(str(tool_input))
        print(f"{observation=}")

 

728x90