Smolagents
Smolagents
AgentOps로 Smolagents AI 에이전트를 추적하고 분석하는 방법을 소개해요. 핵심 개념부터 설치, 다양한 예제까지 알아볼게요.
출처: 문서
본문
AgentOps는 HuggingFace의 가벼운 AI 에이전트 구축 프레임워크인 Smolagents와 원활하게 통합됩니다. 에이전트 워크플로우, 도구 사용, 실행 트레이스를 자동으로 모니터링할 수 있어요.
핵심 개념 (Core Concepts)
Smolagents는 몇 가지 핵심 개념을 중심으로 설계되었습니다.
- Agents: 도구를 사용하고 문제를 추론할 수 있는 AI 어시스턴트
- Tools: 에이전트가 외부 시스템과 상호작용하기 위해 호출할 수 있는 함수
- Models: 에이전트 추론을 구동하는 LLM 백엔드 (LiteLLM을 통해 다양한 프로바이더 지원)
- Code Execution: 에이전트가 샌드박스 환경에서 Python 코드를 작성하고 실행
- Multi-Agent Systems: 함께 작업하는 여러 특화 에이전트를 오케스트레이션
설치 (Installation)
AgentOps와 Smolagents를 추가 의존성과 함께 설치하세요.
poetry add agentops smolagents python-dotenv
uv pip install agentops smolagents python-dotenv
API 키 설정 (Setting Up API Keys)
Smolagents를 AgentOps와 함께 사용하기 전에 API 키를 설정해야 해요.
- AGENTOPS_API_KEY: AgentOps Dashboard에서
- LLM API Keys: 선택한 모델 프로바이더에 따라 (예: OPENAI_API_KEY, ANTHROPIC_API_KEY)
이것들을 환경 변수나 .env 파일로 설정하세요.
AGENTOPS_API_KEY="your_agentops_api_key_here"
OPENAI_API_KEY="your_openai_api_key_here"
그리고 Python 코드에서 로드합니다.
from dotenv import load_dotenv
import os
load_dotenv()
AGENTOPS_API_KEY = os.getenv("AGENTOPS_API_KEY")
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
사용법 (Usage)
Smolagents를 만들기 전에 AgentOps를 초기화하면 모든 에이전트 상호작용이 자동으로 추적됩니다.
import agentops
from smolagents import LiteLLMModel, ToolCallingAgent, DuckDuckGoSearchTool
# Initialize AgentOps
agentops.init()
# Create a model (supports various providers via LiteLLM)
model = LiteLLMModel("openai/gpt-4o-mini")
# Create an agent with tools
agent = ToolCallingAgent(
tools=[DuckDuckGoSearchTool()],
model=model,
)
# Run the agent
result = agent.run("What are the latest developments in AI safety research?")
print(result)
예제 (Examples)
Initialize AgentOps
agentops.init()
Create a model
model = LiteLLMModel("openai/gpt-4o-mini")
Create a code agent that can perform calculations
agent = CodeAgent( tools=[], # No external tools needed for math model=model, additional_authorized_imports=["math", "numpy"], )
Ask the agent to solve a math problem
result = agent.run( "Calculate the compound interest on $10,000 invested at 5% annual rate " "for 10 years, compounded monthly. Show your work." )
print(result)
```python Research Agent with Tools theme={null}
import agentops
from smolagents import (
LiteLLMModel,
ToolCallingAgent,
DuckDuckGoSearchTool,
tool
)
# Initialize AgentOps
agentops.init()
# Create a custom tool
@tool
def word_counter(text: str) -> str:
"""
Counts the number of words in a given text.
Args:
text: The text to count words in.
Returns:
A string with the word count.
"""
word_count = len(text.split())
return f"The text contains {word_count} words."
# Create model and agent
model = LiteLLMModel("openai/gpt-4o-mini")
agent = ToolCallingAgent(
tools=[DuckDuckGoSearchTool(), word_counter],
model=model,
)
# Run a research task
result = agent.run(
"Search for information about the James Webb Space Telescope's latest discoveries. "
"Then count how many words are in your summary."
)
print(result)
import agentops
from smolagents import LiteLLMModel, CodeAgent, tool
import json
# Initialize AgentOps
agentops.init()
# Create tools for data processing
@tool
def save_json(data: dict, filename: str) -> str:
"""
Saves data to a JSON file.
Args:
data: Dictionary to save
filename: Name of the file to save to
Returns:
Success message
"""
with open(filename, 'w') as f:
json.dump(data, f, indent=2)
return f"Data saved to {filename}"
@tool
def load_json(filename: str) -> dict:
"""
Loads data from a JSON file.
Args:
filename: Name of the file to load from
Returns:
The loaded data as a dictionary
"""
with open(filename, 'r') as f:
return json.load(f)
# Create agent
model = LiteLLMModel("openai/gpt-4o-mini")
agent = CodeAgent(
tools=[save_json, load_json],
model=model,
additional_authorized_imports=["pandas", "datetime"],
)
# Run a multi-step data processing task
result = agent.run("""
1. Create a dataset of 5 fictional employees with names, departments, and salaries
2. Save this data to 'employees.json'
3. Load the data back and calculate the average salary
4. Find the highest paid employee
5. Return a summary of your findings
""")
print(result)
더 많은 예제 (More Examples)
AgentOps Dashboard를 방문하면 Smolagents 실행, 도구 사용, 에이전트 추론 단계의 상세 트레이스를 볼 수 있어요.