OpenAI Agents SDK로 빌드 에이전트의 백업 데이터베이스 로 MongoDB 사용할 수 있습니다. Agents SDK는 다음과 같은 작은 기본 설정하다 로 에이전트 애플리케이션을 빌드하기 위한 Python 프레임워크 입니다.
에이전트는 지침과 도구로 구성된 대규모 언어 모델(LLM)입니다.
핸드오프: 한 에이전트 다른 에이전트 에게 작업 위임할 수 있습니다.
에이전트 의 입력과 출력의 유효성을 검사하는 가드레일입니다.
세션은 에이전트 실행 전반에 걸쳐 대화 기록을 저장 .
SDK는 두 가지 설계 원칙을 따릅니다. 여기에는 실제 애플리케이션을 빌드 에 충분한 기능이 포함되어 있지만 짧은 시간에 학습 하기에는 기본 요소가 충분하지 않습니다. 기본값도 좋은 결과를 제공하며 에이전트 실행 의 모든 단계를 사용자 지정할 수 있습니다.
Agents SDK와 함께 MongoDB 사용하는 이유
Agents SDK는 MongoDB 에서 대화 기록을 유지하는 세션 구현 MongoDBSession를 제공합니다. 해당 기록을 MongoDB 에 저장하면 에이전트에 다음과 같은 이점이 있습니다.
수평으로 확장 가능한 멀티 프로세스 세션 저장. 세션 상태 단일 프로세스 의 메모리가 아닌 클러스터 에 상주하므로 동일한 클러스터 에 연결되는 모든 작업자, 컨테이너 또는 서버리스 함수는 대화를 계속할 수 있습니다. 각 메시지는 단조롭게 증가하는 카운터를
seq전달하여 동시 작성기 간에 메시지 순서를 유지합니다.대화 및 애플리케이션 데이터를 위한 하나의 데이터베이스 . 애플리케이션 에서 이미 MongoDB 사용하는 경우, 에이전트는 배포 하고 보호할 별도의 메모리 서비스 없이 동일한 연결과 동일한 운전자 통해 운영 데이터를 읽고 세션 기록을 쓰기 (write) .
에이전트 상태 에 대한 유연한 문서. 문서 모델 대화 회전, 도구 호출 및 구조화된 출력이 발전함에 따라 함께 저장하므로 스키마 마이그레이션 없이 기록 확장할 수 있습니다.
쿼리 가능 에이전트 기록. 세션 기록은 일반 컬렉션에 저장되므로 감사 동작 에이전트 감사하거나 분석 빌드 위해 쿼리, 애그리게이션 및 인덱스 할 수 있습니다.
검색 경로입니다. 에이전트가 이미 MongoDB 에 연결되어 있으므로 동일한 클러스터 에 MongoDB Vector Search를 추가하여 데이터에 대한 시맨틱 검색을 제공할 수 있습니다. 자세한 학습 은 Agentic RAG를 참조하세요.
튜토리얼
이 튜토리얼에서는 다중 에이전트 여행 도우미를 빌드 . 분류 에이전트 두 명의 전문가 에이전트를 도구로 호출하여 질문에 답변하고, 두 전문가는 대화 세션을 저장하는 동일한 클러스터 에서 참조 데이터를 읽습니다.
전제 조건
이 튜토리얼을 완료하려면 다음 조건을 충족해야 합니다.
Python 3.10 이상.
다음 MongoDB cluster 유형 중 하나입니다.
MongoDB 버전 6.0.11을 실행하는 Atlas 클러스터 7.0.2 또는 그 이상. IP 주소가 Atlas 프로젝트의 액세스 목록에 포함되어 있는지 확인하세요.
Python 과 Docker 사용하여 만든 로컬 Atlas
atlas-local-lib-pypip install atlas-local-lib-py배포서버 .()을(를)설치하여 로컬 배포를 프로그래밍 방식으로 생성하고 관리 . 자세한 학습 은 atlas-local-lib-py 리포지토리 참조하세요.검색 및 벡터 검색이 설치된 MongoDB Community 클러스터 .
OpenAI API 키입니다. API 요청에 사용할 수 있는 크레딧이 있는 OpenAI 계정이 있어야 합니다. OpenAI 계정 등록에 대한 자세한 내용은 OpenAI API 웹사이트를 참조하세요.
환경 설정
환경 변수를 설정합니다.
애플리케이션 ATLAS_URI에서 Atlas 연결 문자열 읽고, Agents SDK는 OPENAI_API_KEY에서 키를 읽습니다.
export ATLAS_URI="<connection-string>" export OPENAI_API_KEY="<api-key>"
<connection-string> 자리 표시자 값을 클러스터의 SRV 연결 문자열 로 바꿉니다.
연결 문자열은 다음 형식을 사용해야 합니다.
mongodb+srv://<db_username>:<db_password>@<clusterName>.<hostname>.mongodb.net
에이전트 구축
애플리케이션 파일 만듭니다.
multi_agent_app.py 이라는 파일 만들고 다음 코드를 붙여넣습니다. 인라인 주석은 애플리케이션 의 각 부분에서 MongoDB 사용하는 방법을 설명합니다.
"""Multi-agent travel assistant backed by MongoDB Atlas. A triage agent answers travel questions by calling two specialist agents as tools. Both specialists read reference data from the same Atlas cluster that stores the conversation session, so every agent in the application shares one database. """ import asyncio import os from agents import Agent, Runner, function_tool from agents.extensions.memory import MongoDBSession from pymongo import AsyncMongoClient # The script reads your credentials from the environment so that you # don't commit them to source control. REQUIRED_ENV_VARS = ("ATLAS_URI", "OPENAI_API_KEY") DATABASE_NAME = "travel_assistant" # One client serves both the agent tools and the session store. Because # you create the client yourself, your application owns its lifecycle. # main() assigns both of these after it validates the environment. client: AsyncMongoClient | None = None database = None async def lookup_destination(city: str) -> str: """Look up travel guidance for a destination city.""" # Sub-agent tools query the shared database directly, so the agents # answer from your data instead of from model training data. document = await database.destinations.find_one({"city": city}) if document is None: return f"No destination guide found for {city}." return ( f"{document['city']}: best months are {document['best_months']}. " f"{document['summary']}" ) async def lookup_policy(topic: str) -> str: """Look up the company travel policy for a topic.""" document = await database.policies.find_one({"topic": topic}) if document is None: return f"No policy found for {topic}." return f"{document['topic']}: {document['rule']}" # Each specialist is a full agent with its own instructions and tools. destination_agent = Agent( name="Destination expert", instructions=( "You advise travelers on destinations. Always call " "lookup_destination and answer only from what it returns." ), tools=[lookup_destination], ) policy_agent = Agent( name="Policy expert", instructions=( "You answer questions about the company travel policy. Always " "call lookup_policy and answer only from what it returns." ), tools=[lookup_policy], ) # The as_tool() pattern turns each specialist into a tool that the # triage agent can call. Unlike a handoff, control returns to the # triage agent after each call, so it can combine both answers in one # reply. triage_agent = Agent( name="Travel assistant", instructions=( "You are a travel assistant. Use the destination and policy " "tools to gather facts before you answer, and call both when " "the question needs both. Remember details the traveler shared " "earlier in the conversation." ), tools=[ destination_agent.as_tool( tool_name="ask_destination_expert", tool_description="Get travel guidance about a city.", ), policy_agent.as_tool( tool_name="ask_policy_expert", tool_description="Get the company travel policy for a topic.", ), ], ) async def seed_reference_data() -> None: """Load the sample data that the specialist agents read.""" await database.destinations.delete_many({}) await database.policies.delete_many({}) await database.destinations.insert_many( [ { "city": "Lisbon", "best_months": "March through May", "summary": "Mild spring weather and low hotel rates.", }, { "city": "Reykjavik", "best_months": "June through August", "summary": "Long daylight hours and open highland roads.", }, ] ) await database.policies.insert_many( [ {"topic": "flights", "rule": "Book economy for flights under six hours."}, {"topic": "hotels", "rule": "Nightly rates must stay under 250 USD."}, ] ) async def main() -> None: global client, database # Fail fast with a clear message instead of surfacing a connection # error or an authentication error later in the run. missing = [name for name in REQUIRED_ENV_VARS if not os.environ.get(name)] if missing: raise SystemExit( "Set these environment variables before you run this script: " + ", ".join(missing) ) client = AsyncMongoClient(os.environ["ATLAS_URI"]) database = client[DATABASE_NAME] await seed_reference_data() # The session stores conversation history in Atlas. Pass the # existing client so the session and the agent tools share one # connection pool. session = MongoDBSession( session_id="traveler-123", client=client, database=DATABASE_NAME, ) # Confirm connectivity before the first run. await session.ping() # The Runner loads prior turns from the session and writes the new # turn back, so the second question resolves "there" without you # passing the history yourself. first = await Runner.run( triage_agent, "I'm planning a trip to Lisbon. When should I go?", session=session, ) print(first.final_output) second = await Runner.run( triage_agent, "What's our hotel budget for that trip?", session=session, ) print(second.final_output) # session.close() is a no-op when you supply the client, so close # the client yourself. await client.close() if __name__ == "__main__": asyncio.run(main())
애플리케이션을 실행합니다.
python multi_agent_app.py
에이전트 destinations 컬렉션 의 첫 번째 질문과 policies 컬렉션 의 두 번째 질문에 답변합니다. 세션은 MongoDB 에 첫 번째 차례를 저장하기 때문에 어시스턴트는 "해당 여행"을 해결합니다. 기록을 직접 전달하지 않고 두 번째 질문에 답변합니다.
For Lisbon, the best time to go is **March through May**. That's the sweet spot for **mild weather**, comfortable sightseeing, **fewer crowds**, and generally **better hotel rates** than peak summer. If you want the best single month, I'd pick **May** for warmer days while still avoiding the biggest summer crowds. I still don't see a company policy entry for a **Lisbon hotel budget/nightly cap**. Best next step: check the company booking tool or ask your travel/admin team to confirm the approved lodging allowance for Lisbon.
애플리케이션이 MongoDB 사용하는 방법
애플리케이션 하나의 AsyncMongoClient을(를) 생성하고 이를 에이전트와 세션 전체에서 공유합니다.
전문 에이전트는 도구 기능에서
destinations및policies컬렉션을 쿼리 데이터에서 답변 .MongoDBSession각 대화 차례를 동일한 데이터베이스 의agent_sessions및agent_messages컬렉션에 씁니다. 두 컬렉션 이름 모두 구성할 수 있으며 세션은 처음 사용할 때 필요한 인덱스를 생성합니다.
애플리케이션 클라이언트 자체를 구성하므로 클라이언트 수명 주기는 애플리케이션 에 속하며 session.close()는 아무 작업도 수행하지 않습니다. 대신 세션이 클라이언트 를 소유하게 하려면 MongoDBSession.from_uri()로 생성합니다.
다음 단계
Agents SDK로 여러 에이전트를 조정하는 방법에 대해 자세히 학습 OpenAI 문서의 다음 페이지를 참조하세요.
코드를 통한 오케스트레이션과 LLM을 통한 오케스트레이션 간의 균형을 위해여러 에이전트를 오케스트레이션합니다.
대화를 도구로 호출하는 대신 다른 에이전트 에게 대화를위임하기 위한 핸드오프입니다.