0Pricing
AI Agents with LangChain & Autonomous Workflows · レッスン

初めてのシンプルなエージェントを構築する

手順に沿って環境を設定し、LangChainを使った基本的なAIエージェントを構築します。

「初めてのシンプルなエージェントを構築する」はCoddyKit上の無料AI Agents with LangChain & Autonomous Workflowsレッスンです。 これはレッスン3/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応の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時間対応のAIチューター)、AI Agents with LangChain & Autonomous Workflowsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 AI Agents with LangChain & Autonomous Workflowsコースには全4レッスンが含まれています。

「初めてのシンプルなエージェントを構築する」で何を学びますか?

手順に沿って環境を設定し、LangChainを使った基本的なAIエージェントを構築します。 ブラウザで直接実行するハンズオンコードでAI Agents with LangChain & Autonomous Workflowsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。

AI Agents with LangChain & Autonomous Workflowsを始めるのに経験は必要ですか?

事前経験は必要ありません。CoddyKitのAI Agents with LangChain & Autonomous Workflowsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン3/4です。

「初めてのシンプルなエージェントを構築する」レッスンにはどのくらい時間がかかりますか?

ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。

このAI Agents with LangChain & Autonomous Workflowsレッスンでコードを書いて実行できますか?

はい。すべてのAI Agents with LangChain & Autonomous Workflowsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。

このコースのすべてのレッスン

  1. AIエージェントとLLMを理解する
  2. LangChainのコアコンポーネントを解説
  3. 初めてのシンプルなエージェントを構築する
  4. エージェントにメモリと会話状態を持たせる
← AI Agents with LangChain & Autonomous Workflowsに戻る