Agentic AI / Generative AI

OpenRouter에서 NVIDIA Nemotron으로 보고서 생성 AI 에이전트 구축하기

Reading Time: 9 minutes

사전에 정의된 경로만 따르는 전통적인 시스템과 달리, AI 에이전트거대 언어 모델(LLM)을 활용해 스스로 의사결정을 내리고, 변하는 요구사항에 적응하며, 복잡한 추론을 수행하는 자율 시스템입니다.

보고서 생성 에이전트 구축을 위한 자기 주도형 워크숍 가이드를 통해 다음과 같은 내용을 배우고 얻어갈 수 있습니다.

  • 오픈 데이터와 가중치를 제공하는 오픈 모델 제품군인 NVIDIA Nemotron을 포함하여, 모든 AI 에이전트를 개발할 때 고려해야 할 4가지 핵심 요소에 대한 이해
  • 직접 정보를 조사하고 보고서를 작성할 수 있는 실제 작동하는 문서 생성 에이전트 개발
  • LangGraph와 OpenRouter를 활용해 에이전트를 구축하는 방법
  • 어디서나 즉시 실행 가능한 휴대용 개발 환경 제공
  • NVIDIA Launchable로 바로 공유할 수 있는 나만의 맞춤형 에이전트 완성

영상 안내

워크숍 배포

NVIDIA Brev Launchable로 워크숍을 시작하세요

Button of the “Deploy Now” button for NVIDIA DevX  Workshop
그림 1. ‘Deploy Now’ 버튼을 클릭하여 클라우드에 NVIDIA DevX 워크숍을 배포합니다.

시크릿 설정을 위한 구성

이 워크숍을 진행하려면 몇 가지 프로젝트 시크릿(Secret)을 수집하고 설정해야 합니다.

  • OpenRouter API 키: OpenRouter를 통해 NVIDIA Nemotron-Nano-9B-v2 모델에 접근할 수 있도록 합니다.
  • Tavily API 키: 실시간 웹 검색을 위한 Tavily 웹 검색 API를 사용할 수 있도록 합니다.

JupyterLab 환경이 실행 중인 상태에서, JupyterLab 런처의 ‘NVIDIA DevX Learning Path’ 아래에 있는 Secrets Manager 타일을 사용해 워크숍 개발 환경의 시크릿을 구성할 수 있습니다. 시크릿이 성공적으로 추가되었는지는 로그 탭에서 확인하실 수 있습니다.

다음으로 JupyterLab 런처의 NVIDIA DevX Learning Path 섹션에서 1. Introduction to Agents 타일을 선택하여 실습 안내를 열고 시작하십시오.

에이전트 아키텍처 소개

워크숍 환경 설정이 끝나면, 첫 번째 섹션에서는 에이전트가 무엇인지 소개합니다. 본격적인 구현에 들어가기에 앞서, 에이전트가 일반적인 단순 AI 애플리케이션과 어떻게 다른지 그 차이점을 이해하는 것이 중요합니다.

기존의 LLM 기반 애플리케이션과 달리, 에이전트는 상황에 맞는 도구를 동적으로 선택하고, 복잡한 추론 과정을 유기적으로 결합하며, 주변 환경에 맞춰 분석 방식을 유연하게 변경할 수 있습니다. 이번 섹션에서 개발자들은 모든 에이전트의 뼈대가 되는 4가지 핵심 요소를 학습하게 됩니다.

  • 모델(Model): 어떤 도구를 사용할지, 어떻게 응답할지 판단하는 두뇌 역할을 맡은 LLM입니다.
  • 도구(Tools): LLM이 수학적 계산, 데이터베이스 쿼리, API 호출 등의 실제 작업을 수행할 수 있도록 돕는 함수입니다.
  • 메모리와 상태(Memory and State): 대화가 진행되는 동안, 혹은 대화와 대화 사이에 LLM이 참조하고 활용할 수 있는 정보입니다.
  • 라우팅(Routing): 현재 상태와 LLM의 결정을 바탕으로, 에이전트가 다음에 어떤 행동을 이어가야 할지 결정하는 제어 로직입니다.

