Skip to content

Assistant (pydantic-ai) 개요

truloop-assistant는 AI 대화형 비서 서비스입니다. pydantic-ai의 Agent 패턴을 기반으로 도구(Tool)를 활용한 지능적인 대화를 제공하며, Sendbird 채팅을 통해 사용자와 소통합니다.


기술 스택

항목기술설명
언어Python 3.14최신 Python 버전
웹 프레임워크FastAPI비동기 REST API
AI 프레임워크pydantic-aiAgent + Tool 기반 AI 프레임워크
AI 모델OpenRouterClaude Sonnet 4.6 (기본)
채팅SendbirdWebhook 수신 + 메시지 발송
캐시Redis대화 이력, Pending tool calls
지식 검색NumPy Vector StoreRAG (OpenAI Embeddings)
장기 기억Supermemory사용자별 AI 장기 기억 (선택적)
관측성Logfire자동 계측 (Agent, HTTP, Redis, FastAPI)
에러 추적SentryProduction 에러 모니터링
구조화 로깅structlogJSON 형식 stdout 출력 (CloudWatch 연동)
타입 체크basedpyright정적 타입 분석
코드 품질Ruff포맷팅 + 린팅
테스트pydantic-evalsAI 평가 기반 품질 관리
패키지 관리uv빠른 Python 패키지 매니저

주요 기능

기능설명
대화형 AI자연어 기반 사용자 대화
다국어 지원한국어, 영어, 일본어
Deferred Tool클라이언트 디바이스에서 실행되는 도구 (Human-in-the-Loop)
RAGNotion 문서 기반 지식 검색
장기 기억Supermemory 기반 사용자별 기억
다중 봇 페르소나봇별 성격/말투 커스터마이징 (5종: Ursula, Priya, Jay, Nolan, OD-1)
실시간 알림Sendbird 채팅으로 응답 전달
비회원 Agent비회원 전용 Agent (SMS/RCS/WhatsApp 기반 가용 시간 수집) — 미구현, 향후 구현 예정
Internal Eventstruloop-core에서 수신하는 이벤트 처리 (봇 선택, 일정 초대 등)
메시지 청킹--- 구분자로 응답을 분할하여 자연스러운 대화 흐름 연출

프로젝트 구조

src/truloop_assistant/
├── __init__.py              # Logfire 초기화
├── main.py                  # FastAPI 진입점 (Application Factory)
├── config.py                # 환경 설정 (pydantic-settings)
├── observability.py         # Logfire + Sentry + structlog 초기화
├── handlers.py              # Exception 핸들러
├── dependencies.py          # FastAPI DI
├── agent/
│   ├── base.py             # 회원 Agent 초기화 (Singleton)
│   ├── guest_agent.py      # 비회원 Agent 초기화 (Singleton)
│   ├── deps.py             # AgentDeps (회원 런타임 의존성)
│   ├── guest_deps.py       # GuestAgentDeps (비회원 런타임 의존성)
│   ├── persona.py          # 봇 페르소나 정의 (YAML 로드)
│   ├── personas.yaml       # 5종 봇 페르소나 설정
│   ├── prompts.py          # 시스템 프롬프트 (정적)
│   ├── instructions.py     # 동적 프롬프트 (per-request)
│   ├── decorators.py       # 도구 데코레이터 (현재 비어 있음)
│   └── tools/              # 도구 시스템
│       ├── __init__.py     # all_toolsets, notification_safe_toolsets
│       ├── datetime_tools.py
│       ├── event_tools.py
│       ├── guest_tools.py   # 비회원 Agent 전용 도구
│       ├── interaction_tools.py
│       ├── knowledge_tools.py
│       ├── memory_tools.py
│       ├── permission_tools.py
│       ├── places_tools.py
│       ├── relay_tools.py
│       ├── user_tools.py
│       └── validation.py
├── integrations/
│   ├── sendbird/            # Sendbird 채팅 클라이언트
│   ├── truloop/             # truloop Core API 클라이언트
│   ├── supermemory/         # Supermemory 장기 기억
│   └── messaging/           # 비회원 메시징 (SMS/RCS) ⚠ 미구현 — scaffolding만 존재
│       ├── gateway.py       # MessagingGateway 인터페이스
│       ├── providers/       # 프로바이더 구현 (stub만 동작, twilio 미구현)
│       └── schemas.py       # 메시징 스키마
├── routes/
│   ├── core.py              # /, /health
│   ├── webhook.py           # /sendbird/webhook/{eid}
│   ├── sendbird.py          # /sendbird/send
│   ├── messaging_webhook.py # /messaging/webhook/{provider}
│   ├── internal/
│   │   └── events.py       # /internal/events (truloop-core 이벤트)
│   └── v1/
│       └── agent.py         # POST /api/v1/agent/tool-message
├── services/
│   ├── webhook_processor.py          # Sendbird Webhook 처리
│   ├── tool_message_processor.py     # Tool 결과 처리
│   ├── agent_response_handler.py     # Agent 응답 처리
│   ├── agent_response_router.py      # Agent 응답 라우팅
│   ├── agent_resumption.py           # Agent 재개 (Deferred Tool 완료 시)
│   ├── agent_notification.py         # Agent 기반 알림 생성/발송
│   ├── deferred_tool_handler.py      # Deferred Tool 핸들러 프로토콜
│   ├── deferred_tool_processor.py    # Deferred Tool 처리
│   ├── event_processor.py            # Internal 이벤트 처리
│   ├── message_history.py            # 대화 이력 관리 (Redis)
│   ├── pending_calls.py              # Pending tool call 추적 (Redis)
│   ├── rag_service.py                # RAG 검색 서비스
│   ├── vector_store.py               # NumPy 벡터 스토어
│   ├── user_profile.py               # 사용자 프로필 조회
│   ├── user_profile_cache.py         # 프로필 캐시
│   ├── user_lookup.py                # 사용자 조회
│   ├── bot_resolution.py             # 봇 결정 서비스
│   ├── loop_card_builder.py          # Loop Card 빌더
│   ├── loop_invitation_notifier.py   # 룹 초대 알림
│   ├── loop_coordination_notifier.py # 룹 조율 알림
│   ├── guest_invitation_notifier.py  # 비회원 초대 알림 (SMS)
│   └── guest_messaging_processor.py  # 비회원 메시징 처리
├── schemas/
│   ├── webhook.py              # Sendbird Webhook 스키마
│   ├── sendbird.py             # Sendbird 데이터 모델
│   ├── jsonrpc.py              # JSON-RPC 2.0 스키마
│   ├── auth.py                 # 인증 스키마 (JWT, User)
│   ├── agent_output.py         # Agent 출력 스키마 (AgentOutput)
│   ├── events.py               # Internal 이벤트 스키마 (Discriminated Union)
│   ├── loop_card.py            # Loop Card (RichContent) 스키마
│   └── responses.py            # HTTP 응답 스키마
└── utils/
    ├── errors.py               # 에러 유틸리티
    ├── mention.py              # Sendbird 멘션 포맷
    ├── message_chunking.py     # 메시지 청킹 (--- 구분자)
    ├── sendbird_signature.py   # Webhook 서명 검증
    └── tasks.py                # ConversationTaskRegistry

