การสร้างเครื่องมือ LangChain แบบกำหนดเอง
พัฒนาและผสานรวมเครื่องมือเฉพาะทางของคุณเอง เพื่อขยายฟังก์ชันการทำงานของเอเจนต์ให้เหนือกว่าตัวเลือกสำเร็จรูป
การสร้างเครื่องมือ LangChain แบบกำหนดเอง เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Extend Agent Capabilities
AI agents are powerful, but sometimes they need to perform very specific actions that aren't covered by standard tools. This is where custom tools come in!
Custom tools allow your agent to interact with unique APIs, proprietary databases, or perform highly specialized calculations tailored to your application.
Tools: Agent's Action Kit
In LangChain, a Tool is essentially a function that an agent can call to perform a specific action. Think of it as an item in the agent's utility belt.
- It takes a single string input (e.g., a query, a number).
- It returns a single string output (e.g., a result, an error message).
- The agent uses the tool's description to decide when and how to use it.
Anatomy of a Custom Tool
To build a custom tool, you primarily need two things:
- A standard Python function that contains the logic your tool will execute.
- A way to describe this function (its name, what it does, and what kind of input it expects) to the Large Language Model (LLM).
LangChain provides an easy way to define and expose these functions to your agents.
Crafting the Python Function
First, let's create a simple Python function. This function will be the core logic of our custom tool. Remember, it should ideally take a string and return a string.
Here's an example of a function that calculates the square of a number:
def calculate_square(number_str: str) -> str:
"""Calculates the square of a number."""
try:
number = int(number_str)
return str(number * number)
except ValueError:
return "Error: Input must be a valid integer."Making Tools Agent-Ready
LangChain provides the @tool decorator to easily turn a regular Python function into an agent-callable tool. This decorator automatically infers the tool's schema (inputs, description) for the LLM.
The docstring of your function becomes the tool's description, which is crucial for the LLM to understand its purpose.
from langchain_core.tools import tool
@tool
def calculate_square(number_str: str) -> str:
"""Calculates the square of a number.
Input should be a string representing an integer."""
try:
number = int(number_str)
return str(number * number)
except ValueError:
return "Error: Input must be a valid integer."
# You can test it directly:
# print(calculate_square("7"))
# print(calculate_square("hello"))Equipping Your Agent
Once your custom tool function is defined with the @tool decorator, you need to provide it to your agent. Agents are typically initialized with a list of tools they have access to.
The LLM will then "see" these tools and their descriptions, allowing it to decide when to call them based on the user's prompt.
Agent Setup for Tool Use
Before running our agent with the custom tool, we need a few more pieces:
- An LLM (like OpenAI's GPT models).
- A Prompt Template to guide the LLM's responses.
- The
create_tool_calling_agentfunction to combine the LLM, tools, and prompt. - An Agent Executor to run the agent.
Agent in Action: Custom Square Tool
Let's put it all together! This runnable example shows an agent using our calculate_square custom tool to answer a user's request. Observe the agent's thought process in the output.
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import tool
from langchain.agents import AgentExecutor, create_tool_calling_agent
# IMPORTANT: Set your OpenAI API key in your environment variables
# e.g., export OPENAI_API_KEY='your_key_here'
@tool
def calculate_square(number_str: str) -> str:
"""Calculates the square of a number.
Input should be a string representing an integer."""
try:
number = int(number_str)
return str(number * number)
except ValueError:
return "Error: Input must be a valid integer."
# Define the LLM (replace with your setup if not using OpenAI)
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# Define the tools the agent can use
tools = [calculate_square]
# Create the prompt template
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful assistant. Use the tools provided to answer questions."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}")
])
# Create the agent
agent = create_tool_calling_agent(llm, tools, prompt)
# Create an agent executor with verbosity to see the steps
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Invoke the agent with a question it needs the tool for
result = agent_executor.invoke({"input": "What is the square of 15?"})
print(f"\nAgent's final answer: {result['output']}")Tips for Effective Tools
When designing your custom tools, consider these best practices:
- Clear Descriptions: The tool's docstring is vital. Make it precise so the LLM knows when to use it.
- Robust Error Handling: Build try-except blocks into your tool functions to handle unexpected inputs or external service failures.
- Single Responsibility: Each tool should ideally do one thing well. Avoid making overly complex tools.
- String I/O: Remember, tools typically expect string inputs and return string outputs. Convert types as needed.
Custom Tool Check
Which of the following is the primary purpose of the @tool decorator in LangChain when creating a custom tool?
Custom Tool Power-Up
You've learned how to create and integrate your own custom tools into LangChain agents!
- We saw why custom tools are important for extending agent capabilities.
- We understood the core components: a Python function and its description.
- We used the
@tooldecorator to make functions agent-ready. - Finally, we built a full agent that successfully used our custom tool.
This skill is fundamental for building truly versatile and domain-specific AI agents.
คำถามที่พบบ่อย
บทเรียน “การสร้างเครื่องมือ LangChain แบบกำหนดเอง” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การสร้างเครื่องมือ LangChain แบบกำหนดเอง” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การสร้างเครื่องมือ LangChain แบบกำหนดเอง”
พัฒนาและผสานรวมเครื่องมือเฉพาะทางของคุณเอง เพื่อขยายฟังก์ชันการทำงานของเอเจนต์ให้เหนือกว่าตัวเลือกสำเร็จรูป คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “การสร้างเครื่องมือ LangChain แบบกำหนดเอง” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างเครื่องมือ LangChain แบบกำหนดเอง
- การผสานรวมกับ API ภายนอก
- การดึงข้อมูลจากเว็บและการเสริมข้อมูล
- ชุดเครื่องมือและข้อมูลนำเข้าเครื่องมือแบบมีโครงสร้าง