0Pricing
AI Agents with LangChain & Autonomous Workflows · 강의

첫 번째 간단한 에이전트 구축

환경을 설정하고 LangChain을 사용하여 기본 인공지능 에이전트를 구축하는 과정을 단계별로 학습합니다.

첫 번째 간단한 에이전트 구축은(는) CoddyKit의 무료 AI Agents with LangChain & Autonomous Workflows 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Agents with LangChain & Autonomous Workflows 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Build Your First Agent!

Time to build your first AI agent with LangChain — connecting an LLM to basic tools so it can answer your queries intelligently.

Set Up Your Python Environment

First, set up Python 3.9+ and a virtual environment to isolate dependencies. Create one with venv, then activate it before you install anything.

Install LangChain & Dependencies

Now install LangChain and the OpenAI integration. Run the pip command inside your activated virtual environment.

Connect to an LLM

Your agent needs a brain. Initialize ChatOpenAI with your API key stored as the OPENAI_API_KEY environment variable — never hardcode it.

import os
from langchain_openai import ChatOpenAI

def main():
    # In a real setup, ensure OPENAI_API_KEY is set
    # For demonstration, we'll assume it's available
    # os.environ["OPENAI_API_KEY"] = "sk-..." # DON'T hardcode!

    try:
        llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
        print("LLM initialized successfully!")
        # You can test it:
        # response = llm.invoke("Hello, LLM!")
        # print(response.content)
    except Exception as e:
        print(f"Error initializing LLM: {e}")
        print("Please ensure OPENAI_API_KEY is set.")

if __name__ == "__main__":
    main()

Agents Need Tools

An agent is an LLM plus tools — functions or APIs that let it act on the world: search, run code, calculate. Here we give ours a calculator.

import os
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
from langchain_community.utilities import LLMMathChain

def main():
    # Ensure OPENAI_API_KEY is set
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)

    # Create a basic math tool
    llm_math_chain = LLMMathChain.from_llm(llm)
    math_tool = Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="Useful for when you need to answer questions about math."
    )
    tools = [math_tool]
    print("Basic math tool created and ready!")

if __name__ == "__main__":
    main()

Choosing Your Agent Type

The agent type defines how it reasons. We'll use create_react_agent — ReAct means Reason and Act: it plans, observes results, then refines.

Combining Components

Now combine the pieces: create_react_agent takes your LLM, tools, and prompt to build the logic, then AgentExecutor wraps it to make it runnable.

import os
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
from langchain_community.utilities import LLMMathChain
from langchain.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import ChatPromptTemplate

def main():
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    llm_math_chain = LLMMathChain.from_llm(llm)
    math_tool = Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="Useful for when you need to answer questions about math."
    )
    tools = [math_tool]

    # Define the prompt for the agent
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful AI assistant. Use tools when necessary."),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}")
    ])

    # Create the agent
    agent = create_react_agent(llm, tools, prompt)

    # Create the agent executor
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
    print("Agent assembled and ready for action!")

if __name__ == "__main__":
    main()

Asking Your Agent a Question

With the agent assembled, give it a task via invoke. Ask a math question and watch it reach for its calculator tool to answer.

import os
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
from langchain_community.utilities import LLMMathChain
from langchain.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import ChatPromptTemplate

def main():
    llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    llm_math_chain = LLMMathChain.from_llm(llm)
    math_tool = Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="Useful for when you need to answer questions about math."
    )
    tools = [math_tool]

    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful AI assistant. Use tools when necessary."),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}")
    ])

    agent = create_react_agent(llm, tools, prompt)
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

    print("Asking the agent: 'What is 123 multiplied by 456?'")
    response = agent_executor.invoke({"input": "What is 123 multiplied by 456?"})
    print("\nAgent's final answer:")
    print(response["output"])

if __name__ == "__main__":
    main()

Understanding the Agent's Response

With verbose=True you see the agent's thought process: Thought, Action, Action Input, Observation, then Final Answer. That transparency is key to debugging.

Your Complete First Agent!

Here's your complete first agent. Set your API key, run it, and try changing the input question to see it reason through different problems.

import os
from langchain_openai import ChatOpenAI
from langchain.tools import Tool
from langchain_community.utilities import LLMMathChain
from langchain.agents import AgentExecutor, create_react_agent
from langchain_core.prompts import ChatPromptTemplate

def main():
    # 1. Set up your LLM
    # Ensure OPENAI_API_KEY is set as an environment variable
    # os.environ["OPENAI_API_KEY"] = "YOUR_KEY_HERE" # DO NOT hardcode!
    try:
        llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
    except Exception as e:
        print(f"Error: {e}. Please ensure OPENAI_API_KEY is set.")
        return

    # 2. Define your tools
    llm_math_chain = LLMMathChain.from_llm(llm)
    math_tool = Tool.from_function(
        func=llm_math_chain.run,
        name="Calculator",
        description="Useful for when you need to answer questions about math."
    )
    tools = [math_tool]

    # 3. Define the agent's prompt
    prompt = ChatPromptTemplate.from_messages([
        ("system", "You are a helpful AI assistant. Use tools when necessary."),
        ("human", "{input}"),
        ("placeholder", "{agent_scratchpad}")
    ])

    # 4. Create the agent
    agent = create_react_agent(llm, tools, prompt)

    # 5. Create the AgentExecutor
    agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)

    # 6. Run the agent
    print("\n--- Running the Agent ---")
    question = "What is the square root of 144 plus 25?"
    print(f"Agent input: '{question}'")
    response = agent_executor.invoke({"input": question})
    print("\n--- Agent's Final Answer ---")
    print(response["output"])

if __name__ == "__main__":
    main()

Agent Components Check

You've seen how to build a basic agent. Which of the following are essential components when constructing a LangChain agent using create_react_agent?

Recap: Your First Agent!

Recap: you built a real agent — set up the environment, connected an LLM, added a tool, assembled it with create_react_agent and AgentExecutor, and watched it think.

자주 묻는 질문

“첫 번째 간단한 에이전트 구축” 강의는 무료인가요?

네 — “첫 번째 간단한 에이전트 구축” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Agents with LangChain & Autonomous Workflows 강의 전체를 잠금 해제할 수 있습니다. AI Agents with LangChain & Autonomous Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.

“첫 번째 간단한 에이전트 구축”에서 뭘 배우나요?

환경을 설정하고 LangChain을 사용하여 기본 인공지능 에이전트를 구축하는 과정을 단계별로 학습합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Agents with LangChain & Autonomous Workflows을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Agents with LangChain & Autonomous Workflows을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Agents with LangChain & Autonomous Workflows은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“첫 번째 간단한 에이전트 구축” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Agents with LangChain & Autonomous Workflows 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Agents with LangChain & Autonomous Workflows 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 인공지능 에이전트와 LLM 이해하기
  2. LangChain 핵심 구성 요소 해설
  3. 첫 번째 간단한 에이전트 구축
  4. 에이전트에 메모리와 대화 상태 부여하기
← AI Agents with LangChain & Autonomous Workflows(으)로 돌아가기