Add evaluation operations and reporting

This commit is contained in:
dahyeon committed 2026-05-12 08:16:31 -07:00
1 parent 60f33b8f4b
commit a900016be4
60 files changed
+8689 -142

No files matched your search

+575
View File
@@ -0,0 +1,575 @@
# Lolympus Agent 포트폴리오 정리본
> Confluence에 그대로 옮겨도 읽히도록 작성한 상세 설명 자료입니다.
> Mermaid 다이어그램은 Confluence Mermaid 매크로나 Mermaid 지원 플러그인에 붙여 넣으면 됩니다.
## 1. 프로젝트 한 줄 소개
Lolympus Agent는 게임 커뮤니티의 신규 멤버 온보딩을 자동화하는 TypeScript 기반 LLM Agent입니다.
카카오톡 오픈채팅 본체 서비스가 NATS request/reply로 요청을 보내면, Agent가 Redis/Garnet에 저장된 온보딩 세션, 최근 대화, MongoDB 채팅방 맥락, LLM 응답, 도구 호출 결과를 조합해 신규 멤버에게 필요한 안내만 짧고 정확하게 반환합니다.
핵심은 단순 챗봇이 아니라, 커뮤니티 규칙과 유저 상태를 기반으로 LLM을 제어하는 운영형 온보딩 에이전트라는 점입니다.
## 2. 포트폴리오 요약
| 항목 | 내용 |
| --- | --- |
| 프로젝트명 | Lolympus Agent |
| 목적 | 게임 커뮤니티 신규 멤버 등록 절차 자동 안내 |
| 주요 기능 | 닉네임 형식 안내, 하트 인증 안내, 진행상황 안내, 마감 임박 안내, 디스코드 닉네임 확인, 잡담/타인 멘션 응답 스킵 |
| 핵심 기술 | TypeScript, Node.js, NATS, Redis/Garnet, MongoDB/Mongoose, OpenTelemetry, Pino, Zod, Vitest, LLM provider routing |
| 아키텍처 키워드 | Event-driven, request/reply agent, state-driven orchestration, tool calling, shadow evaluation, circuit breaker, background worker |
| 운영 포인트 | 요청 단위 tracing/logging, LLM endpoint circuit breaker, shadow eval sampling, alert subject 발행, Redis Stream 기반 worker/DLQ |
## 3. 문제 정의
커뮤니티 신규 멤버 등록은 반복적인 안내가 많지만, 실제 응답은 단순 FAQ보다 복잡합니다.
1. 유저마다 남은 절차가 다릅니다.
예를 들어 닉네임은 완료했지만 하트 인증은 안 했을 수 있고, 1단계 이후 디스코드 프로필 단계가 남아 있을 수도 있습니다.
2. 질문 의도가 짧고 모호합니다.
"이제 뭐 남았죠?", "어디서 해요?", "닉변 됐나요?" 같은 메시지는 세션 상태와 최근 대화 맥락을 함께 봐야 정확히 답할 수 있습니다.
3. LLM만 사용하면 규칙 위반 가능성이 있습니다.
디스코드 안내를 너무 일찍 하거나, 잘못된 닉네임 예시를 들거나, 유저가 묻지 않은 절차를 길게 붙이는 문제가 생길 수 있습니다.
4. 운영 환경에서는 응답 시간과 장애 대응도 중요합니다.
LLM endpoint 장애, 네트워크 지연, 도구 호출 실패가 있어도 서비스 전체가 멈추지 않아야 합니다.
이 프로젝트는 위 문제를 해결하기 위해 "결정론적 상태 판단 + LLM 응답 생성 + validator + fallback template + shadow eval" 구조로 설계했습니다.
## 4. 전체 아키텍처
```mermaid
flowchart LR
Main["카카오톡 본체 서비스"] -->|"NATS request/reply<br/>lolympus-agent.request"| Agent["Agent<br/>src/agent/agent.ts"]
Agent -->|"대화 조회/저장"| Conv[("Garnet/Redis<br/>conversation history")]
Agent --> Skill["OnboardingSkill<br/>src/skills/onboarding/skill.ts"]
Skill -->|"온보딩 세션 조회"| Session[("Garnet/Redis<br/>lolympus:onboarding:*")]
Skill -->|"최근 방 대화 조회"| Mongo[("MongoDB<br/>events collection")]
Skill --> Classifier["Intent Classifier<br/>regex first, LLM fallback"]
Skill --> Derived["State Derivation<br/>phase, intent, tier"]
Skill --> Prompt["Prompt Builder<br/>persona/policy/state/examples/context"]
Skill --> Orchestrator["Orchestrator<br/>tier 0/1/2"]
Orchestrator --> LLM["LlmClient<br/>provider routing + circuit breaker"]
LLM --> Provider1["CLI Proxy"]
LLM --> Provider2["OpenRouter"]
LLM --> Provider3["Local Llama"]
Orchestrator --> Tools["Tool Loop<br/>Zod schema tools"]
Tools -->|"Discord lookup"| Main
Tools -->|"rule/session/context lookup"| Session
Skill --> Validator["Validator<br/>state consistency, URL whitelist, length"]
Skill -->|"shadow eval job"| BgStream[("Redis Stream<br/>lolympus-agent:background")]
BgStream --> Worker["Background Worker<br/>src/workers/background.ts"]
Worker --> Eval[("Eval results stream")]
Worker --> Alert["NATS alert<br/>lolympus-agent.alert"]
Agent -->|"AgentResponse"| Main
```
## 5. 요청 처리 시퀀스
```mermaid
sequenceDiagram
autonumber
participant Main as 카카오톡 본체
participant NATS as NATS
participant Agent as Agent
participant Conv as ConversationStore
participant Skill as OnboardingSkill
participant Redis as Garnet/Redis
participant Mongo as MongoDB RoomContext
participant LLM as LlmClient
participant Eval as ShadowEvalBus
Main->>NATS: request(lolympus-agent.request, AgentRequest)
NATS->>Agent: raw message 전달
Agent->>Agent: request schema 검증
Agent->>Agent: AsyncLocalStorage request context 생성
Agent->>Conv: getHistory(chatroomId, userId)
Conv->>Redis: lolympus-agent:conv:* 조회
Redis-->>Conv: 최근 대화
Conv-->>Agent: history
opt userMessage가 있는 경우
Agent->>Conv: appendMessage(user)
Conv->>Redis: conversation 저장
end
Agent->>Skill: handle(request, history)
Skill->>Redis: 온보딩 세션 조회
Redis-->>Skill: OnboardingSession
Skill->>Skill: classify(trigger, userMessage)
Skill->>Skill: deriveState(session, trigger, intent)
alt shouldRespond = false
Skill-->>Agent: empty response
else template mode
Skill->>Skill: template fallback 생성
Skill-->>Agent: template response
else LLM mode
par context load
Skill->>Redis: blackboard 조회
Skill->>Redis: summary 조회
Skill->>Mongo: recent room messages 조회
end
Skill->>Skill: PromptBuilder.build()
Skill->>LLM: chatCompletion(messages, tier/model/deadline)
LLM-->>Skill: draft response
Skill->>Skill: validateOnboardingResponse()
alt validator reject or LLM failure
Skill->>Skill: template fallback
end
Skill-->>Agent: final response
end
opt 응답 text가 있는 경우
Skill->>Redis: blackboard update
Skill->>Eval: shadow eval publish
Eval->>Redis: XADD lolympus-agent:background
Agent->>Conv: appendMessage(assistant)
end
Agent->>NATS: respond(AgentResponse)
NATS-->>Main: response
```
## 6. 디스코드 닉네임 확인 시퀀스
디스코드 닉네임 확인은 LLM이 직접 추측하지 않도록 tool calling으로 분리했습니다.
LLM은 "조회가 필요한 상황"을 판단하고, 실제 확인은 `verify-discord-nickname` 도구가 NATS로 본체 서비스에 요청합니다.
```mermaid
sequenceDiagram
autonumber
participant User as 유저
participant Agent as OnboardingSkill
participant Orchestrator as Orchestrator
participant LLM as LLM
participant ToolLoop as ToolLoop
participant Tool as verify-discord-nickname
participant Main as 본체 Discord Lookup
participant Redis as Garnet/Redis
User->>Agent: "디코 닉변 됐나요?"
Agent->>Agent: intent = discord-verify-question
Agent->>Agent: responseMode = llm-with-tools, tier = 1
Agent->>Orchestrator: run(derived, messages, tools)
Orchestrator->>LLM: planner JSON 요청
LLM-->>Orchestrator: suggestedTools = [verify-discord-nickname]
Orchestrator->>ToolLoop: responder with native/Hermes tools
ToolLoop->>LLM: tool 사용 가능한 메시지 전달
LLM-->>ToolLoop: tool_call verify-discord-nickname
ToolLoop->>Tool: execute()
Tool->>Tool: 세션 닉네임 형식 검사
Tool->>Main: NATS request(lolympus.discord.lookup-members)
Main-->>Tool: 후보 Discord member 목록
Tool->>Tool: Kakao nickname 기반 Discord nickname rule 검증
opt Discord memberId 확인됨
Tool->>Redis: session.discordMemberId 저장
end
Tool-->>ToolLoop: 구조화된 결과 반환
ToolLoop->>LLM: tool result 전달
LLM-->>ToolLoop: 최종 한국어 응답
ToolLoop-->>Orchestrator: final response
Orchestrator-->>Agent: response
```
## 7. Shadow Eval 및 Alert 시퀀스
운영 트래픽 전체를 동기 평가하면 응답 지연이 커지므로, 실제 응답과 평가를 분리했습니다.
Agent는 샘플링된 요청만 Redis Stream에 넣고, Background Worker가 비동기로 validator와 LLM judge를 실행합니다.
```mermaid
sequenceDiagram
autonumber
participant Skill as OnboardingSkill
participant Stream as Redis Stream
participant Worker as ShadowWorker
participant Rule as Rule Judge
participant LLMJudge as LLM Judge
participant Results as Eval Results Stream
participant Alert as AlertService
participant NATS as NATS
Skill->>Stream: XADD type=shadow-eval
Worker->>Stream: XREADGROUP bg-worker
Worker->>Rule: validator 기반 rule judge
Worker->>LLMJudge: friendliness/accuracy/concision/scope 평가
Worker->>Results: XADD shadow-eval-result
Worker->>Worker: 최근 5분 latency/score/error 집계
alt p95 latency, score drop, LLM error rate, circuit open 임계값 초과
Worker->>Alert: sendAlert()
Alert->>Stream: dedupe key SET NX
Alert->>NATS: publish lolympus-agent.alert
end
Worker->>Stream: XACK
```
## 8. 상태 모델
온보딩 응답은 "지금 유저가 어느 단계인지"와 "무엇을 물었는지"를 분리해 판단합니다.
```mermaid
stateDiagram-v2
[*] --> fresh
fresh --> both_pending: 세션 있음, 닉네임/사진 미완료
both_pending --> nickname_pending: 사진 완료
both_pending --> photo_pending: 닉네임 완료
nickname_pending --> step1_completed: 닉네임 완료
photo_pending --> step1_completed: 사진 완료
step1_completed --> completed: 확장 추적 항목 모두 완료
step1_completed --> deadline_near: 마감 임박
both_pending --> nickname_rejected: nickname-invalid trigger
both_pending --> photo_rejected: photo-failed trigger
nickname_pending --> nickname_rejected: nickname-invalid trigger
photo_pending --> photo_rejected: photo-failed trigger
fresh --> timed_out: status = timed_out
completed --> [*]
timed_out --> [*]
```
주요 intent는 다음과 같습니다.
| Intent | 의미 | 처리 방향 |
| --- | --- | --- |
| `greeting` | 인사 | 짧게 응답 |
| `acknowledgement` | 감사/확인 | 짧게 응답 |
| `status-question` | 남은 절차 질문 | 완료된 절차 제외, 남은 것만 안내 |
| `help-how` | 방법 질문 | 해당 단계 방법만 안내 |
| `help-where` | 위치 질문 | 위치/경로만 안내 |
| `nickname-question` | 카카오톡 닉네임 질문 | 형식/오류 원인 안내 |
| `photo-question` | 하트 인증 질문 | 하트 인증만 안내 |
| `discord-question` | 디스코드 일반 질문 | 1단계 완료 여부에 따라 제한 |
| `discord-verify-question` | 디스코드 닉네임 확인 | tool calling으로 실제 조회 |
| `chitchat`, `off-topic-to-other` | 잡담/타인 대상 메시지 | `[NO_RESPONSE]` 또는 빈 응답 |
## 9. 핵심 구현 포인트
### 9.1 NATS 기반 Agent 레이어
관련 파일: `src/main.ts`, `src/agent/agent.ts`, `src/agent/types.ts`
- `src/main.ts`에서 환경변수 로딩, logger/tracing 초기화, NATS/Garnet/MongoDB 연결, LLM client와 skill 등록을 수행합니다.
- Agent는 `lolympus-agent.request` subject를 구독하고 request/reply 패턴으로 응답합니다.
- 모든 요청은 `AsyncLocalStorage` 기반 request context로 감싸져 requestId, chatroomId, userId, trigger가 로그와 span에 자동 포함됩니다.
- 요청 전후로 conversation history를 Redis에 저장해 multi-turn 응답 품질을 유지합니다.
### 9.2 Regex-first intent classifier
관련 파일: `src/skills/onboarding/state/classifier.ts`, `src/skills/onboarding/message-filter.ts`
Classifier는 비용과 latency를 줄이기 위해 regex를 먼저 사용합니다.
- trigger가 명확한 이벤트는 바로 intent로 매핑합니다. 예: `nickname-invalid` -> `nickname-question`
- 인사, 감사, 진행상황 질문, 위치 질문, 디스코드 확인 질문 등 자주 나오는 표현은 regex로 처리합니다.
- regex confidence가 낮은 경우에만 LLM JSON classifier로 fallback합니다.
이 구조는 운영상 유리합니다. 흔한 질문은 LLM 호출 없이 빠르게 처리하고, 애매한 질문만 LLM에 맡길 수 있습니다.
### 9.3 Derived State로 응답 모드 결정
관련 파일: `src/skills/onboarding/state/derive.ts`, `src/skills/onboarding/state/transitions.ts`
`deriveState()`는 세션, trigger, intent를 조합해 다음 값을 결정합니다.
- `phase`: 현재 온보딩 단계
- `shouldRespond`: 응답할지 스킵할지
- `responseMode`: `skip`, `template`, `llm`, `llm-with-tools`
- `tier`: LLM orchestration 단계
- `suggestedMaxTokens`: 상황별 token budget
- `allowShortResponse`: 짧은 응답 허용 여부
예를 들어 닉네임 오류 상태는 `llm-with-tools`, tier 1로 승격됩니다. 반대로 잡담이나 타인 멘션은 응답하지 않습니다.
### 9.4 Layered Prompt Builder
관련 파일: `src/skills/onboarding/prompts/builder.ts`, `src/skills/onboarding/prompts/layers.ts`
Prompt는 하나의 거대한 system prompt가 아니라 여러 layer를 조립합니다.
1. `personaLayer`: 커뮤니티 선배 역할과 핵심 규칙
2. `policyLayer`: intent별 답변 정책
3. `stateLayer`: 현재 세션 상태와 남은 절차
4. `examplesLayer`: intent별 few-shot 예시
5. `contextLayer`: 최근 대화, 요약, 방 분위기, blackboard 메모
이 방식의 장점은 변경 범위를 줄일 수 있다는 점입니다.
예를 들어 디스코드 응답 정책을 수정할 때 전체 prompt를 건드리지 않고 `policyLayer`와 관련 예시만 조정할 수 있습니다.
### 9.5 Tier 기반 LLM Orchestration
관련 파일: `src/skills/onboarding/runtime/orchestrator.ts`, `src/skills/onboarding/runtime/critic.ts`
모든 요청을 동일하게 처리하지 않고 난이도에 따라 tier를 나눕니다.
| Tier | 흐름 | 사용 상황 |
| --- | --- | --- |
| Tier 0 | Direct responder | 인사, 상태 질문, 일반 안내 |
| Tier 1 | Planner -> Responder | 닉네임 오류, 디스코드 확인, 마감 임박 |
| Tier 2 | Planner -> Responder -> Critic/Rewrite | 더 높은 정확도가 필요한 복잡 상황 |
Orchestrator는 request deadline을 확인해 남은 시간이 부족하면 고비용 tier를 포기하고 더 빠른 경로로 내려갑니다.
즉, 품질과 응답 시간을 함께 관리합니다.
### 9.6 LLM Provider Routing과 Circuit Breaker
관련 파일: `src/llm/llm-client.ts`, `src/llm/routing.ts`, `src/llm/circuit.ts`
LLM client는 provider 우선순위를 적용합니다.
1. CLI Proxy
2. OpenRouter
3. Local Llama
각 endpoint는 health check와 circuit breaker 상태를 거칩니다.
연속 실패가 발생하면 해당 endpoint를 cooldown 상태로 두고 다른 provider로 fallback합니다.
### 9.7 Tool Calling 호환 계층
관련 파일: `src/tools/*`, `src/skills/onboarding/runtime/tool-loop.ts`
Tool interface는 Zod schema를 포함합니다.
```ts
interface Tool<A, R> {
name: string;
description: string;
argsSchema: ZodType<A>;
resultSchema: ZodType<R>;
execute(args: A, ctx: ToolContext): Promise<R>;
}
```
지원 도구:
| Tool | 역할 |
| --- | --- |
| `validate-nickname` | 카카오톡 닉네임 형식 검사 |
| `check-onboarding-progress` | 현재 남은 절차 구조화 |
| `lookup-community-rule` | 나이 제한, 티어 코드, 하트 규칙 등 상수 조회 |
| `get-room-context` | 최근 채팅방 메시지 조회 |
| `verify-discord-nickname` | NATS로 본체에 Discord member lookup 요청 |
Parser는 OpenAI native `tool_calls`와 Hermes `<tool_call>` 포맷을 모두 처리합니다.
덕분에 provider가 바뀌어도 Agent runtime은 같은 tool interface를 사용할 수 있습니다.
### 9.8 LLM 응답 Validator
관련 파일: `src/skills/onboarding/runtime/validator.ts`
LLM 응답은 그대로 내보내지 않고 후처리와 검증을 거칩니다.
- `<think>` 제거
- 허용되지 않은 URL 제거
- 마크다운 제거
- 최대 길이 제한
- 빈 응답과 너무 짧은 응답 reject
- 디스코드 안내가 1단계 완료 전 과하게 나가는지 검사
- 잘못된 티어 코드가 포함된 닉네임 예시 reject
- intent별 기대 키워드 soft warning
- 반복 phrase soft warning
reject된 응답은 재시도하거나 template fallback으로 내려갑니다.
### 9.9 Memory와 Context
관련 파일: `src/conversation/conversation-store.ts`, `src/conversation/summarizer.ts`, `src/skills/onboarding/state/blackboard.ts`, `src/room-context/room-context-service.ts`
대화 품질을 위해 세 가지 context를 사용합니다.
| Context | 저장 위치 | 목적 |
| --- | --- | --- |
| Conversation history | `lolympus-agent:conv:{chatroomId}:{userId}` | 최근 user/assistant turn 유지 |
| Conversation summary | `lolympus-agent:summary:{chatroomId}:{userId}` | 긴 대화 압축 |
| Blackboard | `lolympus-agent:bb:{chatroomId}:{userId}` | 최근 intent, 열린 질문, 닉네임 시도, tone memory 저장 |
| Room context | MongoDB `events` collection | 최근 방 분위기와 타인 대상 메시지 판단 |
5턴 이상 누적되면 background stream에 summarize job을 넣고 worker가 비동기로 요약합니다.
### 9.10 Eval, Observability, Alert
관련 파일: `src/eval/*`, `src/observability/*`, `src/workers/background.ts`
운영 품질 관리를 위해 다음 구조를 갖고 있습니다.
- Pino logger: 환경별 log level, secret redaction
- OpenTelemetry spans: agent, skill, classifier, LLM, tool 단위 span
- ShadowEvalBus: 실제 응답을 샘플링해 Redis Stream에 기록
- ShadowWorker: rule judge, LLM judge, summary job 처리
- AlertService: latency, eval score drop, LLM error rate, open circuit 발생 시 NATS alert 발행
- DLQ: background job이 반복 실패하면 `lolympus-agent:background:dlq`로 이동
## 10. 주요 데이터 계약
### 10.1 Agent Request
```ts
interface AgentRequest {
requestId: string;
skill: string;
chatroomId: string;
userId: string;
nickname: string;
trigger: string;
userMessage?: string;
context?: Record<string, unknown>;
}
```
### 10.2 Agent Response
```ts
interface AgentResponse {
requestId: string;
text: string;
confidence: number;
source: "llm" | "template";
metadata?: Record<string, unknown>;
}
```
### 10.3 Redis/Garnet Key 설계
| Key | 목적 |
| --- | --- |
| `lolympus:onboarding:{chatroomId}:{userId}` | 본체가 작성하는 온보딩 세션. Agent는 주로 read |
| `lolympus-agent:conv:{chatroomId}:{userId}` | 최근 대화 |
| `lolympus-agent:summary:{chatroomId}:{userId}` | 대화 요약 |
| `lolympus-agent:bb:{chatroomId}:{userId}` | 온보딩 blackboard |
| `lolympus-agent:background` | shadow eval 및 summarize job stream |
| `lolympus-agent:background:dlq` | worker 실패 job DLQ |
| `lolympus-agent:eval:results` | shadow eval 결과 |
| `lolympus-agent:circuit:*` | LLM endpoint circuit breaker 상태 |
| `lolympus-agent:alert:dedupe:*` | alert rate limit/dedupe |
### 10.4 NATS Subject
| Subject | 방향 | 목적 |
| --- | --- | --- |
| `lolympus-agent.request` | 본체 -> Agent | 온보딩 응답 요청 |
| `lolympus.discord.lookup-members` | Agent -> 본체 | Discord member 조회 |
| `lolympus-agent.alert` | Agent worker -> 본체 | 운영 alert |
| `lolympus-agent.eval.report` | Eval CLI -> 본체/관찰자 | eval report 발행 |
## 11. 현재 리포지토리 기준 품질 지표
현재 저장된 리포지토리 스냅샷 기준입니다. 운영 KPI라기보다는 회귀 방지용 품질 자료로 보는 것이 안전합니다.
| 항목 | 현재 값 |
| --- | --- |
| 테스트 파일 | `src/**/*.test.ts` 기준 16개 |
| 주요 테스트 영역 | LLM routing, alert, eval worker, judges, shadow bus, parser, classifier, state derive, prompt builder, validator, tool loop, orchestrator, built-in tools |
| Golden eval case | 3개 |
| 저장된 baseline pass rate | 1.0 |
| 저장된 baseline rule average score | 1.0 |
| 저장된 baseline average latency | 3ms |
| 저장된 baseline LLM judge case | 0개 |
포트폴리오에는 다음처럼 쓰는 것이 좋습니다.
> 현재는 rule-based golden eval을 smoke benchmark로 운영하고 있으며, shadow eval과 LLM judge를 통해 운영 트래픽 기반 품질 평가로 확장 가능한 구조를 구현했습니다.
## 12. 포트폴리오에서 강조할 수 있는 기술적 성과
### 12.1 LLM을 제품 로직 안에 안전하게 넣은 구조
LLM에게 모든 판단을 맡기지 않고, `Intent -> DerivedState -> Prompt -> Orchestrator -> Validator -> Fallback` 파이프라인으로 감쌌습니다.
덕분에 커뮤니티 규칙, 유저 진행 상태, 응답 범위 제한을 코드 레벨에서 제어할 수 있습니다.
### 12.2 비용과 latency를 고려한 hybrid classifier
자주 나오는 짧은 메시지는 regex로 처리하고, 애매한 메시지만 LLM classifier로 넘깁니다.
이 방식은 LLM 호출 비용을 줄이고 p50 latency를 낮추는 데 유리합니다.
### 12.3 Provider 장애를 고려한 LLM client
Provider priority, health check, circuit breaker, fallback model을 한 레이어에 모았습니다.
외부 LLM endpoint가 불안정해도 서비스는 다른 endpoint 또는 template fallback으로 계속 응답할 수 있습니다.
### 12.4 Tool calling으로 사실 확인 분리
디스코드 닉네임 확인처럼 실제 조회가 필요한 기능은 LLM 추측이 아니라 tool execution으로 처리합니다.
또한 OpenAI tool call과 Hermes tool call을 모두 파싱해 provider 교체 가능성을 높였습니다.
### 12.5 운영 평가 루프
실제 응답을 shadow eval stream에 샘플링하고, background worker가 rule judge/LLM judge를 비동기로 수행합니다.
평가 결과가 나빠지거나 latency가 올라가면 alert subject로 알릴 수 있어, 단순 구현을 넘어 운영 가능한 LLM 시스템 형태를 갖췄습니다.
## 13. Confluence 페이지 구성 추천
Confluence에는 아래 순서로 넣으면 읽기 좋습니다.
1. 프로젝트 한 줄 소개
2. 문제 정의
3. 전체 아키텍처 다이어그램
4. 요청 처리 시퀀스 다이어그램
5. 핵심 구현 포인트
6. 운영 안정성 및 평가 구조
7. 데이터 계약과 저장소 설계
8. 성과/품질 지표
9. 배운 점과 개선 계획
## 14. 면접/리뷰에서 말하기 좋은 포인트
### Q. 왜 LLM만 쓰지 않고 상태 기반 파이프라인을 만들었나요?
온보딩 안내는 "친절한 문장"보다 "현재 단계에 맞는 정확한 안내"가 더 중요했습니다.
LLM은 표현 생성에 강하지만, 디스코드 안내 가능 여부나 닉네임 형식 같은 규칙 판단은 코드가 더 안정적입니다. 그래서 상태 판단과 validator는 코드가 담당하고, LLM은 최종 문장 생성과 애매한 의도 해석에 집중하게 했습니다.
### Q. 왜 tier를 나눴나요?
모든 요청에 planner, tool, critic을 붙이면 품질은 올라갈 수 있지만 latency와 비용이 커집니다.
인사나 단순 진행상황 질문은 direct response로 빠르게 처리하고, 닉네임 오류나 디스코드 확인처럼 정확도가 중요한 경우만 tier 1 이상으로 승격했습니다.
### Q. 환각은 어떻게 줄였나요?
세 가지 방식으로 줄였습니다.
1. prompt에 현재 세션 상태와 남은 절차를 명시합니다.
2. 실제 조회가 필요한 것은 tool calling으로 분리합니다.
3. 최종 응답을 validator로 검사하고, reject되면 재시도 또는 template fallback을 사용합니다.
### Q. 운영 중 품질 저하는 어떻게 감지하나요?
실제 응답을 Redis Stream에 shadow eval job으로 기록하고, worker가 rule judge와 LLM judge를 비동기로 실행합니다.
최근 5분 기준 p95 latency, LLM judge 점수 하락, judge error rate, LLM circuit open 상태를 감지해 NATS alert를 발행합니다.
### Q. 이 프로젝트에서 가장 어려웠던 점은 무엇인가요?
LLM 응답을 자연스럽게 만들면서도, 커뮤니티 규칙과 진행 상태를 벗어나지 않게 제어하는 점이 가장 어려웠습니다.
이를 해결하기 위해 prompt engineering만 하는 대신, 상태 모델, 도구, validator, fallback, eval을 하나의 파이프라인으로 묶었습니다.
## 15. 개선 계획
현재 구조에서 다음을 추가하면 포트폴리오 완성도가 더 올라갑니다.
| 개선 항목 | 기대 효과 |
| --- | --- |
| Golden set 30-50개로 확장 | 회귀 테스트 신뢰도 향상 |
| 운영 dashboard 추가 | latency, fallback rate, judge score 추이를 시각화 |
| OTLP exporter 연동 | Jaeger/Grafana Tempo 등으로 trace 분석 |
| prompt/version metadata 저장 | 응답 품질 저하 원인 추적 |
| eval case 자동 익명화 강화 | 실제 운영 데이터 기반 평가셋 구축 |
| 실패 응답 샘플 리뷰 페이지 | 운영자가 직접 prompt/tool 개선 포인트 확인 |
## 16. 포트폴리오용 짧은 소개 문장
> TypeScript와 NATS 기반으로 게임 커뮤니티 신규 멤버 온보딩을 자동화하는 LLM Agent를 설계/구현했습니다. Redis/Garnet 세션 상태, MongoDB 채팅 맥락, regex-first intent classifier, tier 기반 LLM orchestration, Zod schema tool calling, validator/fallback, shadow eval worker를 결합해 단순 챗봇이 아니라 운영 가능한 온보딩 자동화 시스템으로 구성했습니다.
## 17. 이력서용 bullet 예시
- NATS request/reply 기반 LLM Agent를 구현해 카카오톡 커뮤니티 신규 멤버 온보딩 안내를 자동화했습니다.
- Regex-first intent classifier와 상태 기반 `DerivedState` 모델을 설계해 응답 여부, LLM 사용 여부, tool calling 필요 여부를 결정했습니다.
- Tier 0/1/2 orchestration을 도입해 단순 질문은 빠르게, 검증이 필요한 질문은 planner/tool/critic 경로로 처리하도록 구성했습니다.
- Zod schema 기반 tool registry와 OpenAI/Hermes tool call parser를 구현해 provider에 덜 종속적인 tool execution 구조를 만들었습니다.
- LLM 응답 validator, URL whitelist, state consistency check, template fallback으로 커뮤니티 규칙 위반 가능성을 낮췄습니다.
- Redis Stream 기반 shadow eval worker와 alert pipeline을 구현해 운영 트래픽 기반 품질 평가 및 장애 감지 구조를 마련했습니다.
+510
View File
@@ -0,0 +1,510 @@
# lolympus-agent Service and Evaluation Operations
이 문서는 `lolympus-agent`의 운영 흐름과 evaluation 파이프라인을 한 곳에서 보기 위한 runbook이다. 실시간 응답 경로, background worker, shadow evaluation, human review, calibration, closed-loop prompt experiment까지 포함한다.
## 1. 프로세스 구성
운영 프로세스는 크게 두 개다.
| 프로세스 | 엔트리포인트 | 역할 |
|---|---|---|
| agent | `src/main.ts` | NATS request/reply를 받아 실시간 온보딩 응답 생성 |
| worker | `src/workers/background.ts` | Redis Stream background job 처리, shadow eval, archive, drift, review routing |
PM2 기준으로는 `ecosystem.config.cjs`에서 agent와 worker를 함께 띄운다.
```bash
npm run pm2:dev
npm run pm2:test
npm run pm2:prod
```
개발 환경 단독 실행은 기존 스크립트를 사용한다.
```bash
npm run start:dev
```
## 2. Bootstrap 흐름
`src/main.ts`의 기동 순서는 다음과 같다.
1. `loadEnvironmentFromNodeEnv()`로 `env-vars/{NODE_ENV}.env` 로드
2. logger/tracing 초기화
3. NATS 연결
4. Garnet/Redis 연결
5. LLM endpoint와 provider key 구성
6. MongoDB 연결, 가능하면 room context 활성화
7. `Agent` 생성
8. `OnboardingSkill` 등록
9. `lolympus-agent.request` 구독 시작
중요한 점은 NATS가 가장 먼저 외부 TLS 연결을 시도한다는 것이다. 따라서 bootstrap fatal error가 `certificate has expired`이고 `✓ NATS connected` 로그가 없었다면 1순위 원인은 `NATS_ENDPOINT` 인증서 만료다.
## 3. 실시간 응답 흐름
본체는 NATS request/reply로 agent에 요청한다.
```text
lolympus-agent.request
-> Agent.handleRequest
-> OnboardingSkill.handle
-> AgentResponse
```
`OnboardingSkill.handle()` 내부 흐름:
1. Garnet에서 온보딩 세션 로드
2. user message와 trigger 기반 intent classify
3. session, trigger, intent로 `DerivedState` 생성
4. `shouldRespond=false`면 empty response 반환
5. `responseMode=template`이면 template fallback 응답
6. LLM 경로면 prompt build 후 orchestrator 실행
7. tier에 따라 planner/responder/critic/tool-loop 사용
8. validator로 응답 검증
9. 최종 응답 반환
10. blackboard 업데이트
11. shadow eval event를 background stream에 비동기 발행
실시간 사용자 응답은 9번에서 끝난다. Evaluation은 11번 이후 worker가 비동기로 처리한다.
## 4. Prompt와 Tool 경로
Prompt는 `src/skills/onboarding/prompts/builder.ts`가 만든다.
기본 layer:
- persona
- policy
- state
- examples
- context
`PROMPT_VARIANT_ID`가 설정되면 `src/eval/proposals/{variantId}.json` manifest를 읽어 prompt layer diff를 적용한다. 운영 반영은 env로 variant를 선택하는 방식이며, proposal 생성과 tournament는 별도 CLI에서 수행한다.
Tool loop는 `responseMode=llm-with-tools`일 때 작동한다. Built-in tool은 `src/tools/builtins/*`에 있다.
## 5. Background Worker 흐름
Worker는 `lolympus-agent:background` Redis Stream을 consumer group `bg-worker`로 읽는다.
| Job type | 처리 |
|---|---|
| `shadow-eval` | 실시간 응답을 rule/LLM/process 기준으로 평가 |
| `summarize` | 오래된 대화 일부를 요약해 summary slot에 저장 |
Worker는 pending job을 복구하고, delivery count가 한도를 넘으면 DLQ로 이동한다.
| Stream | 용도 |
|---|---|
| `lolympus-agent:background` | background job queue |
| `lolympus-agent:background:dlq` | 반복 실패 job 저장 |
## 6. Shadow Evaluation 흐름
실시간 응답이 만들어지면 `ShadowEvalBus`가 background stream에 `shadow-eval` job을 발행한다.
Worker는 이 job을 받아 다음을 수행한다.
1. validator 재실행
2. LLM judge 실행
3. process trace가 있으면 process judge 실행
4. latency, tier, intent, phase, judge 결과 저장
결과는 Redis Stream에 저장된다.
```text
lolympus-agent:eval:results
```
이 Stream이 이후 evaluation 운영의 원천 데이터다.
## 7. 주기 Evaluation 작업
Worker는 일정 간격으로 eval result를 가공한다.
| 작업 | 기본 주기 | 결과 |
|---|---:|---|
| aggregation | `EVAL_AGG_TICK_MS` 5분 | slice별 Redis Hash metric |
| archive | `EVAL_ARCHIVE_TICK_MS` 1시간 | MongoDB `eval_archive` |
| drift detection | `EVAL_DRIFT_TICK_MS` 24시간 | `eval-drift` alert |
| promotion | `EVAL_PROMOTE_TICK_MS` 24시간 | golden candidate jsonl |
| review routing | `EVAL_REVIEW_TICK_MS` 5분 | human review queue |
| review label archive | archive tick과 함께 | MongoDB `eval_review_labels` |
Slice 정의:
```text
tier × intent × phase
```
예:
```text
0:photo-question:photo-pending
1:discord-question:step1-completed
```
## 8. Redis Key Schema
주요 Redis/Garnet key:
| Key | Type | 용도 |
|---|---|---|
| `lolympus-agent:background` | Stream | worker job queue |
| `lolympus-agent:background:dlq` | Stream | worker dead-letter queue |
| `lolympus-agent:eval:results` | Stream | shadow eval 결과 |
| `lolympus-agent:eval:baseline` | String | 최근 안정 baseline report |
| `lolympus-agent:eval:agg:{tier}:{intent}:{phase}` | Hash | slice별 count/score/latency/process metric |
| `lolympus-agent:eval:agg:cursor` | String | aggregation cursor |
| `lolympus-agent:eval:archive:cursor` | String | eval archive cursor |
| `lolympus-agent:eval:review:queue` | Stream | human review 대기 큐 |
| `lolympus-agent:eval:review:labeled` | Stream | human review label |
| `lolympus-agent:eval:review:cursor` | String | review routing cursor |
| `lolympus-agent:eval:review:dedupe:{evalStreamId}` | String | 동일 eval result 중복 라우팅 방지 |
| `lolympus-agent:eval:review:label-archive:cursor` | String | review label archive cursor |
| `lolympus-agent:alert:dedupe:{kind}` | String | alert rate limit |
## 9. MongoDB Collections
| Collection | 생성/사용 모듈 | 용도 |
|---|---|---|
| `eval_archive` | `src/eval/archive.ts` | shadow eval 결과 장기 보관 |
| `eval_review_labels` | `src/eval/review/label-archive.ts` | 사람 라벨 장기 보관 |
| `eval_tournaments` | `src/eval/loop/tournament.ts` | prompt variant tournament 결과 |
`eval_archive`는 `evaluatedAt` 기준 TTL index를 가진다. 기본 보관 기간은 `EVAL_ARCHIVE_TTL_DAYS=30`이다.
## 10. Human Review 흐름
Review routing은 eval result 중 사람이 봐야 할 케이스를 큐에 넣는다.
조건:
- LLM judge overall이 낮음
- validator와 LLM judge가 불일치
- validator soft-warn
- rare slice
큐:
```text
lolympus-agent:eval:review:queue
```
라벨링:
```bash
npm run eval:review -- --limit=20
```
특정 reason만 보기:
```bash
npm run eval:review -- --reason=low-score --limit=10
```
stale pending item을 다시 큐에 넣기:
```bash
npm run eval:review -- --reset-pending
```
세션 라벨을 JSONL로 저장:
```bash
npm run eval:review -- --limit=20 --export-labeled=eval-reports/review-labels.jsonl
```
라벨 결과는 `lolympus-agent:eval:review:labeled` Stream에 쌓이고 archive tick에서 `eval_review_labels`로 영속화된다.
## 11. Calibration 흐름
Calibration은 사람 점수와 LLM judge 점수의 상관을 계산한다.
```bash
npm run eval:calibrate
```
CI나 수동 gate로 쓰려면:
```bash
npm run eval:calibrate -- --check
```
`pairs < 10`이면 표본이 부족하므로 경고만 출력하고 실패 처리하지 않는다. 충분한 라벨이 쌓이면 `EVAL_CALIBRATION_MIN_CORR` 기준으로 LLM judge 신뢰도를 감시한다.
## 12. Report와 Promotion
Slice별 약한 영역 확인:
```bash
npm run eval:report -- --worst=20
```
최근 7일 대신 다른 window:
```bash
npm run eval:report -- --worst=20 --since=24h
npm run eval:report -- --top=20 --since=30d
```
Golden candidate 확인:
```bash
npm run eval:promote -- --dry-run
```
Candidate 파일에 추가:
```bash
npm run eval:promote
```
기본 출력:
```text
src/eval/golden/onboarding.candidate.jsonl
```
Promotion 우선순위:
1. human-labeled fail
2. low-score
3. rule/LLM disagree
4. rare-slice
candidate는 바로 golden으로 승격되는 것이 아니라 사람이 직접 검토해 `onboarding.jsonl`로 옮긴다.
## 13. Closed Loop 흐름
Phase 9의 closed loop는 prompt/tool 개선안을 만들고 tournament로 비교하는 흐름이다.
### 13.1 Proposal 생성
약한 slice를 지정한다.
```bash
npm run eval:propose -- --slice=tier=1,intent=photo-question,phase=photo-pending
```
archive case 수가 부족해도 강제로 실행하려면:
```bash
npm run eval:propose -- --slice=tier=1,intent=photo-question,phase=photo-pending --force
```
결과는 git-tracked proposal manifest로 저장된다.
```text
src/eval/proposals/{variantId}.json
```
### 13.2 Tournament 실행
Control과 variant를 비교한다.
```bash
npm run eval:tournament -- --variants=control,<variantId>
```
특정 archive case만 지정:
```bash
npm run eval:tournament -- --variants=control,<variantId> --case-ids=1-0,2-0
```
결과 조회:
```bash
npm run eval:tournament-results
npm run eval:tournament-results -- --variant=<variantId>
```
Tournament는 A/B 위치 편향을 줄이기 위해 variant 순서를 바꾼 match도 실행하고 ELO를 갱신한다. 결과는 MongoDB `eval_tournaments`에 저장된다.
### 13.3 운영 반영
운영 prompt에 variant를 반영하려면 env를 설정한다.
```env
PROMPT_VARIANT_ID=<variantId>
```
반영 전에는 반드시 다음을 확인한다.
```bash
npm run typecheck
npm run lint
npm run build
npm test
npm run eval -- --skip-llm-judge --no-publish-report
```
Variant 적용은 자동 머지가 아니다. 사람이 tournament 결과와 sample match를 보고 결정한다.
## 14. Eval CLI 요약
| 명령 | 용도 |
|---|---|
| `npm run eval` | golden set 실행 |
| `npm run eval:capture` | MongoDB events에서 golden scaffold 추출 |
| `npm run eval:baseline` | 안정 baseline 저장 |
| `npm run eval:report` | archive slice report 출력 |
| `npm run eval:promote` | golden candidate 추출 |
| `npm run eval:review` | human review CLI |
| `npm run eval:calibrate` | 사람/LLM judge calibration |
| `npm run eval:propose` | prompt/tool improvement proposal 생성 |
| `npm run eval:tournament` | prompt variant A/B tournament 실행 |
| `npm run eval:tournament-results` | tournament 결과 조회 |
## 15. 주요 Env
| Env | 기본값 | 용도 |
|---|---:|---|
| `EVAL_STREAM_MAXLEN` | 10000 | eval results Stream maxlen |
| `EVAL_AGG_TICK_MS` | 300000 | aggregation tick |
| `EVAL_AGG_TTL_SEC` | 604800 | slice metric TTL |
| `EVAL_ARCHIVE_TICK_MS` | 3600000 | archive tick |
| `EVAL_ARCHIVE_TTL_DAYS` | 30 | archive TTL days |
| `EVAL_DRIFT_TICK_MS` | 86400000 | drift tick |
| `EVAL_PROMOTE_TICK_MS` | 86400000 | promotion tick |
| `EVAL_REVIEW_TICK_MS` | 300000 | review routing tick |
| `EVAL_REVIEW_QUEUE_MAXLEN` | 500 | review queue maxlen |
| `EVAL_REVIEW_LABEL_MAXLEN` | 5000 | review label Stream maxlen |
| `EVAL_REVIEW_DEDUPE_TTL_SEC` | 604800 | review dedupe TTL |
| `EVAL_CALIBRATION_MIN_CORR` | 0.5 | calibration gate |
| `REVIEWER_ID` | git user.email | human review 식별자 |
| `LLM_PROPOSE_MODEL` | `LLM_JUDGE_MODEL` | proposal model |
| `LLM_PROPOSE_MAX_TOKENS` | 1024 | proposal max tokens |
| `EVAL_TOURNAMENT_MAX_MATCHES` | 50 | tournament match cap |
| `EVAL_TOURNAMENT_MIN_CASES` | 10 | proposal 최소 archive cases |
| `PROMPT_VARIANT_ID` | unset | 운영 prompt variant 선택 |
## 16. Alert와 Monitoring
Worker는 다음 종류의 alert를 보낼 수 있다.
| Alert kind | 의미 |
|---|---|
| `latency` | 최근 shadow eval latency p95 초과 |
| `llm-error-rate` | LLM judge 실패율 상승 |
| `eval-score-drop` | baseline 대비 eval score 하락 |
| `eval-drift` | 24h vs 7d slice score drift |
| `endpoint-down` | LLM circuit breaker open |
| `archive-stalled` | MongoDB archive 연속 실패 |
Alert는 `lolympus-agent.alert` NATS subject로 발행되고, dedupe key로 rate limit된다.
## 17. 장애 확인 Runbook
### 17.1 Bootstrap에서 `certificate has expired`
증상:
```text
[Bootstrap] Fatal startup error
message: certificate has expired
code: CERT_HAS_EXPIRED
```
`src/main.ts` 기준 NATS 연결이 첫 외부 TLS 연결이다. `✓ NATS connected` 로그가 없으면 `NATS_ENDPOINT` 인증서가 1순위 원인이다.
확인:
```bash
node --trace-warnings --import tsx src/main.ts
```
인증서 날짜 확인:
```bash
openssl s_client -connect <host>:<port> -servername <host> </dev/null 2>/dev/null \
| openssl x509 -noout -dates -subject
```
`✓ NATS connected` 이후 같은 오류가 나면 다음 후보는 Garnet 또는 MongoDB다.
### 17.2 LLM endpoint warning
증상:
```text
[LLM] Endpoint unavailable via circuit breaker
[LLM] Request error
[LLM] All endpoints failed
```
확인 순서:
1. `CLI_PROXY_API_URLS`
2. `OPENROUTER_API_KEY`, `OPENROUTER_API_URL`
3. `AGENT_LLM_API_URLS`
4. `LLAMA_SERVER_API_URL`
5. provider별 API key
`npm run eval -- --skip-llm-judge`는 LLM judge를 생략하지만 실제 응답 생성 LLM은 여전히 호출될 수 있다. endpoint가 모두 실패하면 template/fallback 경로로 통과할 수 있다.
### 17.3 MongoDB 미설정
Worker가 다음과 비슷한 로그를 남긴다.
```text
MongoDB connection string missing; eval archive/drift/promote disabled
```
영향:
- 실시간 응답은 가능
- shadow eval result Stream은 쌓임
- archive, drift, promote, calibration, tournament는 제한됨
필요 env:
```env
MONGODB_CONNECTION_STRING=
MONGODB_PROJECT_ID=
```
### 17.4 Review queue가 밀림
확인:
```bash
npm run eval:review -- --limit=5
```
stale pending item 정리:
```bash
npm run eval:review -- --reset-pending
```
같은 케이스가 반복 라우팅되면 dedupe TTL과 cursor를 확인한다.
```text
lolympus-agent:eval:review:cursor
lolympus-agent:eval:review:dedupe:{evalStreamId}
```
### 17.5 Archive stalled
`archive-stalled` alert가 뜨면 MongoDB 연결과 index 생성 권한을 확인한다.
관련 cursor:
```text
lolympus-agent:eval:archive:cursor
lolympus-agent:eval:review:label-archive:cursor
```
cursor가 진행되지 않으면 worker가 다음 tick에서 재시도한다.
## 18. 운영 원칙
- 실시간 응답 경로는 가능한 짧게 유지한다.
- Evaluation은 Redis Stream을 통해 비동기로 처리한다.
- Golden set 승격은 사람이 직접 결정한다.
- Prompt variant 운영 반영은 tournament 결과와 eval smoke를 본 뒤 결정한다.
- 자동 rollback이나 자동 merge는 하지 않는다.
- 모든 timestamp는 UTC ISO-8601을 사용한다.