code/intro_to_agents.ipynb에서 이러한 구성요소를 결합하여 계산기 기능을 갖춘 첫 번째 기본 에이전트를 구축하는 방법을 학습합니다. 이 실습을 마치면 다음을 수행하는 에이전트를 보유하게 됩니다.

[{'content': 'What is 3 plus 12?', 'role': 'user'},
 {'content': None,
  'role': 'assistant',
  'tool_calls': [{'function': {'arguments': '{"a": 3, "b": 12}', 'name': 'add'},
                  'id': 'chatcmpl-tool-b852128b6bdf4ee29121b88490174799',
                  'type': 'function'}]},
 {'content': '15',
  'name': 'add',
  'role': 'tool',
  'tool_call_id': 'chatcmpl-tool-b852128b6bdf4ee29121b88490174799'},
 {'content': 'The answer is 15.', 'role': 'assistant'}]

보고서 생성 구성요소

이 워크숍의 나머지 부분은 LangGraphOpenRouter 엔드포인트로 호스팅되는 NVIDIA NIM을 사용하는 다계층 에이전트 시스템 구축을 중심으로 진행됩니다. 이 아키텍처는 문서 생성 프로세스의 특정 측면을 각각 담당하는 4개의 상호 연결된 에이전트 구성요소로 구성됩니다.

  • 초기 조사: 주제에 관한 포괄적인 정보 수집
  • 개요 기획: 조사를 바탕으로 구조화된 문서 개요 작성
  • 섹션 작성: 필요시 추가 조사를 통해 각 섹션의 상세 콘텐츠 생성
  • 최종 편집: 모든 섹션을 전문적인 보고서로 취합

코드 학습 및 구현

개념을 이해했으니 이제 본격적인 구현에 들어갈 차례입니다. 앞서 짚어본 핵심 요소들을 하나씩 채워가며 완벽히 작동하는 에이전트를 차근차근 구축해 보겠습니다.

  • 모델 선택
  • 도구 선택
  • 리서처(researcher) 구축
  • 저자(author) 구축
  • 최종 에이전트 구축
  • 에이전트 관리 및 라우팅

기초: 모델

이번 워크숍에서는 에이전트를 구동하는 핵심 모델로 NVIDIA NIM 엔드포인트를 활용합니다. NVIDIA NIM은 다음과 같은 고성능 추론 기능을 제공합니다.

  • 도구 바인딩(tool binding): 함수 호출에 대한 기본 지원
  • 구조화된 출력: Pydantic 모델에 대한 내장 지원
  • 비동기 작업: 동시 처리를 위한 완전한 async/await 지원
  • 엔터프라이즈급 안정성: 프로덕션 수준의 추론 인프라

다음 예시는 OpenRouter 엔드포인트로 호스팅되는 NVIDIA NIM을 사용하는 ChatNVIDIA 커넥터를 보여줍니다.

from langchain_nvidia_ai_endpoints import ChatNVIDIA

llm = ChatNVIDIA(
    base_url="https://openrouter.ai/api/v1",
    model="nvidia/nemotron-nano-9b-v2:free",
    api_key=os.getenv("OPENROUTER_API_KEY")
)
llm_with_tools = llm.bind_tools([tools.search_tavily])

명확한 품질 지침은 모든 LLM 기반 애플리케이션에서 중요하지만, 에이전트 시스템에서는 특히 더 결정적인 역할을 합니다. 지침이 명확해야 모호성이 제거되고 에이전트의 의사결정 프로세스가 확실해지기 때문입니다. code/docgen_agent/prompts.py에 포함된 예시 코드는 다음과 같습니다.

