تعريف الأدوات واستخدامها
تعلّم كيفية إنشاء الأدوات ودمجها لتمكين الوكلاء من تنفيذ إجراءات مثل البحث في الويب أو تشغيل التعليمات البرمجية
تعريف الأدوات واستخدامها درس مجاني في AI Agents with LangChain & Autonomous Workflows على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Agents with LangChain & Autonomous Workflows، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Agents with LangChain & Autonomous Workflows 4 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
Agents Need Tools
Welcome! In this lesson, we'll explore how AI agents can go beyond just talking. While Large Language Models (LLMs) are great at understanding and generating text, they have limitations.
They can't access real-time information, perform calculations, or interact with external systems. This is where tools come in!
Extending Agent Capabilities
Think of tools as the agent's 'hands' and 'eyes' to the outside world. They allow an agent to:
- Search the web: Get up-to-date information.
- Execute code: Perform calculations or run scripts.
- Access databases: Retrieve specific data.
- Interact with APIs: Control smart devices, send emails, etc.
Tools transform a conversational LLM into an active, problem-solving agent.
Tool's Core Components
In LangChain, a tool is essentially a function that an agent can call. Every tool needs three core components:
- Function (
func): The actual Python code that performs the action. - Name (
name): A unique string identifier for the tool. - Description (
description): A clear, concise explanation of what the tool does and when it should be used. This helps the LLM decide if and when to use the tool.
Crafting a Tool Function
Let's start by defining a simple Python function. This function will simulate getting weather information. This is the 'action' part of our future tool.
Notice the location: str type hint. This helps define what input the function expects.
def get_current_weather(location: str) -> str:
"""Get the current weather in a given location."""
# In a real application, this would call an external API.
if location == "London":
return "It's 15 degrees Celsius and cloudy."
elif location == "New York":
return "It's 22 degrees Celsius and sunny."
else:
return "Weather data not available for this location."Making it a LangChain Tool
Now, let's wrap our get_current_weather function into a LangChain Tool object. We'll give it a name and a helpful description. You can run this snippet to see the tool's properties.
from langchain.tools import Tool
def get_current_weather(location: str) -> str:
"""Get the current weather in a given location."""
if location == "London":
return "It's 15 degrees Celsius and cloudy."
elif location == "New York":
return "It's 22 degrees Celsius and sunny."
else:
return "Weather data not available for this location."
# Create the Tool object
weather_tool = Tool(
name="get_current_weather",
func=get_current_weather,
description="Useful for getting the current weather in a specific location."
)
if __name__ == "__main__":
print(f"Tool name: {weather_tool.name}")
print(f"Tool description: {weather_tool.description}")
print(f"Weather in London (direct call): {weather_tool.func('London')}")Agent Chooses Wisely
Once you've defined your Tool objects, you pass a list of them to your LangChain agent. The LLM within the agent then uses its reasoning capabilities to decide:
- If a tool is needed for the current user query.
- Which tool to use from the available list.
- What arguments to pass to the chosen tool.
This decision is heavily influenced by the tool's description.
Equipping Your Agent (Conceptual)
While a full runnable agent requires an LLM API key, conceptually, this is how you'd equip an agent with our weather_tool. The agent is 'initialized' with a list of tools it can use.
When you ask the agent a question like "What's the weather in Paris?", it will read the description of weather_tool and decide to call its function with "Paris" as the argument.
from langchain.agents import initialize_agent, AgentType
from langchain.tools import Tool
# from langchain_openai import ChatOpenAI # Requires API key
# Assume weather_tool is defined as before
def get_current_weather(location: str) -> str:
return "Weather data..." # Simplified for concept
weather_tool = Tool(
name="get_current_weather",
func=get_current_weather,
description="Useful for getting the current weather."
)
# This part needs an actual LLM setup, e.g.:
# llm = ChatOpenAI(temperature=0, model="gpt-3.5-turbo")
# agent = initialize_agent(
# [weather_tool],
# llm,
# agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
# verbose=True
# )
# The agent then uses the tool based on query.Clear Descriptions are Key
The description of your tool is paramount. It's the only way the LLM understands its purpose.
- Be specific: Clearly state what the tool does.
- Mention inputs: What information does it need?
- State outputs: What kind of result does it return?
- Guide usage: When should the agent consider using this tool?
A poorly described tool will either be ignored or used incorrectly by the agent.
Structured Tool Inputs (Pydantic)
For more complex tools, you can ensure the agent provides arguments in a specific format using Pydantic. This helps validate inputs and makes your tools robust.
We define a BaseModel that describes the expected inputs. LangChain uses this to guide the LLM's argument generation.
from langchain.tools import Tool
from pydantic import BaseModel, Field
from typing import Type
# Define a Pydantic model for the tool's input
class WeatherInput(BaseModel):
location: str = Field(description="The city and state, e.g., San Francisco, CA")
def get_current_weather_with_schema(location: str) -> str:
"""Get the current weather in a given location."""
if location == "London":
return "It's 15 degrees Celsius and cloudy."
elif location == "New York":
return "It's 22 degrees Celsius and sunny."
else:
return "Weather data not available for this location."
weather_tool_schema = Tool(
name="get_current_weather",
func=get_current_weather_with_schema,
description="Useful for getting the current weather in a specific location.",
args_schema=WeatherInput # Link the Pydantic schema here
)
if __name__ == "__main__":
print(f"Tool with schema: {weather_tool_schema.name}")
print(f"Expected input fields: {weather_tool_schema.args_schema.schema()['properties']}")Check Your Understanding
Consider the role of tools in LangChain agents.
Tools: Agents' Superpowers
You've successfully started your journey into equipping AI agents with tools! We learned that:
- Tools are functions that extend an agent's capabilities beyond its inherent LLM knowledge.
- Every tool needs a function, a unique name, and a clear description.
- Good descriptions are vital for the LLM to choose and use tools correctly.
- Pydantic schemas can provide structured input validation for tools.
Next, we'll explore different agent types and how they make decisions about using these tools!
الأسئلة الشائعة
هل درس «تعريف الأدوات واستخدامها» مجاني؟
نعم — نص درس «تعريف الأدوات واستخدامها» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Agents with LangChain & Autonomous Workflows، انتقل إلى CoddyKit PRO. تتضمن دورة AI Agents with LangChain & Autonomous Workflows 4 دروس في المجموع.
ماذا ستتعلم في «تعريف الأدوات واستخدامها»؟
تعلّم كيفية إنشاء الأدوات ودمجها لتمكين الوكلاء من تنفيذ إجراءات مثل البحث في الويب أو تشغيل التعليمات البرمجية تتمرن على AI Agents with LangChain & Autonomous Workflows مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ AI Agents with LangChain & Autonomous Workflows؟
لا تُشترط خبرة سابقة. AI Agents with LangChain & Autonomous Workflows على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.
كم من الوقت يستغرق درس «تعريف الأدوات واستخدامها»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس AI Agents with LangChain & Autonomous Workflows هذا؟
نعم. كل درس في AI Agents with LangChain & Autonomous Workflows يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تعريف الأدوات واستخدامها
- أنواع الوكلاء واتخاذ القرارات
- الاستفادة من حِزم الأدوات الجاهزة
- معالجة الأخطاء والتنفيذ الآمن للأدوات