외부 API를 도구로 통합
RAG 시스템을 외부 API 및 서비스에 연결해 에이전트가 실시간 데이터를 가져오거나 작업을 수행하도록 합니다.
외부 API를 도구로 통합은(는) CoddyKit의 무료 LangChain / RAG / Vector DBs 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 LangChain / RAG / Vector DBs 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Agents & External APIs
Agents can do more than just generate text! They can interact with the real world by using special functions called "tools." External APIs are perfect for this, allowing agents to fetch real-time data or perform actions.
Tools for Real-World Interaction
In LangChain, a tool is essentially a Python function that an agent can call. These functions can wrap almost anything:
- Searching the web
- Querying a database
- Sending emails
- Interacting with an external API
Tools give agents superpowers, extending their capabilities beyond their internal knowledge.
Crafting an API Tool
To integrate an external API, you first define a standard Python function that makes the API call. Then, you wrap this function using LangChain's Tool class.
The Tool needs:
- A name: How the agent refers to it.
- A description: What the tool does and its expected input.
- The actual function (
func) that performs the action.
Simple Tool Function Example
Let's start with a basic Python function that simulates an API call. This function will "get current time" for a given city.
Notice how the function takes a single string argument, which the agent will provide based on its reasoning.
from langchain.tools import Tool
def get_current_time(city: str) -> str:
"""Gets the current time for a specified city."""
# This would typically make an actual API call
if city.lower() == "london":
return "10:30 AM GMT"
elif city.lower() == "new york":
return "05:30 AM EST"
else:
return "Time not available for that city."
# This function will be wrapped into a Tool later.Agent Using a Simple Tool
Here's a complete example where a LangChain agent uses our get_current_time tool. The agent decides when to call the tool based on the user's query and the tool's description.
Note: You'll need to set your OPENAI_API_KEY environment variable for this to run.
import os
from langchain.tools import Tool
from langchain_openai import OpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub
# Mock function for getting time (simulates API)
def get_current_time(city: str) -> str:
"""Gets the current time for a specified city."""
if city.lower() == "london":
return "10:30 AM GMT"
elif city.lower() == "new york":
return "05:30 AM EST"
else:
return "Time not available for that city."
# Create the LangChain Tool
time_tool = Tool(
name="get_time",
func=get_current_time,
description="Useful for getting the current time for a given city. Input should be a city name (e.g., 'London')."
)
# List of tools available to the agent
tools = [time_tool]
# Initialize the LLM (ensure OPENAI_API_KEY is set)
llm = OpenAI(temperature=0)
# Pull the ReAct prompt template from LangChain Hub
prompt = hub.pull("hwchase17/react")
# Create the agent
agent = create_react_agent(llm, tools, prompt)
# Create the AgentExecutor to run the agent
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Invoke the agent with a query
response = agent_executor.invoke({"input": "What time is it in London?"})
print(response["output"])
Connecting to Real APIs with `requests`
For real-world API interactions, Python's requests library is your go-to. It simplifies making HTTP requests to external services.
Within your tool function, you'll typically send a request, receive an HTTP response, and then parse its content (often JSON) to extract the relevant data.
import requests
def fetch_data_from_api(query: str) -> str:
"""Fetches data from a hypothetical external API."""
try:
# Example: calling a public API (e.g., a mock weather API)
# Replace with your actual API endpoint and parameters
api_url = f"https://api.example.com/data?q={query}" # Placeholder URL
response = requests.get(api_url)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
data = response.json()
return str(data) # Return relevant part of the data
except requests.exceptions.RequestException as e:
return f"Error fetching data: {e}"
# This function would then be wrapped in a LangChain Tool.Building a Weather Tool
Let's create a more practical example: a tool that fetches current weather for a city using a mock weather API. In a real scenario, you'd integrate with a service like OpenWeatherMap.
Notice the detailed description, guiding the LLM on the input format.
import requests
from langchain.tools import Tool
# Mock weather API function
def get_weather_for_city(city: str) -> str:
"""
Fetches the current weather for a specified city.
Uses a mock API for demonstration.
"""
# In a real app, replace with an actual weather API call
mock_weather_data = {
"london": {"temperature": "15C", "conditions": "Cloudy"},
"new york": {"temperature": "22C", "conditions": "Sunny"},
"paris": {"temperature": "18C", "conditions": "Partly Cloudy"}
}
weather = mock_weather_data.get(city.lower())
if weather:
return f"The current weather in {city} is {weather['temperature']} and {weather['conditions']}."
else:
return f"Weather data not available for {city}."
# Create the LangChain Tool for weather
weather_tool = Tool(
name="get_weather",
func=get_weather_for_city,
description="Useful for getting the current weather conditions (temperature, conditions) for a specific city. Input should be a city name (e.g., 'London')."
)
# This tool can now be added to an agent's tool list.Agent Calling Weather API
Now, let's see an agent use our get_weather tool. The agent's reasoning process (if verbose=True) will show it deciding to use the tool, calling it, and then using the result to answer the query.
import os
from langchain.tools import Tool
from langchain_openai import OpenAI
from langchain.agents import AgentExecutor, create_react_agent
from langchain import hub
# Mock weather API function (from previous scene)
def get_weather_for_city(city: str) -> str:
"""
Fetches the current weather for a specified city.
Uses a mock API for demonstration.
"""
mock_weather_data = {
"london": {"temperature": "15C", "conditions": "Cloudy"},
"new york": {"temperature": "22C", "conditions": "Sunny"},
"paris": {"temperature": "18C", "conditions": "Partly Cloudy"}
}
weather = mock_weather_data.get(city.lower())
if weather:
return f"The current weather in {city} is {weather['temperature']} and {weather['conditions']}."
else:
return f"Weather data not available for {city}."
# Create the LangChain Tool for weather
weather_tool = Tool(
name="get_weather",
func=get_weather_for_city,
description="Useful for getting the current weather conditions (temperature, conditions) for a specific city. Input should be a city name (e.g., 'London')."
)
# List of tools available to the agent
tools = [weather_tool]
# Initialize the LLM (ensure OPENAI_API_KEY is set)
llm = OpenAI(temperature=0)
# Pull the ReAct prompt template from LangChain Hub
prompt = hub.pull("hwchase17/react")
# Create the agent
agent = create_react_agent(llm, tools, prompt)
# Create the AgentExecutor to run the agent
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
# Invoke the agent with a query
response = agent_executor.invoke({"input": "What's the weather like in Paris?"})
print(response["output"])
Effective Tool Descriptions
The LLM relies heavily on your tool's description to decide if and how to use it. Make your descriptions:
- Clear and concise: State exactly what the tool does.
- Specific about input: Clearly explain what kind of argument it expects.
- Purpose-driven: Explain *why* the tool is useful or in what scenarios.
- Provide examples: If the input is complex, offer an example format.
A well-crafted description is crucial for an agent's success.
Tool Integration Check
You're building an agent to help users find real-time information. You need to create a tool that fetches current stock prices for a given company ticker (e.g., "AAPL") by calling an external API.
Which of the following describes the most important aspect of the Tool definition for the LLM to understand and use it correctly?
Recap: APIs as Agent Tools
You've learned how to empower LangChain agents by integrating external APIs as tools. This allows your agents to:
- Access real-time data from the internet.
- Perform actions in the real world (like sending emails or updating databases).
- Extend their capabilities far beyond their initial training data.
By wrapping API calls in well-described Tool objects, you significantly enhance your agent's intelligence and utility!
자주 묻는 질문
“외부 API를 도구로 통합” 강의는 무료인가요?
네 — “외부 API를 도구로 통합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 LangChain / RAG / Vector DBs 강의 전체를 잠금 해제할 수 있습니다. LangChain / RAG / Vector DBs 강의에는 총 4개의 강의가 포함되어 있습니다.
“외부 API를 도구로 통합”에서 뭘 배우나요?
RAG 시스템을 외부 API 및 서비스에 연결해 에이전트가 실시간 데이터를 가져오거나 작업을 수행하도록 합니다. 브라우저에서 직접 실행하는 실습 코드로 LangChain / RAG / Vector DBs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
LangChain / RAG / Vector DBs을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 LangChain / RAG / Vector DBs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“외부 API를 도구로 통합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 LangChain / RAG / Vector DBs 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 LangChain / RAG / Vector DBs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.