research_prompt: Final[str] = """
Your goal is to generate targeted web search queries that will gather comprehensive information for writing a technical report section.

Topic for this section:
{topic}

When generating {number_of_queries} search queries, ensure they:
1. Cover different aspects of the topic (e.g., core features, real-world applications, technical architecture)
2. Include specific technical terms related to the topic
3. Target recent information by including year markers where relevant (e.g., "2024")
4. Look for comparisons or differentiators from similar technologies/approaches
5. Search for both official documentation and practical implementation examples

Your queries should be:
- Specific enough to avoid generic results
- Technical enough to capture detailed implementation information
- Diverse enough to cover all aspects of the section plan
- Focused on authoritative sources (documentation, technical blogs, academic papers)"""

이 프롬프트는 신뢰할 수 있는 LLM 프롬프팅의 몇 가지 핵심 원칙을 보여줍니다.

  • 역할 명시: 에이전트의 전문성과 책임에 대한 명확한 정의
  • 작업 분해: 복잡한 요구사항을 구체적이고 실행 가능한 단계 또는 기준으로 분리
  • 구체성: 시간적 구체성 및 권위 있는 출처의 예시 참조
  • 구조화된 입출력: 원하는 응답 구조와 예상 입력 구조에 대한 구체적인 지침

기초: 도구

에이전트의 실질적인 기능은 어떤 도구를 갖추었느냐에 따라 정의됩니다. 이번 워크숍에서는 AI 에이전트를 위해 특별히 설계된 검색 API인 Tavily를 정보 수집을 위한 핵심 도구로 활용합니다.

# imports and constants omitted
@tool(parse_docstring=True)
async def search_tavily(
    queries: list[str],
    topic: Literal["general", "news", "finance"] = "news",
) -> str:
    """Search the web using the Tavily API.

    Args:
        queries: List of queries to search.
        topic: The topic of the provided queries.
          general - General search.
          news - News search.
          finance - Finance search.

    Returns:
        A string of the search results.
    """
    search_jobs = []
    for query in queries:
        search_jobs.append(
            asyncio.create_task(
                tavily_client.search(
                    query,
                    max_results=MAX_RESULTS,
                    include_raw_content=INCLUDE_RAW_CONTENT,
                    topic=topic,
                    days=days,  # type: ignore[arg-type]
                )
            )
        )
    search_docs = await asyncio.gather(*search_jobs)
    return _deduplicate_and_format_sources(
        search_docs,
        max_tokens_per_source=MAX_TOKENS_PER_SOURCE,
        include_raw_content=INCLUDE_RAW_CONTENT,
    )

도구 모듈 구현의 주요 아키텍처 결정 사항은 다음과 같습니다.

  • 비동기 작업: 동시 검색을 위한 asyncio.gather() 활용
  • 중복 제거: 다중 검색에서 발생하는 중복을 방지하는 헬퍼 함수
  • 구조화된 문서화: LLM이 도구 사용법을 이해할 수 있도록 돕는 Google 스타일 독스트링(docstring)

모델과 도구를 다루는 코드의 기초를 다졌으니, 이제 이를 결합해 실제 동작하는 에이전트를 조립해 보겠습니다. 아직 다루지 않은 상태 관리와 라우팅 요소는 에이전트 핵심 구성요소를 모두 구축한 후에 다시 살펴보겠습니다.

리서처 구현

에이전트의 리서처 구성요소는 도구 활용 에이전트에게 가장 효과적인 아키텍처 중 하나인 추론-행동(ReAct, Reasoning and Acting) 패턴을 구현합니다. 이 패턴은 에이전트가 다음에 수행할 작업을 생각하고, 그에 따른 행동을 취한 뒤, 도출된 결과를 바탕으로 다음 단계를 다시 결정하는 루프를 형성합니다. 이 과정은 에이전트가 작업을 완료하기 위해 더 이상의 추가 행동이 필요 없다고 판단할 때까지 계속해서 반복됩니다.

이 리서처 구성요소의 코드는 code/docgen_agent/researcher.py에 구현되어 있으며, code/researcher_client.ipynb로 테스트할 수 있습니다.

