Add evaluation operations and reporting
This commit is contained in:
1 parent
60f33b8f4b
commit
a900016be4
60 files changed
+8689
-142
No files matched your search
@@ -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을 구현해 운영 트래픽 기반 품질 평가 및 장애 감지 구조를 마련했습니다.
|
||||
Reference in new issue
Block a user