Skip to content
TheChatArchiveThe Chat Archive
Qwenqwen-max-2025-01-25· Alibaba (Qwen)Hugging Face LMArena Human Preference 140K

LangChain을 통해 RAG를 포함한 다양한 에이전트를 function calling으로 활용할 수 있는 방법을 알려줘.

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    LangChain을 통해 RAG를 포함한 다양한 에이전트를 function calling으로 활용할 수 있는 방법을 알려줘.

  2. Qwen Assistant

    LangChain을 사용하여 **RAG(Retrieval-Augmented Generation)**를 포함한 다양한 에이전트를 구현하고, 이를 Function Calling 방식으로 활용하는 방법은 다음과 같이 단계별로 설명할 수 있습니다. 이 접근법은 특히 복잡한 작업을 분리하고, 각 에이전트가 특정 역할(예: 검색, 생성, 추론 등)을 수행하도록 설계된 시스템에 적합합니다.


    1. 기본 개념 이해

    LangChain의 주요 구성 요소

    • LLM (Large Language Model): 대형 언어 모델을 호출하는 핵심 인터페이스.
    • RAG (Retrieval-Augmented Generation):
      • 외부 데이터베이스로부터 관련 정보를 검색(Retrieval).
      • 검색된 정보를 기반으로 LLM이 응답을 생성(Generation).
    • Function Calling:
      • LLM이 특정 함수를 호출하도록 설계된 프레임워크.
      • 예: get_weather(), search_documents()와 같은 함수 호출.

    목표

    • 다양한 에이전트를 LangChain에서 구현하고, 각 에이전트가 특정 역할을 수행하도록 설계.
    • RAG를 활용한 정보 검색 및 생성.
    • Function Calling을 통해 에이전트 간의 협업을 가능하게 함.

    2. 구현 단계

    Step 1: 환경 설정

    LangChain 및 필요한 라이브러리를 설치합니다.

    pip install langchain openai faiss-cpu tiktoken
    

    Step 2: RAG 시스템 구축

    RAG는 두 가지 주요 구성 요소로 이루어집니다:

    1. Retrieval: 외부 데이터베이스에서 관련 문서를 검색.
    2. Generation: 검색된 문서를 기반으로 LLM이 응답을 생성.

    예제: FAISS를 사용한 문서 저장 및 검색

    from langchain.embeddings import OpenAIEmbeddings
    from langchain.vectorstores import FAISS
    from langchain.text_splitter import RecursiveCharacterTextSplitter
    
    # 문서 데이터 준비
    documents = [
        "기후 변화는 전 세계적으로 중요한 문제입니다.",
        "인공지능은 미래의 핵심 기술입니다.",
        "LangChain은 AI 애플리케이션 개발을 쉽게 만듭니다."
    ]
    
    # 텍스트 분할
    text_splitter = RecursiveCharacterTextSplitter(chunk_size=100, chunk_overlap=20)
    texts = text_splitter.create_documents(documents)
    
    # 임베딩 생성 및 FAISS 인덱스 저장
    embeddings = OpenAIEmbeddings()
    db = FAISS.from_documents(texts, embeddings)
    
    # 검색 예제
    query = "기후 변화에 대해 알려줘"
    results = db.similarity_search(query)
    print(results[0].page_content)
    

    Step 3: Function Calling 정의

    OpenAI GPT-4 또는 기타 LLM에서 제공하는 Function Calling을 활용하여 작업을 분리합니다.

    예제: Function Calling을 위한 스키마 정의

    functions = [
        {
            "name": "search_documents",
            "description": "질문과 관련된 문서를 검색합니다.",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "검색할 질문"},
                },
                "required": ["query"],
            },
        },
        {
            "name": "generate_response",
            "description": "검색된 문서를 기반으로 답변을 생성합니다.",
            "parameters": {
                "type": "object",
                "properties": {
                    "context": {"type": "string", "description": "검색된 문서 내용"},
                    "question": {"type": "string", "description": "사용자의 질문"},
                },
                "required": ["context", "question"],
            },
        },
    ]
    

    Step 4: 에이전트 구현

    각 에이전트는 특정 역할을 수행하도록 설계됩니다.

    Agent 1: 문서 검색 에이전트

    def search_documents(query):
        results = db.similarity_search(query)
        return [doc.page_content for doc in results]
    

    Agent 2: 답변 생성 에이전트

    from langchain.llms import OpenAI
    
    def generate_response(context, question):
        llm = OpenAI(model_name="gpt-3.5-turbo")
        prompt = f"문맥: {context}\n질문: {question}\n답변:"
        return llm(prompt)
    

    Step 5: Function Calling 통합

    LLM이 함수 호출을 통해 에이전트를 실행하도록 연결합니다.

    예제: OpenAI API를 사용한 Function Calling

    import json
    from openai import OpenAI
    
    client = OpenAI()
    
    def run_agent(user_input):
        # Step 1: LLM이 함수 호출을 요청
        response = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=[{"role": "user", "content": user_input}],
            functions=functions,
            function_call="auto",
        )
    
        # Step 2: 함수 호출 실행
        if response.choices[0].message.function_call:
            function_name = response.choices[0].message.function_call.name
            arguments = json.loads(response.choices[0].message.function_call.arguments)
    
            if function_name == "search_documents":
                results = search_documents(arguments["query"])
                return {"function": "search_documents", "results": results}
            elif function_name == "generate_response":
                answer = generate_response(arguments["context"], arguments["question"])
                return {"function": "generate_response", "answer": answer}
        else:
            return {"response": response.choices[0].message.content}
    
    # 실행 예제
    result = run_agent("기후 변화에 대해 알려줘")
    print(result)
    

    3. 확장 가능성

    1. 다중 에이전트 협업

    • Orchestrator Agent: 여러 에이전트를 조율하는 역할.
    • Task-Specific Agents: 검색, 생성, 추론 등 특정 작업을 담당.

    예제: Orchestrator 구현

    def orchestrator(user_input):
        # Step 1: 문서 검색
        search_result = run_agent(user_input)
        if search_result["function"] == "search_documents":
            context = "\n".join(search_result["results"])
    
            # Step 2: 답변 생성
            response = run_agent(f"문맥: {context}\n질문: {user_input}")
            return response["answer"]
    

    2. 복잡한 워크플로우 자동화

    • Chains: LangChain의 Chain을 사용하여 에이전트 간 작업을 연결.
    • Memory: 세션 상태 유지.

    4. 참고 자료


    결론

    LangChain을 통해 RAG와 Function Calling을 결합하면, 복잡한 AI 시스템을 효율적이고 유연하게 구축할 수 있습니다. 각 에이전트는 특정 역할을 수행하며, 이를 조율하여 강력한 멀티모달 애플리케이션을 만들 수 있습니다.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.