state = ResearcherState(
    topic="Examples of AI agents in various industries.",
    number_of_queries=3,
)
state = await graph.ainvoke(state)

for message in state["messages"]:
    print("ROLE: ", getattr(message, "role", "tool_call"))
    print(message.content[:500] or message.additional_kwargs)
    print("")

실행 중 리서처가 취하는 각 행동도 확인할 수 있습니다.

INFO:docgen_agent.researcher:Calling model.
INFO:docgen_agent.researcher:Executing tool calls.
INFO:docgen_agent.researcher:Executing tool call: search_tavily
INFO:docgen_agent.tools:Searching the web using the Tavily API
INFO:docgen_agent.tools:Searching for query: Technical architecture of AI agents in healthcare 2024
INFO:docgen_agent.tools:Searching for query: Comparison of machine learning frameworks for AI agents in finance
INFO:docgen_agent.tools:Searching for query: Real-world applications of natural language processing in AI agents for customer service 2024
INFO:httpx:HTTP Request: POST https://api.tavily.com/search "HTTP/1.1 200 OK"
INFO:httpx:HTTP Request: POST https://api.tavily.com/search "HTTP/1.1 200 OK"
INFO:httpx:HTTP Request: POST https://api.tavily.com/search "HTTP/1.1 200 OK"
INFO:docgen_agent.researcher:Calling model.

도구 호출 요청, 도구 출력, 결과를 요약하는 최종 메시지를 포함한 최종 출력도 확인할 수 있습니다.

ROLE:  assistant
{'tool_calls': [{'id': 'chatcmpl-tool-b7185ba8eb3a44259b0bdf930495ece5', 'type': 'function', 'function': {'name': 'search_tavily', 'arguments': '{"queries": ["Technical architecture of AI agents in healthcare 2024", "Comparison of machine learning frameworks for AI agents in finance", "Real-world applications of natural language processing in AI agents for customer service 2024"], "topic": "general"}'}}]}

ROLE:  tool_call
"Sources:\n\nSource AI Agents in Modern Healthcare: From Foundation to Pioneer:\n===\nURL: https://www.preprints.org/manuscript/202503.1352/v1\n===\nMost relevant content from source: T. Guo et al., \"Large language model based multi-agents: A survey of progress and challenges,\" arXiv preprint arXiv:2402.01680, 2024. J. Ruan et al., \"TPTU: Large Language Model-based AI Agents for Task Planning and Tool Usage. | **Partner Agent** | * True healthcare team partners * Generates clinical hypotheses

ROLE:  assistant
Based on the search results, here are some potential search queries that could be used to gather comprehensive information for writing a technical report section on examples of AI agents in various industries:

1. "Technical architecture of AI agents in healthcare 2024"
2. "Comparison of machine learning frameworks for AI agents in finance"
3. "Real-world applications of natural language processing in AI agents for customer service 2024"

저자 구현

단순한 ReAct 구조의 에이전트도 강력한 성능을 발휘하지만, 복잡한 워크플로우를 처리할 때는 추가적인 단계와 결합하여 사용하는 경우가 많습니다. 본 섹션의 저자 에이전트는 사용자가 요청할 때만 특정 섹션과 관련된 추가 조사를 수행합니다. 그리고 필요한 조사가 모두 완료되면, 확보한 조사 내용을 바탕으로 문서를 작성하도록 설계되었습니다.

수정된 아키텍처 다이어그램을 보면, 추가 조사가 필요한지 여부를 먼저 판단하는 게이팅(Gating) 함수가 ReAct 스타일의 에이전트 전 단계에 배치되어 있으며, 전체 프로세스의 마지막에 최종 작성 단계가 포함되어 있는 것을 확인할 수 있습니다.

이 리서처 구성요소의 코드는 code/docgen_agent/author.py에 구현되어 있으며, code/author_client.ipynb로 테스트할 수 있습니다.

