การผสานรวมกับ API ภายนอก
เชื่อมต่อเอเจนต์กับบริการจากภายนอกและ API เฉพาะขององค์กร เพื่อใช้ประโยชน์จากระบบนิเวศข้อมูลและฟังก์ชันการทำงานที่กว้างขวาง
การผสานรวมกับ API ภายนอก เป็นบทเรียน AI Agents with LangChain & Autonomous Workflows ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Agents with LangChain & Autonomous Workflows และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ
Agents & External APIs
AI agents are powerful, but their knowledge is often limited to their training data. To interact with the real world, they need to fetch live information or perform actions.
This is where External APIs come in! They are the bridge for agents to access a vast ecosystem of services and data.
Tools for External Access
In LangChain, Tools are how agents interact with external systems. Think of them as specialized functions an agent can "call" when needed.
- A tool could search the web.
- Another might fetch weather data.
- Or even send an email!
We'll build tools to wrap API calls.
API: Your Agent's Interface
An API (Application Programming Interface) is a set of rules allowing different software applications to communicate with each other.
When your agent uses an API, it sends a request (like asking a question) and receives a response (the answer or data).
- Endpoint: A specific URL for an API function.
- Request: What your agent sends (e.g., "get me the current weather for London").
- Response: What the API sends back (e.g., weather data in JSON).
Securing API Access
Many external APIs require authentication to ensure only authorized users access their services. Common methods include:
- API Keys: A unique string passed with each request.
- OAuth: A more complex protocol for secure delegated access.
Always keep your API keys secret and never hardcode them directly in your public code!
Python & HTTP Requests
To interact with APIs, Python needs to send HTTP requests. The requests library is the standard way to do this.
Here's how to make a simple GET request to a public API:
import requests
def fetch_joke():
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url)
if response.status_code == 200:
return response.json()
else:
return {"error": "Could not fetch joke."}
if __name__ == "__main__":
joke_data = fetch_joke()
if "error" not in joke_data:
print(f"Setup: {joke_data['setup']}")
print(f"Punchline: {joke_data['punchline']}")
else:
print(joke_data["error"])
From Function to LangChain Tool
Now, let's turn our API-calling function into a LangChain Tool. This involves defining a Pydantic model for the tool's input and wrapping the function.
The agent will use this schema to understand how to call your tool.
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
import requests
# Define the input schema for the tool
class JokeInput(BaseModel):
# Our joke API doesn't need specific input,
# but tools usually define what they expect.
query: str = Field(description="A placeholder query, not used by this API.")
class JokeTool(BaseTool):
name = "get_random_joke"
description = (
"Useful for when you need a random joke. "
"Returns a setup and a punchline."
)
args_schema: type[BaseModel] = JokeInput
def _run(self, query: str):
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url)
if response.status_code == 200:
joke = response.json()
return f"Setup: {joke['setup']}\nPunchline: {joke['punchline']}"
return "Failed to fetch a joke."
async def _arun(self, query: str):
# Asynchronous version (optional, but good practice)
raise NotImplementedError("Asynchronous call not implemented for this tool yet.")
if __name__ == "__main__":
joke_tool = JokeTool()
print(joke_tool._run("tell me a joke"))
Agent with API Tool
With our JokeTool ready, we can now provide it to a LangChain agent. The agent will then decide when and how to use this tool based on the user's prompt.
Remember to initialize your LLM first!
# Assuming you have an OpenAI API key set as an environment variable
# export OPENAI_API_KEY="..."
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
import requests
import os
# Re-define JokeTool for completeness in runnable snippet
class JokeInput(BaseModel):
query: str = Field(description="A placeholder query, not used by this API.")
class JokeTool(BaseTool):
name = "get_random_joke"
description = "Useful for when you need a random joke. Returns a setup and a punchline."
args_schema: type[BaseModel] = JokeInput
def _run(self, query: str):
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url)
if response.status_code == 200:
joke = response.json()
return f"Setup: {joke['setup']}\nPunchline: {joke['punchline']}"
return "Failed to fetch a joke."
async def _arun(self, query: str):
raise NotImplementedError("Async not implemented.")
if __name__ == "__main__":
# Ensure OPENAI_API_KEY is set in environment
if not os.getenv("OPENAI_API_KEY"):
print("Please set your OPENAI_API_KEY environment variable.")
exit()
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
tools = [JokeTool()]
# Get the prompt for the ReAct agent
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
print("Agent is ready!")
# Example usage will be in the next scene.
Agent Using the API Tool
Now, let's ask our agent to tell us a joke. Observe how it uses the get_random_joke tool we provided.
The verbose=True setting helps us see the agent's "thought process" and tool calls.
# This code block assumes the setup from the previous scene
# has been executed and the agent_executor is available.
# In a real interactive environment, you'd run this after Scene 7.
# For demonstration, we re-initialize parts needed for execution
import os
from langchain_openai import ChatOpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub
from langchain.tools import BaseTool
from pydantic import BaseModel, Field
import requests
# Re-define JokeTool for completeness
class JokeInput(BaseModel):
query: str = Field(description="A placeholder query, not used by this API.")
class JokeTool(BaseTool):
name = "get_random_joke"
description = "Useful for when you need a random joke. Returns a setup and a punchline."
args_schema: type[BaseModel] = JokeInput
def _run(self, query: str):
url = "https://official-joke-api.appspot.com/random_joke"
response = requests.get(url)
if response.status_code == 200:
joke = response.json()
return f"Setup: {joke['setup']}\nPunchline: {joke['punchline']}"
return "Failed to fetch a joke."
async def _arun(self, query: str):
raise NotImplementedError("Async not implemented.")
if __name__ == "__main__":
if not os.getenv("OPENAI_API_KEY"):
print("Please set your OPENAI_API_KEY environment variable.")
exit()
llm = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
tools = [JokeTool()]
prompt = hub.pull("hwchase17/react")
agent = create_react_agent(llm, tools, prompt)
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
print("--- Asking the agent for a joke ---")
response = agent_executor.invoke({"input": "Tell me a random joke."})
print("\nAgent's final answer:")
print(response["output"])
Robust API Integration
External APIs can fail due to network issues, rate limits, invalid requests, or server errors. It's crucial to build robust tools that gracefully handle these situations.
- Try-except blocks: Catch network errors.
- Status codes: Check HTTP status codes (e.g., 200 for success, 4xx for client errors, 5xx for server errors).
- Informative messages: Return clear error messages to the agent.
Beyond Simple APIs
The principles learned here extend to more complex APIs. You might encounter:
- APIs requiring specific headers or body data (POST requests).
- Pagination for large datasets.
- Asynchronous calls for long-running operations.
Always consult the API's official documentation!
API Integration Check
You've learned how to empower your agents by connecting them to external APIs. Let's test your understanding.
Recap & Next Steps
Great job! You've learned how to empower your AI agents by connecting them to external APIs.
- APIs expand an agent's capabilities beyond its internal knowledge.
- Custom Tools wrap API calls, providing a structured interface for the agent.
- Authentication and error handling are key for robust integrations.
This skill is fundamental for building truly dynamic and useful AI agents. Keep exploring different APIs!
คำถามที่พบบ่อย
บทเรียน “การผสานรวมกับ API ภายนอก” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “การผสานรวมกับ API ภายนอก” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Agents with LangChain & Autonomous Workflows ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Agents with LangChain & Autonomous Workflows มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การผสานรวมกับ API ภายนอก”
เชื่อมต่อเอเจนต์กับบริการจากภายนอกและ API เฉพาะขององค์กร เพื่อใช้ประโยชน์จากระบบนิเวศข้อมูลและฟังก์ชันการทำงานที่กว้างขวาง คุณปฏิบัติ AI Agents with LangChain & Autonomous Workflows ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Agents with LangChain & Autonomous Workflows หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Agents with LangChain & Autonomous Workflows บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน
บทเรียน “การผสานรวมกับ API ภายนอก” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Agents with LangChain & Autonomous Workflows นี้ได้ไหม
ได้ บทเรียน AI Agents with LangChain & Autonomous Workflows ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การสร้างเครื่องมือ LangChain แบบกำหนดเอง
- การผสานรวมกับ API ภายนอก
- การดึงข้อมูลจากเว็บและการเสริมข้อมูล
- ชุดเครื่องมือและข้อมูลนำเข้าเครื่องมือแบบมีโครงสร้าง