개발 이야기/[스터디] LLM
오늘의 LLM 공부: smolagent
경이로운아일라
2025. 1. 9. 15:50
smolagent
AI 에이전트를 더 쉽게 만들 수 있도록 설계된 프레임워크입니다.
* AI 에이전트: 특정한 목적을 달성하기 위해 환경과 상호작용하며 스스로 행동을 결정하는 프로그램을 의미합니다.
예로는, 사용자의 질문을 이해하고 적절한 답변을 제공하는 챗봇, 시장 데이터를 분석하고 매매 결정을 내리는 금융 트레이딩 에이전트 등이 있습니다.
smolagent 예시
시장의 가격 데이터를 분석하고, 매수/매도 신호를 생성한 뒤, 동적으로 행동을 결정하는 에이전트를 구성해 봅시다.
목표
- 실시간 시장 데이터를 가져옵니다.
- 데이터를 분석해 매수/매도 신호를 생성합니다.
- 시장 상황과 포트폴리오 상태를 바탕으로 행동을 결정합니다:
- 매수 (Buy)
- 매도 (Sell)
- 대기 (Hold)
- 행동 결과를 저장하고 보고합니다.
구성
1. AI 에이전트가 사용할 도구 정의
import requests
from smolagents import ToolCallingAgent
# 1. 시장 데이터 가져오기 도구
def fetch_market_data_tool(symbol):
"""
특정 암호화폐 또는 주식의 실시간 데이터를 가져옵니다.
"""
api_url = f"https://api.marketdata.com/v1/quote?symbol={symbol}&apikey=YOUR_API_KEY"
response = requests.get(api_url)
if response.status_code == 200:
return response.json()
return {"error": "Failed to fetch market data"}
# 2. 매수/매도 신호 분석 도구
def analyze_signal_tool(data):
"""
시장 데이터를 기반으로 매수/매도 신호를 생성합니다.
"""
prompt = f"""
The following market data is provided:
{data}
Based on this data, determine whether to "Buy", "Sell", or "Hold".
Provide your response as a JSON object:
{{
"action": "<Buy|Sell|Hold>",
"confidence": "<confidence score>",
"reason": "<explanation>"
}}
"""
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers={"Authorization": "Bearer YOUR_API_KEY"},
json={"model": "gpt-4", "messages": [{"role": "user", "content": prompt}]},
)
return response.json()["choices"][0]["message"]["content"]
# 3. 행동 실행 도구
def execute_trade_tool(action, symbol, amount):
"""
매수/매도 명령을 실행합니다.
"""
trade_api_url = f"https://api.tradingplatform.com/v1/order"
payload = {"symbol": symbol, "action": action, "amount": amount}
response = requests.post(trade_api_url, json=payload)
if response.status_code == 200:
return {"status": "Trade executed", "details": response.json()}
return {"error": "Failed to execute trade"}
# 4. 기록 저장 도구
def save_trade_record_tool(record):
"""
거래 기록을 데이터베이스 또는 로컬 저장소에 저장합니다.
"""
# 데이터 저장 API 예시
db_api_url = f"https://api.database.com/v1/save"
response = requests.post(db_api_url, json=record)
if response.status_code == 200:
return {"status": "Record saved"}
return {"error": "Failed to save record"}
2. smolagent 에이전트 정의
agent = ToolCallingAgent(
tools={
"fetch_market_data": fetch_market_data_tool,
"analyze_signal": analyze_signal_tool,
"execute_trade": execute_trade_tool,
"save_trade_record": save_trade_record_tool,
},
prompt_template="""
The agent manages trading decisions for the symbol {symbol}.
1. Fetch real-time market data for {symbol}.
2. Analyze the market data and determine whether to "Buy", "Sell", or "Hold".
3. If "Buy" or "Sell", execute the trade for the given amount ({amount}).
4. Save the trade action and details to the database.
5. Return a summary of the trade or decision.
"""
)
3. 에이전트 실행
result = agent.act({
"symbol": "BTC/USD",
"amount": 0.1 # 0.1 BTC 거래
})
print(result)
smolagent 의 장점
- 자연어 기반 로직 설계:
- 복잡한 로직을 자연어 프롬프트로 표현할 수 있습니다.
- 즉, 도구(tool)를 정의한 후 무엇을 할 것인지"에만 집중하면 됩니다.
- 예: "데이터를 수집하고 분석하여 알림을 보내세요."라는 요구사항을 자연어로 정의하면 에이전트가 이를 실행합니다.
- 확장성:
- 도구(tool)를 추가하거나 로직을 변경할 때 프롬프트만 수정하면 됩니다.
- 기존 코드를 대대적으로 수정하지 않고도 새로운 요구사항에 대응 가능.
- 비개발자와의 협업:
- 자연어로 작성된 프롬프트는 **비개발자(예: 기획자, 데이터 분석가)**가 로직을 이해하고, 일부 수정할 수 있도록 도와줍니다.
- 코딩 지식이 부족한 사람도 로직 설계에 참여할 수 있는 가능성을 제공합니다.