state = SectionWriterState(
    index=1,
    topic="Examples of AI agents in various industries.",
    section=Section(
        name="Real-World Applications",
        description="Examples of AI agents in various industries",
        research=True,
        content=""
    ),
)

state = await graph.ainvoke(state)
Markdown(state["section"].content)

실행 중 저자가 취하는 각 행동도 확인할 수 있습니다.

INFO:docgen_agent.author:Researching section: Real-World Applications
INFO:docgen_agent.author:Executing tool calls for section: Real-World Applications
INFO:docgen_agent.author:Executing tool call: search_tavily
INFO:docgen_agent.tools:Searching the web using the Tavily API
INFO:docgen_agent.tools:Searching for query: AI agents in healthcare industry 2024
INFO:docgen_agent.tools:Searching for query: Implementation of AI agents in finance sector 2023
...
INFO:httpx:HTTP Request: POST https://api.tavily.com/search "HTTP/1.1 200 OK"
INFO:docgen_agent.author:Researching section: Real-World Applications
INFO:docgen_agent.author:Writing section: Real-World Applications

마크다운 형식으로 작성된 섹션으로 구성된 최종 출력도 확인할 수 있습니다.

## Real-World Applications

AI agents have numerous applications across various industries...

### Healthcare

AI agents in healthcare are revolutionizing patient care and medical innovation. They are being used to automate administrative tasks, enhance diagnostics, and improve workflow efficiency. For instance...

### Finance

AI agents in finance are driving innovation, success, and compliance. They are being used to automate tasks such as data entry, transaction processing, and compliance checks. AI agents are also being used to detect fraud, improve customer service, and provide personalized investment advice. For example...

최종 에이전트 구현

이 두 가지 구성요소를 활용하면 문서 생성 에이전트의 전체 워크플로우를 완성할 수 있습니다. 이 아키텍처는 지금까지 다룬 구조 중 가장 직관적인 형태로, 먼저 주제를 조사하는 리서처 단계를 거치고, 각 섹션을 작성하는 저자 단계를 지나, 최종적으로 완성된 보고서 전체를 감수 및 편집하는 선형 워크플로우를 따릅니다.

이 리서처 구성요소의 코드는 code/docgen_agent/agent.py에 구현되어 있으며, code/agent_client.ipynb로 테스트할 수 있습니다.

state = AgentState(
    topic="The latest developments with AI Agents in 2025.",
    report_structure="This article should be..."
)

state = await graph.ainvoke(state)
Markdown(state["report"])

실행 중 저자가 취하는 각 행동도 확인할 수 있습니다.

INFO:docgen_agent.agent:Performing initial topic research.
INFO:docgen_agent.researcher:Calling model.
INFO:docgen_agent.researcher:Executing tool calls.
INFO:docgen_agent.researcher:Executing tool call: search_tavily
INFO:docgen_agent.tools:Searching the web using the Tavily API
INFO:docgen_agent.tools:Searching for query: AI Agents 2025 core features
INFO:docgen_agent.tools:Searching for query: Real-world applications of AI Agents in 2025
...
INFO:httpx:HTTP Request: POST https://api.tavily.com/search "HTTP/1.1 200 OK"
INFO:docgen_agent.researcher:Calling model.
INFO:docgen_agent.agent:Calling report planner.
INFO:docgen_agent.agent:Orchestrating the section authoring process.
INFO:docgen_agent.agent:Creating author agent for section: Introduction
INFO:docgen_agent.agent:Creating author agent for section: Autonomous Decision-Making
INFO:docgen_agent.agent:Creating author agent for section: Integration with Physical World
INFO:docgen_agent.agent:Creating author agent for section: Agentic AI Trends
INFO:docgen_agent.agent:Creating author agent for section: AI Agents in Customer Support
INFO:docgen_agent.agent:Creating author agent for section: AI Agents in Healthcare
INFO:docgen_agent.agent:Creating author agent for section: Conclusion
INFO:docgen_agent.agent:Throttling LLM calls.
INFO:docgen_agent.author:Writing section: Introduction
INFO:docgen_agent.author:Researching section: Autonomous Decision-Making
...

