첫 번째 AI 에이전트 만들기

네오 블록체인·2026년 2월 20일

SpoonOS

목록 보기
22/28

간단한 설정부터 시작해서, 단 몇 분 만에 완전히 동작하는 AI 에이전트를 만들어 보겠습니다.

💡 AI 기반 개발이 처음이신가요?

Vibe Coding 가이드를 참고하시면 Cursor나 Windsurf 같은 AI 코딩 도구를 활용하여 SpoonOS 에이전트를 더 효율적으로 만드는 방법을 배울 수 있습니다.

사전 준비 사항

이 예제를 따라하려면 다음이 필요합니다:

  • SpoonOS SDK 패키지 설치
  • 사용할 LLM 제공업체(OpenAI, Anthropic, Google 등)의 API 키 발급
  • 환경 변수 설정:
# LLM 제공업체 (하나 선택)
export OPENAI_API_KEY="your-openai-key"
# 또는 export ANTHROPIC_API_KEY="your-anthropic-key"

# Desearch 도구용 (검색 예제에 필요)
export DESEARCH_API_KEY="your-desearch-key"

이 예제에서는 기본적으로 OpenAI를 사용하지만, llm_provider 파라미터를 변경하고 해당 API 키를 설정하면 다른 제공업체도 사용할 수 있습니다.

설치 방법

# uv 사용 (권장)
uv venv .venv
source .venv/bin/activate            # macOS/Linux
# .\.venv\Scripts\Activate.ps1       # Windows (PowerShell)

uv pip install spoon-ai-sdk          # 코어 SDK
uv pip install spoon-toolkits        # 도구 모음 (웹 검색, 블록체인 등)

# 또는 pip 사용
pip install spoon-ai-sdk spoon-toolkits

기본 에이전트 만들기

먼저 웹 페이지를 스크래핑하고 질문에 답할 수 있는 간단한 에이전트를 만들어 봅시다. 이 에이전트는 WebScraperTool을 사용하여 모든 URL에서 실제 콘텐츠를 가져옵니다.

참고: 이 기본 예제는 OPENAI_API_KEY만 있으면 됩니다. 추가 API 키는 필요하지 않습니다.

import asyncio
from spoon_ai.agents import SpoonReactAI
from spoon_ai.chat import ChatBot
from spoon_toolkits import WebScraperTool

# 웹 스크래핑 기능을 갖춘 에이전트 생성
agent = SpoonReactAI(
    llm=ChatBot(llm_provider="openai", model_name="gpt-5.1-chat-latest"),
    tools=[WebScraperTool()],
    system_prompt="You are a helpful assistant that can read web pages."
)

# 에이전트 실행
async def main():
    response = await agent.run(
        "Scrape https://news.ycombinator.com and tell me the top 3 stories"
    )
    print(response)

if __name__ == "__main__":
    asyncio.run(main())

실전 에이전트 만들기

다음으로, 프로덕션 환경에서 중요한 핵심 개념들을 보여주는 실용적인 리서치 어시스턴트 에이전트를 만들어 보겠습니다:

  1. 상세한 시스템 프롬프트 - 에이전트의 행동을 더 정확하게 제어
  2. 다중 도구 활용 - 웹에서 실제 데이터를 가져오는 여러 도구 사용
  3. 모델 설정 - 대화 메모리가 내장된 모델 구성
  4. 에이전트 생성 및 실행 - 완전한 기능을 갖춘 어시스턴트로 동작

각 단계를 하나씩 살펴보겠습니다:

1단계: 시스템 프롬프트 정의하기

시스템 프롬프트는 에이전트의 역할과 행동 방식을 정의합니다. 구체적이고 실행 가능하게 작성하는 것이 중요합니다:

SYSTEM_PROMPT = """You are an expert research assistant who helps users find and analyze information.

You have access to these tools:
- desearch_web_search: Search the web for general information
- desearch_ai_search: Search across web, Reddit, Wikipedia, YouTube, and arXiv
- web_scraper: Fetch and read full content from any URL

When a user asks for information:
1. Use the appropriate search tool to find relevant sources
2. If needed, use web_scraper to read full articles
3. Synthesize the information and provide clear, cited answers

Always cite your sources with URLs when providing information."""

2단계: 도구(Tools) 생성하기

도구(Tools)는 모델이 여러분이 정의한 함수를 호출하여 외부 시스템과 상호작용할 수 있게 해줍니다.

SpoonOS는 실제 데이터를 가져오는 사전 구축된 도구들을 제공합니다:

from spoon_toolkits import DesearchWebSearchTool, DesearchAISearchTool, WebScraperTool

# 웹 검색 - 웹을 검색하고 실제 결과를 반환
web_search = DesearchWebSearchTool()

# AI 검색 - 여러 플랫폼에서 검색 (웹, Reddit, Wikipedia, YouTube, arXiv)
ai_search = DesearchAISearchTool()

# 웹 스크래퍼 - 모든 URL에서 콘텐츠를 가져오고 정리
scraper = WebScraperTool()

💡 팁

도구는 문서화가 잘 되어 있어야 합니다. 도구의 이름, 설명, 인자 이름이 모델의 프롬프트에 포함되기 때문입니다. 명확하고 설명적인 이름과 포괄적인 파라미터 설명을 사용하세요.

3단계: 모델 설정하기

대화 메모리 관리가 내장된 언어 모델을 설정합니다:

from spoon_ai.chat import ChatBot

llm = ChatBot(
    llm_provider="openai",
    model_name="gpt-5.1-chat-latest",
    enable_short_term_memory=True,
    short_term_memory_config={
        "max_tokens": 8000,
        "strategy": "summarize",  # 또는 "trim"
        "messages_to_keep": 6,
    }
)

enable_short_term_memory=True 옵션은 대화 히스토리를 자동으로 관리해줍니다:

  • summarize: 토큰 한도에 도달하면 오래된 메시지를 요약합니다
  • trim: 토큰 한도 내에 머물기 위해 오래된 메시지를 삭제합니다

SpoonOS는 다양한 LLM 제공업체를 기본 지원합니다:

제공업체모델 예시문서
openaigpt-5.1-chat-latest, gpt-5-mini, gpt-4.1, o3, o4-miniOpenAI Models
anthropicclaude-opus-4-5, claude-sonnet-4-5, claude-haiku-4-5Anthropic Models
geminigemini-3-pro-preview, gemini-2.5-flashGemini Models
deepseekdeepseek-chat, deepseek-reasonerDeepSeek Models
openrouter100개 이상의 모델OpenRouter Models

4단계: 에이전트 생성 및 실행하기

이제 모든 구성 요소를 조합하여 에이전트를 만들고 실행해 봅시다!

import asyncio
from spoon_ai.agents import SpoonReactAI
from spoon_ai.chat import ChatBot
from spoon_toolkits import DesearchWebSearchTool, DesearchAISearchTool, WebScraperTool

# 시스템 프롬프트
SYSTEM_PROMPT = """You are an expert research assistant who helps users find and analyze information.

You have access to these tools:
- desearch_web_search: Search the web for general information
- desearch_ai_search: Search across web, Reddit, Wikipedia, YouTube, and arXiv
- web_scraper: Fetch and read full content from any URL

Always cite your sources with URLs when providing information."""

# 메모리가 포함된 모델 설정
llm = ChatBot(
    llm_provider="openai",
    model_name="gpt-5.1-chat-latest",
    enable_short_term_memory=True,
    short_term_memory_config={
        "max_tokens": 8000,
        "strategy": "summarize",
        "messages_to_keep": 6,
    }
)

# 실제 데이터 도구를 갖춘 에이전트 생성
agent = SpoonReactAI(
    llm=llm,
    system_prompt=SYSTEM_PROMPT,
    tools=[
        DesearchWebSearchTool(),
        DesearchAISearchTool(),
        WebScraperTool(),
    ],
    max_steps=10,
)

# 대화형 에이전트 실행
async def main():
    # 첫 번째 질의 - 웹에서 실제 데이터를 검색
    response = await agent.run(
        "What are the latest developments in AI agents?"
    )
    print("Agent:", response)

    # 후속 질의 - 에이전트가 이전 맥락을 기억
    response = await agent.run(
        "Can you find academic papers about that topic on arXiv?"
    )
    print("Agent:", response)

if __name__ == "__main__":
    asyncio.run(main())

선택 사항: 스트리밍 응답

토큰 단위로 출력하여 더 인터랙티브한 경험을 원한다면 다음과 같이 할 수 있습니다:

import asyncio

async def stream_demo():
    llm = ChatBot(
        llm_provider="openai",
        model_name="gpt-5.1-chat-latest"
    )

    messages = [
        {"role": "user", "content": "Explain machine learning in 3 sentences"}
    ]

    async for chunk in llm.astream(messages=messages):
        print(chunk.delta or "", end="", flush=True)
    print()  # 줄바꿈

if __name__ == "__main__":
    asyncio.run(stream_demo())