API 엔드포인트

Unversioned (인프라/Webhook)

경로인증설명
GET /없음Welcome
GET /health없음헬스체크 (Load Balancer)
POST /sendbird/webhook/{eid}Webhook SecretSendbird Webhook 수신 (eid로 페르소나 선택)
POST /sendbird/send없음Sendbird 메시지 발송
POST /messaging/webhook/{provider}없음비회원 메시징 Webhook (SMS/RCS) — 미구현

Internal (truloop-core 연동)

경로인증설명
POST /internal/eventsX-Internal-API-KeyInternal 이벤트 수신 (봇 선택, 일정 초대 등)

Versioned (클라이언트)

경로인증설명
POST /api/v1/agent/tool-messageJWTTool 결과/에러 제출

개발 명령어

bash
# 의존성 설치
uv sync

# 개발 서버 (auto-reload)
uv run fastapi dev src/truloop_assistant/main.py:app

# 프로덕션 서버
uv run fastapi run src/truloop_assistant/main.py:app

# 코드 품질 검사
uv run ruff format .
uv run ruff check --fix .
uv run basedpyright .

# 유닛 테스트
uv run pytest

# AI 평가 실행
cd evals && uv run python run_eval.py

# Docker 빌드 (ARM64/Graviton)
docker buildx build --platform linux/arm64 -t truloop-assistant:latest .

테스트 전략

정보

AI Agent의 행동은 pydantic-evals 평가로 테스트합니다. 유닛 테스트는 API 계약만 검증합니다.

테스트 유형도구파일설명
API 계약pytesttests/test_api_contracts.pyHTTP 엔드포인트 계약
Tool 사용pydantic-evalsevals/datasets/datetime_tools.yaml도구 호출 정확성
대화 품질pydantic-evalsevals/datasets/chat.yaml대화 응답 품질

변경 이력

날짜변경 내용
2026-03-12availability_deadline 지원: event_tools (create/update), 시스템 프롬프트, 초대/조율 알림에 마감 시각 안내 포함. LoopCard 빌드 실패 시 graceful fallback 추가
2026-03-11ECS Fargate ARM64 (Graviton) 전환 반영 — Docker 빌드 플랫폼 linux/arm64, ECS task cpuArchitecture: ARM64
2026-03-11비회원 Agent / SMS two-way 기능을 미구현 상태로 정정
2026-03-10비회원 Agent, Internal Events, 메시지 청킹, 프로젝트 구조 트리 전면 업데이트