완성된 보고서는 마크다운 형식으로 생성됩니다. 이 에이전트가 생성한 샘플 조사 보고서는 샘플 마크다운 출력에서 확인할 수 있습니다.

기초: 상태 관리와 라우팅

에이전트 구성요소가 모두 구축되었으니, 이제 한 걸음 물러서서 이 세 가지 요소를 하나의 유기적인 에이전틱 AI 시스템으로 연결해 보겠습니다. 여기서는 고급 상태 관리와 흐름 제어를 위한 에이전트 프레임워크로 LangGraph를 활용합니다. LangGraph는 다음과 같은 주요 이점을 제공합니다.

  • 조건부 라우팅: 조건부 엣지를 통해 실행 시점의 조건에 따라 흐름을 동적으로 제어할 수 있으며, 이를 바탕으로 에이전트가 다음 행동에 대한 지능적인 결정을 내리도록 돕습니다.
  • 그래프 컴파일 및 실행: 컴파일된 그래프는 비동기 방식으로 호출할 수 있어, 멀티 에이전트 시스템에 필수적인 동시 실행과 복잡한 오케스트레이션 패턴을 안정적으로 지원합니다.

code/docgen_agent/agent.py의 다음 예시에서 이전에 구축한 구성요소가 어떤 노드에 해당하는지, 그리고 하나의 노드에서 다음 노드로 중간 출력을 연결하거나 라우팅하는 엣지를 확인할 수 있습니다.

main_workflow = StateGraph(AgentState)
main_workflow.add_node("topic_research", topic_research)
main_workflow.add_node("report_planner", report_planner)
main_workflow.add_node("section_author_orchestrator", section_author_orchestrator)
main_workflow.add_node("report_author", report_author)

main_workflow.add_edge(START, "topic_research")
main_workflow.add_edge("topic_research", "report_planner")
main_workflow.add_edge("report_planner", "section_author_orchestrator")
main_workflow.add_edge("section_author_orchestrator", "report_author")
main_workflow.add_edge("report_author", END)

축하합니다! 이 개발자 워크숍의 각 단계를 차근차근 따라오며 나만의 LangGraph 에이전트를 성공적으로 구축하셨습니다. 이제 code/agent_client.ipynb 노트북을 열고 새롭게 완성한 에이전트를 직접 테스트해 보세요.

요약

AI 에이전트를 구축하려면 이론적 기초와 실제 구현 과정에서의 과제를 모두 이해해야 합니다. 이 워크숍은 기본 개념부터 복잡한 에이전트 시스템까지 포괄적인 학습 과정을 제공하며, 프로덕션 수준의 도구와 기술을 활용한 실습 학습을 강조합니다.

워크숍을 완료하면 개발자들은 다음에 대한 실무 경험을 쌓을 수 있습니다.

  • 에이전트의 기본 개념: 워크플로와 지능형 에이전트의 차이점 이해
  • 상태 관리: 복잡한 상태 전환 및 지속성 구현
  • 도구 통합: 외부 도구 기능 생성 및 관리
  • 현대 AI 스택: LangGraph, NVIDIA NIM 및 관련 툴링 활용

더 알아보기

실습을 통한 학습과 다양한 팁, 트릭이 궁금하시다면 Nemotron Labs 라이브스트림 다시보기인 “OpenRouter에서 NVIDIA Nemotron으로 보고서 생성 AI 에이전트 구축하기“를 시청해 보세요.

NVIDIA Nemotron 관련 최신 소식을 빠르게 받아보시려면 NVIDIA 뉴스를 구독하고, LinkedIn, X, Discord, YouTube에서 NVIDIA AI 채널을 팔로우하세요.

Discuss (0)

Tags