전체 예제 코드

프로덕션 레벨 전체 예제 보기 (클릭하여 펼치기)
"""
프로덕션 레벨 SpoonOS 리서치 어시스턴트 에이전트.

이 예제에서 다루는 내용:
- Desearch 도구를 통한 실시간 웹 검색
- 웹 페이지 스크래핑으로 전체 콘텐츠 가져오기
- 자동 요약 기능이 포함된 대화 메모리
"""
import asyncio
import logging

from spoon_ai.agents import SpoonReactAI
from spoon_ai.chat import ChatBot
from spoon_toolkits import DesearchWebSearchTool, DesearchAISearchTool, WebScraperTool

# 로깅 설정
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# 시스템 프롬프트 정의
SYSTEM_PROMPT = """You are an expert research assistant who helps users find and analyze information.

You have access to these tools:
- desearch_web_search: Search the web for general information
- desearch_ai_search: Search across web, Reddit, Wikipedia, YouTube, and arXiv platforms
- web_scraper: Fetch and read full content from any URL

When a user asks for information:
1. Use the appropriate search tool to find relevant sources
2. If needed, use web_scraper to read full articles for deeper analysis
3. Synthesize the information and provide clear, cited answers

Always cite your sources with URLs when providing information.
Be thorough but concise in your analysis."""


def create_agent() -> SpoonReactAI:
    """리서치 어시스턴트 에이전트를 생성하고 설정합니다."""

    # 메모리 관리가 포함된 모델 설정
    llm = ChatBot(
        llm_provider="openai",
        model_name="gpt-5.1-chat-latest",
        enable_short_term_memory=True,
        short_term_memory_config={
            "max_tokens": 8000,
            "strategy": "summarize",
            "messages_to_keep": 6,
        }
    )

    # 실제 데이터 도구 구성
    tools = [
        DesearchWebSearchTool(),
        DesearchAISearchTool(),
        WebScraperTool(),
    ]

    # 에이전트 생성
    agent = SpoonReactAI(
        llm=llm,
        system_prompt=SYSTEM_PROMPT,
        tools=tools,
        max_steps=10,
    )

    logger.info("Agent created with %d tools", len(tools))
    return agent


async def interactive_session():
    """에이전트와 대화형 채팅 세션을 실행합니다."""
    agent = create_agent()

    print("\n리서치 어시스턴트 에이전트 준비 완료!")
    print("'quit' 또는 'exit'를 입력하면 세션이 종료됩니다.\n")

    while True:
        try:
            user_input = input("You: ").strip()

            if not user_input:
                continue

            if user_input.lower() in ['quit', 'exit', 'bye']:
                print("안녕히 가세요!")
                break

            # 에이전트 실행 및 응답 받기
            response = await agent.run(user_input)
            print(f"\nAgent: {response}\n")

        except KeyboardInterrupt:
            print("\n세션이 종료되었습니다.")
            break
        except Exception as e:
            logger.error("Error: %s", e)
            print(f"오류 발생: {e}")


async def demo_queries():
    """샘플 질의로 에이전트 기능을 시연합니다."""
    agent = create_agent()

    queries = [
        "Search for the latest news about large language models",
        "Find academic papers about transformer architectures on arXiv",
        "Scrape https://news.ycombinator.com and summarize the top stories",
    ]

    print("\n데모 질의 실행 중\n" + "=" * 50)

    for query in queries:
        print(f"\nUser: {query}")
        response = await agent.run(query)
        print(f"Agent: {response}")

    print("\n" + "=" * 50 + "\n데모 완료!")


if __name__ == "__main__":
    import sys

    if "--demo" in sys.argv:
        asyncio.run(demo_queries())
    else:
        asyncio.run(interactive_session())

지금까지 만든 것 정리

축하합니다! 이제 다음과 같은 기능을 갖춘 AI 에이전트가 완성되었습니다:

  • 실시간 웹 검색 - Desearch 도구를 활용한 웹 검색
  • 웹 페이지 전체 읽기 - WebScraper 도구로 페이지 콘텐츠 가져오기
  • 학술 논문 검색 - arXiv 등 다양한 플랫폼에서 논문 탐색
  • 대화 기억 - 단기 메모리를 통한 맥락 유지
  • 다중 도구 활용 - 사용자 질의에 따라 지능적으로 도구 선택
  • 스트리밍 응답 - 실시간 토큰 단위 출력
profile
스마트 이코노미를 위한 퍼블릭 블록체인, 네오에 대한 모든것

0개의 댓글