Refactor skill definitions into SSOT structure
Move onboarding intents, prompt data, and tools behind skill-local sources. Register skills through factories and add a moderation skill PoC.
This commit is contained in:
1 parent
b1cc27f6ad
commit
fb189330da
29 files changed
+993
-494
No files matched your search
@@ -0,0 +1,13 @@
|
||||
---
|
||||
name: moderation
|
||||
description: 커뮤니티 규칙 문의와 위반 안내를 담당하는 PoC skill.
|
||||
version: 1
|
||||
intents: [greeting, rule-question, violation-report, appeal, off-topic]
|
||||
triggers: [user-message]
|
||||
tools: []
|
||||
resources: {}
|
||||
trustTier: T4
|
||||
---
|
||||
|
||||
커뮤니티 규칙 질문에는 알려진 범위 안에서 짧고 명확하게 답한다.
|
||||
위반 제보나 이의 제기는 운영진 확인이 필요하다고 안내한다.
|
||||
@@ -0,0 +1,9 @@
|
||||
import type { Skill } from "@skills/skill";
|
||||
import type { SkillDeps } from "@skills/skill-factory";
|
||||
import { ModerationSkill } from "./skill.js";
|
||||
|
||||
export { ModerationSkill } from "./skill.js";
|
||||
|
||||
export function createModerationSkill(deps: SkillDeps): Skill {
|
||||
return new ModerationSkill(deps.llmClient);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
interface ModerationIntentDefinition {
|
||||
confidence: number;
|
||||
regex: readonly RegExp[];
|
||||
}
|
||||
|
||||
export const MODERATION_INTENT_TABLE = {
|
||||
greeting: {
|
||||
confidence: 0.9,
|
||||
regex: [/^(안녕|하이|반갑|문의드립니다)/u],
|
||||
},
|
||||
"rule-question": {
|
||||
confidence: 0.92,
|
||||
regex: [/(규칙|룰|금지|가능|해도\s*돼|하면\s*안|제재|경고)/u],
|
||||
},
|
||||
"violation-report": {
|
||||
confidence: 0.94,
|
||||
regex: [/(신고|제보|위반|욕설|분쟁|비매너|문제\s*있|처리해)/u],
|
||||
},
|
||||
appeal: {
|
||||
confidence: 0.94,
|
||||
regex: [/(이의|소명|억울|해제|풀어|재검토|항소|정지)/u],
|
||||
},
|
||||
"off-topic": {
|
||||
confidence: 0,
|
||||
regex: [],
|
||||
},
|
||||
} as const satisfies Record<string, ModerationIntentDefinition>;
|
||||
|
||||
export type ModerationIntentKind = keyof typeof MODERATION_INTENT_TABLE;
|
||||
export type ModerationIntent = { kind: ModerationIntentKind };
|
||||
|
||||
export function classifyModerationIntent(message: string): {
|
||||
confidence: number;
|
||||
intent: ModerationIntent;
|
||||
} {
|
||||
const trimmed = message.trim();
|
||||
if (!trimmed) {
|
||||
return {
|
||||
confidence: 0,
|
||||
intent: { kind: "off-topic" },
|
||||
};
|
||||
}
|
||||
|
||||
for (const [kind, definition] of Object.entries(MODERATION_INTENT_TABLE) as
|
||||
Array<[ModerationIntentKind, ModerationIntentDefinition]>) {
|
||||
if (kind === "off-topic") {
|
||||
continue;
|
||||
}
|
||||
if (definition.regex.some((pattern) => pattern.test(trimmed))) {
|
||||
return {
|
||||
confidence: definition.confidence,
|
||||
intent: { kind },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
confidence: 0.4,
|
||||
intent: { kind: "off-topic" },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { ModerationIntentKind } from "./intents.js";
|
||||
|
||||
export const MODERATION_PROMPT_DATA = {
|
||||
persona: [
|
||||
"너는 롤림푸스 커뮤니티의 규칙 안내를 돕는 moderation assistant야.",
|
||||
"운영진 판단이 필요한 사안은 단정하지 않고 운영진 확인이 필요하다고 안내해.",
|
||||
],
|
||||
policy: {
|
||||
base: [
|
||||
"- 답변은 1~3문장으로 짧게 한다.",
|
||||
"- 처벌, 제재, 신고 처리 결과를 확정해서 말하지 않는다.",
|
||||
"- 개인정보, 계정 정보, 특정 이용자 평가를 요구하면 운영진 확인으로 돌린다.",
|
||||
],
|
||||
perIntent: {
|
||||
appeal: [
|
||||
"- 이의 제기나 소명은 운영진에게 상황과 근거를 정리해 전달하라고 안내한다.",
|
||||
],
|
||||
greeting: ["- 짧게 인사하고 규칙 문의를 도울 수 있다고 말한다."],
|
||||
"off-topic": ['- 규칙/운영 문의가 아니면 "[NO_RESPONSE]"만 출력한다.'],
|
||||
"rule-question": [
|
||||
"- 규칙 질문은 알려진 원칙만 답하고, 애매하면 운영진 확인이 필요하다고 말한다.",
|
||||
],
|
||||
"violation-report": [
|
||||
"- 위반 제보는 증거와 상황을 정리해 운영진에게 전달하라고 안내한다.",
|
||||
],
|
||||
} satisfies Record<ModerationIntentKind, readonly string[]>,
|
||||
},
|
||||
examples: {
|
||||
appeal: [
|
||||
{
|
||||
user: "제재가 억울하면 어떻게 해요?",
|
||||
assistant: "상황과 근거를 정리해서 운영진에게 소명해 주세요. 제가 결과를 확정하진 못해요.",
|
||||
},
|
||||
],
|
||||
greeting: [
|
||||
{
|
||||
user: "규칙 문의 좀 할게요",
|
||||
assistant: "네, 규칙 관련해서 궁금한 점을 짧게 알려주세요.",
|
||||
},
|
||||
],
|
||||
"off-topic": [
|
||||
{
|
||||
user: "오늘 게임 할 사람?",
|
||||
assistant: "[NO_RESPONSE]",
|
||||
},
|
||||
],
|
||||
"rule-question": [
|
||||
{
|
||||
user: "욕설하면 경고인가요?",
|
||||
assistant: "욕설이나 분쟁 유발은 제재 대상이 될 수 있어요. 구체적인 판단은 운영진 확인이 필요합니다.",
|
||||
},
|
||||
],
|
||||
"violation-report": [
|
||||
{
|
||||
user: "누가 규칙 위반한 것 같아요",
|
||||
assistant: "관련 메시지와 상황을 정리해서 운영진에게 제보해 주세요. 처리는 운영진이 확인해야 해요.",
|
||||
},
|
||||
],
|
||||
} satisfies Record<
|
||||
ModerationIntentKind,
|
||||
Array<{ assistant: string; user: string }>
|
||||
>,
|
||||
} as const;
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import type {
|
||||
AgentRequest,
|
||||
AgentResponse,
|
||||
ConversationMessage,
|
||||
} from "@agent/types";
|
||||
import type { LlmClient } from "@llm/llm-client";
|
||||
import type { ChatMessage } from "@llm/types";
|
||||
import type { Skill } from "@skills/skill";
|
||||
import { classifyModerationIntent, type ModerationIntent } from "./intents.js";
|
||||
import { MODERATION_PROMPT_DATA } from "./prompt-data.js";
|
||||
import { createModerationToolRegistry } from "./tools.js";
|
||||
|
||||
function formatHistory(history: ConversationMessage[]): string {
|
||||
if (history.length === 0) {
|
||||
return "(none)";
|
||||
}
|
||||
|
||||
return history
|
||||
.slice(-5)
|
||||
.map((message) => `${message.role}: ${message.content}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function formatExamples(intent: ModerationIntent): string {
|
||||
return MODERATION_PROMPT_DATA.examples[intent.kind]
|
||||
.slice(0, 2)
|
||||
.map((example) => `user: ${example.user}\nassistant: ${example.assistant}`)
|
||||
.join("\n\n");
|
||||
}
|
||||
|
||||
function buildMessages(
|
||||
request: AgentRequest,
|
||||
history: ConversationMessage[],
|
||||
intent: ModerationIntent,
|
||||
): ChatMessage[] {
|
||||
const policies = [
|
||||
...MODERATION_PROMPT_DATA.policy.base,
|
||||
...MODERATION_PROMPT_DATA.policy.perIntent[intent.kind],
|
||||
];
|
||||
|
||||
return [
|
||||
{
|
||||
role: "system",
|
||||
content: [
|
||||
...MODERATION_PROMPT_DATA.persona,
|
||||
"",
|
||||
"[policy]",
|
||||
policies.join("\n"),
|
||||
"",
|
||||
"[intent]",
|
||||
intent.kind,
|
||||
"",
|
||||
"[examples]",
|
||||
formatExamples(intent),
|
||||
].join("\n"),
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
"[history]",
|
||||
formatHistory(history),
|
||||
"",
|
||||
"[message]",
|
||||
request.userMessage?.trim() || "",
|
||||
].join("\n"),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
function templateForIntent(intent: ModerationIntent): string {
|
||||
switch (intent.kind) {
|
||||
case "appeal":
|
||||
return "이의 제기나 소명은 상황과 근거를 정리해서 운영진에게 전달해 주세요.";
|
||||
case "greeting":
|
||||
return "네, 규칙 관련해서 궁금한 점을 알려주세요.";
|
||||
case "rule-question":
|
||||
return "규칙 관련 사안은 알려진 원칙 안에서 안내할 수 있고, 애매한 경우 운영진 확인이 필요해요.";
|
||||
case "violation-report":
|
||||
return "위반 제보는 관련 메시지와 상황을 정리해서 운영진에게 전달해 주세요.";
|
||||
case "off-topic":
|
||||
return "[NO_RESPONSE]";
|
||||
}
|
||||
}
|
||||
|
||||
export class ModerationSkill implements Skill {
|
||||
readonly name = "moderation";
|
||||
private readonly toolRegistry = createModerationToolRegistry();
|
||||
|
||||
constructor(private readonly llmClient: LlmClient) {}
|
||||
|
||||
canHandle(request: AgentRequest): boolean {
|
||||
return request.skill === this.name;
|
||||
}
|
||||
|
||||
async handle(
|
||||
request: AgentRequest,
|
||||
conversationHistory: ConversationMessage[],
|
||||
): Promise<AgentResponse> {
|
||||
const classified = classifyModerationIntent(request.userMessage ?? "");
|
||||
const metadata = {
|
||||
intent: classified.intent.kind,
|
||||
toolCount: this.toolRegistry.list().length,
|
||||
};
|
||||
|
||||
if (classified.intent.kind === "off-topic") {
|
||||
return {
|
||||
confidence: classified.confidence,
|
||||
metadata,
|
||||
requestId: request.requestId,
|
||||
source: "template",
|
||||
text: templateForIntent(classified.intent),
|
||||
};
|
||||
}
|
||||
|
||||
const response = await this.llmClient.chatCompletion(
|
||||
buildMessages(request, conversationHistory, classified.intent),
|
||||
{
|
||||
maxTokens: 192,
|
||||
temperature: 0.2,
|
||||
tier: 0,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
confidence: classified.confidence,
|
||||
metadata,
|
||||
requestId: request.requestId,
|
||||
source: response ? "llm" : "template",
|
||||
text: response?.content.trim() || templateForIntent(classified.intent),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ToolRegistry } from "@tools/registry";
|
||||
|
||||
export function createModerationToolRegistry(): ToolRegistry {
|
||||
return new ToolRegistry();
|
||||
}
|
||||
@@ -1,5 +1,19 @@
|
||||
import type { Skill } from "@skills/skill";
|
||||
import type { SkillDeps } from "@skills/skill-factory";
|
||||
import { OnboardingSkill } from "./skill.js";
|
||||
|
||||
export { OnboardingSkill } from "./skill.js";
|
||||
export type {
|
||||
OnboardingSession,
|
||||
OnboardingStatus,
|
||||
} from "./types.js";
|
||||
|
||||
export function createOnboardingSkill(deps: SkillDeps): Skill {
|
||||
return new OnboardingSkill(
|
||||
deps.garnetClient,
|
||||
deps.llmClient,
|
||||
deps.roomContextService,
|
||||
deps.shadowEvalBus,
|
||||
deps.natsClient,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,252 @@
|
||||
import {
|
||||
detectLightweightIntent,
|
||||
isRemainingStatusQuestion,
|
||||
shouldSkipMessage,
|
||||
} from "./message-filter.js";
|
||||
|
||||
type IntentMatcher = (input: { lower: string; trimmed: string }) => boolean;
|
||||
type IntentRegexRule = RegExp | { confidence?: number; pattern: RegExp };
|
||||
|
||||
interface OnboardingIntentDefinition {
|
||||
confidence: number;
|
||||
keywords: readonly string[];
|
||||
llm: boolean;
|
||||
match?: IntentMatcher | undefined;
|
||||
regex?: readonly IntentRegexRule[] | undefined;
|
||||
triggers?: readonly string[] | undefined;
|
||||
}
|
||||
|
||||
export const ONBOARDING_INTENT_TABLE = {
|
||||
greeting: {
|
||||
confidence: 0.99,
|
||||
keywords: ["반갑", "환영", "어서 오세요"],
|
||||
llm: true,
|
||||
match: ({ trimmed }) => detectLightweightIntent(trimmed) === "greeting",
|
||||
},
|
||||
acknowledgement: {
|
||||
confidence: 0.99,
|
||||
keywords: ["네", "좋아요", "천천히"],
|
||||
llm: true,
|
||||
match: ({ trimmed }) =>
|
||||
detectLightweightIntent(trimmed) === "acknowledgement",
|
||||
triggers: ["completed"],
|
||||
},
|
||||
"status-question": {
|
||||
confidence: 0.96,
|
||||
keywords: ["남았", "완료", "아직", "끝"],
|
||||
llm: true,
|
||||
match: ({ trimmed }) => isRemainingStatusQuestion(trimmed),
|
||||
triggers: ["progress-update", "timeout-warning"],
|
||||
},
|
||||
"help-where": {
|
||||
confidence: 0.9,
|
||||
keywords: [
|
||||
"오른쪽 상단",
|
||||
"커버 보기",
|
||||
"프로필",
|
||||
"본인인증방",
|
||||
"구인방",
|
||||
"채팅방",
|
||||
],
|
||||
llm: true,
|
||||
regex: [/(어디|위치|어딨어|찾겠|찾을)/u],
|
||||
},
|
||||
"help-how": {
|
||||
confidence: 0.72,
|
||||
keywords: [
|
||||
"하트",
|
||||
"닉네임",
|
||||
"스크린샷",
|
||||
"형식",
|
||||
"본인인증방",
|
||||
"구인방",
|
||||
"운영진",
|
||||
],
|
||||
llm: true,
|
||||
regex: [
|
||||
{
|
||||
confidence: 0.9,
|
||||
pattern: /(어떻게|방법|어케|어케해|어케 함|어케함)/u,
|
||||
},
|
||||
{
|
||||
confidence: 0.94,
|
||||
pattern: /(본인인증\s*방|본인인증방|구인\s*방|구인방)/u,
|
||||
},
|
||||
/(가입|등록|절차|도움|도와|뭐해야|뭐 해야|해야 돼|해야해|무엇을 해야)/u,
|
||||
],
|
||||
},
|
||||
"discord-verify-question": {
|
||||
confidence: 0.96,
|
||||
keywords: ["디스코드", "확인", "닉네임"],
|
||||
llm: true,
|
||||
match: ({ lower, trimmed }) => {
|
||||
const mentionsDiscord = /(디스코드|디코|discord)/u.test(lower);
|
||||
const asksDiscordVerification =
|
||||
/(확인|조회|찾아|검색|검사|바뀌|변경|닉변|맞(?:아|나요)?|됐(?:나|나요)?|완료됐(?:나|나요)?)/u.test(
|
||||
trimmed,
|
||||
);
|
||||
const reportsDiscordNicknameCompletion =
|
||||
/(닉네임|닉변|프로필\s*닉네임|서버\s*닉네임)/u.test(trimmed) &&
|
||||
/(완료했(?:어|어요|습니다)?|끝냈(?:어|어요|습니다)?|설정했(?:어|어요|습니다)?|바꿨(?:어|어요|습니다)?|변경했(?:어|어요|습니다)?|다\s*했(?:어|어요|습니다)?|해놨(?:어|어요|습니다)?|해뒀(?:어|어요|습니다)?|적용됐(?:어|어요|습니다)?)/u.test(
|
||||
trimmed,
|
||||
);
|
||||
return (
|
||||
mentionsDiscord &&
|
||||
(asksDiscordVerification || reportsDiscordNicknameCompletion)
|
||||
);
|
||||
},
|
||||
},
|
||||
"discord-question": {
|
||||
confidence: 0.95,
|
||||
keywords: ["디스코드", "주민신청", "프로필", "권한", "설정"],
|
||||
llm: true,
|
||||
match: ({ lower }) => /(디스코드|디코|discord)/u.test(lower),
|
||||
regex: [
|
||||
{
|
||||
confidence: 0.94,
|
||||
pattern: /(주민신청\s*채널|주민신청채널|서버\s*프로필)/u,
|
||||
},
|
||||
],
|
||||
},
|
||||
"age-question": {
|
||||
confidence: 0.93,
|
||||
keywords: ["27", "가입", "가능"],
|
||||
llm: true,
|
||||
regex: [/(나이|연령|27세|나이\s*제한|몇\s*살|몇살)/u],
|
||||
},
|
||||
"nickname-question": {
|
||||
confidence: 0.9,
|
||||
keywords: ["닉네임", "형식", "티어", "/"],
|
||||
llm: true,
|
||||
regex: [/(닉네임|닉변|형식|이름)/u],
|
||||
triggers: ["nickname-invalid"],
|
||||
},
|
||||
"photo-question": {
|
||||
confidence: 0.88,
|
||||
keywords: ["하트", "스크린샷", "프로필", "커버 보기"],
|
||||
llm: true,
|
||||
regex: [/(하트|인증|사진|스크린샷|스샷|프로필)/u],
|
||||
triggers: ["photo-failed"],
|
||||
},
|
||||
"off-topic-to-other": {
|
||||
confidence: 0.99,
|
||||
keywords: [],
|
||||
llm: true,
|
||||
regex: [/^@\S+/u],
|
||||
},
|
||||
chitchat: {
|
||||
confidence: 0.95,
|
||||
keywords: [],
|
||||
llm: true,
|
||||
match: ({ trimmed }) => shouldSkipMessage(trimmed),
|
||||
},
|
||||
unknown: {
|
||||
confidence: 0,
|
||||
keywords: [],
|
||||
llm: true,
|
||||
},
|
||||
} as const satisfies Record<string, OnboardingIntentDefinition>;
|
||||
|
||||
export type IntentKind = keyof typeof ONBOARDING_INTENT_TABLE;
|
||||
export type Intent = { kind: IntentKind };
|
||||
|
||||
export const UNKNOWN_INTENT_KIND = "unknown" satisfies IntentKind;
|
||||
|
||||
export interface ClassifiedIntentInfo {
|
||||
confidence: number;
|
||||
intent: Intent;
|
||||
source: "regex";
|
||||
}
|
||||
|
||||
export const EXPECTED_KEYWORDS = Object.fromEntries(
|
||||
Object.entries(ONBOARDING_INTENT_TABLE).map(([kind, definition]) => [
|
||||
kind,
|
||||
[...definition.keywords],
|
||||
]),
|
||||
) as Record<IntentKind, string[]>;
|
||||
|
||||
export const LLM_INTENT_ALLOWLIST = Object.entries(ONBOARDING_INTENT_TABLE)
|
||||
.filter(([, definition]) => definition.llm)
|
||||
.map(([kind]) => kind) as IntentKind[];
|
||||
|
||||
export function createIntent(kind: IntentKind): Intent {
|
||||
return { kind };
|
||||
}
|
||||
|
||||
export function parseOnboardingIntent(raw: unknown): Intent {
|
||||
return typeof raw === "string" && raw in ONBOARDING_INTENT_TABLE
|
||||
? createIntent(raw as IntentKind)
|
||||
: createIntent(UNKNOWN_INTENT_KIND);
|
||||
}
|
||||
|
||||
export function mapTriggerToIntent(trigger: string): Intent | null {
|
||||
for (const [kind, definition] of Object.entries(ONBOARDING_INTENT_TABLE) as
|
||||
Array<[IntentKind, OnboardingIntentDefinition]>) {
|
||||
if (definition.triggers?.includes(trigger)) {
|
||||
return createIntent(kind);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function matchRegexRule(
|
||||
rule: IntentRegexRule,
|
||||
trimmed: string,
|
||||
): { confidence: number | null; matched: boolean } {
|
||||
if (rule instanceof RegExp) {
|
||||
return {
|
||||
confidence: null,
|
||||
matched: rule.test(trimmed),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
confidence: rule.confidence ?? null,
|
||||
matched: rule.pattern.test(trimmed),
|
||||
};
|
||||
}
|
||||
|
||||
export function classifyByRegex(userMessage: string): ClassifiedIntentInfo {
|
||||
const trimmed = userMessage.trim();
|
||||
const lower = trimmed.toLowerCase();
|
||||
|
||||
if (!trimmed) {
|
||||
return {
|
||||
confidence: 0,
|
||||
intent: createIntent(UNKNOWN_INTENT_KIND),
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
for (const [kind, definition] of Object.entries(ONBOARDING_INTENT_TABLE) as
|
||||
Array<[IntentKind, OnboardingIntentDefinition]>) {
|
||||
if (kind === UNKNOWN_INTENT_KIND) {
|
||||
continue;
|
||||
}
|
||||
if (definition.match?.({ lower, trimmed })) {
|
||||
return {
|
||||
confidence: definition.confidence,
|
||||
intent: createIntent(kind),
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
for (const rule of definition.regex ?? []) {
|
||||
const result = matchRegexRule(rule, trimmed);
|
||||
if (!result.matched) {
|
||||
continue;
|
||||
}
|
||||
return {
|
||||
confidence: result.confidence ?? definition.confidence,
|
||||
intent: createIntent(kind),
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
confidence: 0,
|
||||
intent: createIntent(UNKNOWN_INTENT_KIND),
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,256 @@
|
||||
import type { IntentKind } from "./intents.js";
|
||||
import {
|
||||
DISCORD_NICKNAME_FORMAT_EXAMPLE,
|
||||
HEART_RULE_TEXT,
|
||||
KAKAOTALK_NICKNAME_FORMAT_EXAMPLE,
|
||||
MIN_AGE,
|
||||
TIER_CODES_TEXT,
|
||||
} from "./constants.js";
|
||||
import type { Example } from "./types.js";
|
||||
import type { OnboardingPhase } from "./state/onboarding-state.js";
|
||||
|
||||
export const ONBOARDING_PROMPT_DATA = {
|
||||
sections: {
|
||||
blackboard: {
|
||||
flaggedIssues: "- flaggedIssues",
|
||||
lastIntent: "- lastIntent",
|
||||
openQuestions: "- openQuestions",
|
||||
recentNicknameAttempts: "- recentNicknameAttempts",
|
||||
},
|
||||
context: {
|
||||
blackboard: "[메모]",
|
||||
history: "[최근 대화]",
|
||||
room: "[방 분위기]",
|
||||
summary: "[최근 요약]",
|
||||
userMemory: "[유저 메모리]",
|
||||
},
|
||||
examples: {
|
||||
assistant: "응답",
|
||||
empty: "(예시 없음)",
|
||||
title: "[응답 예시]",
|
||||
user: "유저",
|
||||
},
|
||||
state: {
|
||||
deadline: "- deadline(KST)",
|
||||
discordProfileMessage: "- 디스코드 프로필 메시지",
|
||||
discordProfileNickname: "- 디스코드 프로필 닉네임",
|
||||
extendedTracking: "- extendedTracking",
|
||||
identityRoom: "- 카카오톡 본인인증방 입장",
|
||||
nickname: "- 카카오톡 닉네임",
|
||||
phase: "- phase",
|
||||
photo: "- 방 하트 인증",
|
||||
recruitingRoom: "- 카카오톡 구인방 입장",
|
||||
remaining: "- remaining",
|
||||
step1: "- step1(카카오톡)",
|
||||
title: "[현재 유저 상태]",
|
||||
},
|
||||
},
|
||||
persona: [
|
||||
"너는 롤림푸스(lolympus) 카카오톡 오픈채팅에서 새내기 등록을 도와주는 친절한 선배야.",
|
||||
"처음 온 멤버가 편안하게 등록을 마칠 수 있도록 자연스럽고 정확하게 안내해줘.",
|
||||
"",
|
||||
"[롤림푸스 규칙]",
|
||||
`- 가입 가능 연령은 ${MIN_AGE}세 이상이야.`,
|
||||
"- 새내기 등록 1단계는 카카오톡 닉네임 변경과 방 하트 인증이야.",
|
||||
"- 1단계 완료 후에는 카카오톡 본인인증방/구인방 입장과 디스코드 서버 프로필 설정, 디스코드 주민신청 채널 메시지 남기기가 남아 있을 수 있어.",
|
||||
`- 카카오톡 닉네임 형식은 닉네임/출생 연도 두 자리/성별/티어야. 예: ${KAKAOTALK_NICKNAME_FORMAT_EXAMPLE}`,
|
||||
`- 디스코드 서버 닉네임 형식은 닉네임#태그/출생 연도 두 자리/티어야. 카카오톡 형식과 달리 성별은 빼고 태그(#)가 들어가. 예: ${DISCORD_NICKNAME_FORMAT_EXAMPLE}`,
|
||||
"- 디스코드 관련 질문(디코 닉변, 서버 프로필 등)에는 절대 카카오톡 형식(성별 포함)을 예시로 들지 마. 반드시 디스코드 형식만 안내해.",
|
||||
`- 성별은 남 또는 여, 티어 코드는 ${TIER_CODES_TEXT} 중 하나야.`,
|
||||
`- 방 하트 인증은 ${HEART_RULE_TEXT}`,
|
||||
"- 세션에 디스코드 관련 미완료 항목이 있으면 전체 등록은 아직 완료가 아니야.",
|
||||
"- 디스코드 안내는 카카오톡 1단계가 완료된 뒤에만 해줘.",
|
||||
].join("\n"),
|
||||
policy: {
|
||||
base: [
|
||||
"[답변 원칙]",
|
||||
"- 마지막 메시지에서 직접 물은 내용에만 정확히 답해.",
|
||||
"- 사용자가 요청하지 않은 다음 단계, 방법, 위치, 예시는 먼저 붙이지 마.",
|
||||
"- 마크다운 문법, 링크, URL은 쓰지 마.",
|
||||
'- 온보딩과 무관한 잡담이거나 다른 사람에게 하는 말이면 "[NO_RESPONSE]"만 출력해.',
|
||||
],
|
||||
default: ["- 질문 범위를 넘어서 먼저 설명하지 마."],
|
||||
perIntent: {
|
||||
acknowledgement: ["- 짧은 확인이나 마무리만 1문장으로 답해."],
|
||||
"age-question": ["- 나이 제한만 간단히 답해."],
|
||||
chitchat: [],
|
||||
"discord-question": [
|
||||
"- 디스코드 질문에만 답해. 카카오톡 1단계 전이라면 먼저 닉네임 변경과 하트 인증이 필요하다고 알려줘.",
|
||||
"- 주민신청 채널이나 서버 프로필처럼 디스코드 공간/설정을 묻는 질문에는 용도와 역할을 자연스럽게 설명해.",
|
||||
],
|
||||
"discord-verify-question": [
|
||||
"- 확인되지 않았으면 확인되지 않았다고만 답하고, 추측해서 단정하지 마.",
|
||||
`- 디스코드 닉네임 형식은 카카오톡과 달라. 반드시 이름#태그/출생 연도 두 자리/티어 형식(성별 없음, 태그 포함)으로 안내하고, 카카오톡 형식(이름/연도/성별/티어)을 절대 제시하지 마. 예시는 ${DISCORD_NICKNAME_FORMAT_EXAMPLE} 하나만 사용해.`,
|
||||
"- 디스코드 닉네임이 규칙에 맞지 않으면 위 형식과 예시를 1개만 들고 형식에 맞게 변경해 달라고 안내해.",
|
||||
"- 사용자가 묻지 않은 디스코드 절차나 다음 단계는 먼저 붙이지 마.",
|
||||
],
|
||||
greeting: ["- 짧은 인사만 1문장으로 답해."],
|
||||
"help-how": [
|
||||
"- 어떤 절차가 남아있는지 묻는 질문에는 완료된 건 말하지 말고 남은 절차만 짧게 말해.",
|
||||
"- 사용자가 물은 한 가지 절차나 방의 의미/방법만 답해.",
|
||||
"- 본인인증방이나 구인방이 무엇인지 묻는 질문에는 간단히 답하고, 본인인증방/구인방에 들어가서 어떻게 해야 하는지 묻는 경우 공지사항/안내메시지를 참조하라고 답해..",
|
||||
],
|
||||
"help-where": [
|
||||
"- 위치나 경로만 답하고, 요청하지 않은 다음 단계는 붙이지 마.",
|
||||
],
|
||||
"nickname-question": [
|
||||
"- 닉네임 형식 또는 오류 원인만 답하고 다른 절차는 언급하지 마.",
|
||||
],
|
||||
"off-topic-to-other": [],
|
||||
"photo-question": ["- 하트 인증에 대해서만 답하고 다른 절차는 언급하지 마."],
|
||||
"status-question": [
|
||||
"- 완료된 것은 빼고 남은 절차만 간단하게 답해.",
|
||||
"- 방법 설명, 위치 설명, 예시는 넣지 마.",
|
||||
],
|
||||
unknown: [],
|
||||
} satisfies Record<IntentKind, readonly string[]>,
|
||||
},
|
||||
examples: {
|
||||
acknowledgement: [
|
||||
{
|
||||
user: "넵 확인했어요",
|
||||
assistant: "네, 편하게 진행해 보시면 돼요.",
|
||||
},
|
||||
{
|
||||
user: "감사합니다",
|
||||
assistant: "좋아요! 천천히 진행해 주세요.",
|
||||
},
|
||||
],
|
||||
"age-question": [
|
||||
{
|
||||
user: "나이 제한 있나요?",
|
||||
assistant: "롤림푸스는 27세 이상만 가입이 가능해요.",
|
||||
},
|
||||
],
|
||||
chitchat: [
|
||||
{
|
||||
user: "오늘 날씨 좋네요",
|
||||
assistant: "[NO_RESPONSE]",
|
||||
},
|
||||
],
|
||||
"discord-question": [
|
||||
{
|
||||
user: "디스코드는 언제 들어가요?",
|
||||
assistant:
|
||||
"카카오톡 닉네임 변경과 하트 인증을 완료하셨다면, 이제 카카오톡 본인인증방/구인방 입장과 디스코드 서버 프로필 설정을 진행하시면 돼요.",
|
||||
},
|
||||
],
|
||||
"discord-verify-question": [
|
||||
{
|
||||
user: "디코 닉변 확인해줘",
|
||||
assistant: "아직 디스코드 닉네임 변경은 확인되지 않았어요.",
|
||||
},
|
||||
{
|
||||
user: "디스코드 프로필 닉네임 설정 완료했어요",
|
||||
assistant:
|
||||
"디스코드 닉네임을 확인해봤는데 아직 올바른 형식으로 확인되지는 않았어요. 디스코드 서버 닉네임은 이름#태그/출생 연도/티어 형식이에요. 예: 할리#프렌치불독/88/D",
|
||||
},
|
||||
{
|
||||
user: "디스코드 닉네임 바꿨어요",
|
||||
assistant:
|
||||
"디스코드 닉네임이 아직 이름#태그/출생 연도/티어 형식으로 확인되지 않아요. 예: 할리#프렌치불독/88/D처럼 태그를 포함해서 설정해 주세요.",
|
||||
},
|
||||
],
|
||||
greeting: [
|
||||
{
|
||||
user: "안녕하세요!",
|
||||
assistant: "어서오세요!",
|
||||
},
|
||||
{
|
||||
user: "반갑습니다",
|
||||
assistant: "안녕하세요~",
|
||||
},
|
||||
],
|
||||
"help-how": [
|
||||
{
|
||||
user: "하트 인증은 어떻게 해요?",
|
||||
assistant:
|
||||
'채팅방 오른쪽 상단 메뉴 버튼에서 "커버 보기"로 들어가 하트를 클릭하시고, 편집 없이 원본 스크린샷을 올려주시면 돼요.',
|
||||
},
|
||||
{
|
||||
user: "본인인증 방은 뭐에요?",
|
||||
assistant:
|
||||
"본인 계정을 사용하고 계신지 확인하는 절차가 있어요! 본인인증방은 담당 운영진이 확인 작업을 도와드리는 별도의 채팅방이에요.",
|
||||
},
|
||||
{
|
||||
user: "닉네임 형식 예시 알려줘",
|
||||
assistant:
|
||||
"닉네임은 이름/출생 연도 두 자리/성별/티어 형식이에요. 예를 들면 면정학/89/남/D처럼 쓰시면 돼요.",
|
||||
},
|
||||
],
|
||||
"help-where": [
|
||||
{
|
||||
user: "하트 어디서 바꿔요?",
|
||||
assistant:
|
||||
'채팅방 오른쪽 상단 메뉴 버튼을 누르면 "커버 보기"가 보여요. 거기서 프로필과 하트를 확인하실 수 있어요.',
|
||||
},
|
||||
],
|
||||
"nickname-question": [
|
||||
{
|
||||
user: "닉네임이 왜 안 돼요?",
|
||||
assistant: "티어는 한 글자 코드로 넣어야 해요. 예를 들면 D처럼 바꿔주시면 돼요.",
|
||||
},
|
||||
{
|
||||
user: "닉네임 형식이 뭐예요?",
|
||||
assistant: "닉네임은 이름/출생 연도 두 자리/성별/티어 형식으로 입력해 주시면 돼요.",
|
||||
},
|
||||
],
|
||||
"off-topic-to-other": [
|
||||
{
|
||||
user: "@프리리 이거 확인해줘",
|
||||
assistant: "[NO_RESPONSE]",
|
||||
},
|
||||
],
|
||||
"photo-question": [
|
||||
{
|
||||
user: "하트 인증이 뭐예요?",
|
||||
assistant:
|
||||
"채팅방 프로필에서 하트를 빨간색으로 바꾼 뒤, 그 화면이 보이게 원본 스크린샷을 보내주시면 돼요.",
|
||||
},
|
||||
],
|
||||
"status-question": [
|
||||
{
|
||||
user: "이제 뭐 남았지?",
|
||||
assistant:
|
||||
"이제 디스코드 서버 프로필 닉네임 변경하시고 주민신청 채널에 메시지만 남겨주시면 돼요!",
|
||||
},
|
||||
{
|
||||
user: "이제 뭐 해야 할까요?",
|
||||
assistant: "카톡 닉네임 변경해 주시고 방 하트 인증해 주시면 됩니다!",
|
||||
},
|
||||
],
|
||||
unknown: [
|
||||
{
|
||||
user: "가입은 어떻게 하나요?",
|
||||
assistant: "톡 게시글의 공지를 참고하셔서 닉네임 변경과 하트 인증을 진행해 주세요!",
|
||||
},
|
||||
],
|
||||
} satisfies Record<IntentKind, Example[]>,
|
||||
toolPolicy: {
|
||||
byIntent: {
|
||||
"age-question": [
|
||||
"- 디스코드 일반 안내나 규칙 질문이면 lookup-community-rule 도구를 사용해 정확한 규칙만 답해.",
|
||||
"- 사용자가 디스코드 닉네임이나 프로필 설정을 끝냈다고 말하거나 반영 여부를 묻는다면 verify-discord-nickname 도구를 먼저 사용해 직접 확인해.",
|
||||
].join("\n"),
|
||||
"discord-question": [
|
||||
"- 디스코드 일반 안내나 규칙 질문이면 lookup-community-rule 도구를 사용해 정확한 규칙만 답해.",
|
||||
"- 사용자가 디스코드 닉네임이나 프로필 설정을 끝냈다고 말하거나 반영 여부를 묻는다면 verify-discord-nickname 도구를 먼저 사용해 직접 확인해.",
|
||||
].join("\n"),
|
||||
"discord-verify-question":
|
||||
"- 디스코드 닉네임 확인 요청은 verify-discord-nickname 도구를 먼저 사용하고, 조회 결과만 짧게 답해.",
|
||||
"help-where":
|
||||
"- 위치 안내가 모호할 때만 get-room-context 도구를 고려하고, 기본적으로는 절차 위치만 답해.",
|
||||
"status-question":
|
||||
"- 진행 상태 질문은 check-onboarding-progress 도구를 우선 사용하고, 상태만 짧게 답해.",
|
||||
} satisfies Partial<Record<IntentKind, string>>,
|
||||
byIntentPhase: {
|
||||
"nickname-question:nickname-rejected":
|
||||
"- 닉네임 후보나 현재 닉네임을 설명할 때는 validate-nickname 도구를 먼저 사용한 뒤, 틀린 부분만 짚어.",
|
||||
} satisfies Partial<Record<`${IntentKind}:${OnboardingPhase["kind"]}`, string>>,
|
||||
byPhase: {
|
||||
"deadline-near": "- 마감이 가까운 상태에서는 남은 절차만 우선순위로 짧게 답해.",
|
||||
} satisfies Partial<Record<OnboardingPhase["kind"], string>>,
|
||||
default:
|
||||
"- 도구가 꼭 필요하지 않다면 호출하지 말고, 지금 질문에 대한 답만 간결하게 해.",
|
||||
},
|
||||
} as const;
|
||||
@@ -109,7 +109,7 @@ describe("PromptBuilder", () => {
|
||||
expect(messages[0]?.content).toContain("[ACTIVE_SKILL:onboarding]");
|
||||
expect(messages[0]?.content).toContain("카카오톡 오픈채팅 새내기 등록");
|
||||
expect(messages[0]?.content).toContain("[현재 유저 상태]");
|
||||
expect(messages[0]?.content.length ?? 0).toBeLessThan(basePrompt.length * 0.65);
|
||||
expect(messages[0]?.content.length ?? 0).toBeLessThan(basePrompt.length * 0.75);
|
||||
});
|
||||
|
||||
it("injects user memory and adaptive examples when enabled", () => {
|
||||
|
||||
@@ -1,124 +1,3 @@
|
||||
import type { Intent } from '../state/onboarding-state.js';
|
||||
import type { Example } from '../types.js';
|
||||
import { ONBOARDING_PROMPT_DATA } from "../prompt-data.js";
|
||||
|
||||
export const EXAMPLES_BY_INTENT: Record<Intent['kind'], Example[]> = {
|
||||
greeting: [
|
||||
{
|
||||
user: '안녕하세요!',
|
||||
assistant: '어서오세요!',
|
||||
},
|
||||
{
|
||||
user: '반갑습니다',
|
||||
assistant: '안녕하세요~',
|
||||
},
|
||||
],
|
||||
acknowledgement: [
|
||||
{
|
||||
user: '넵 확인했어요',
|
||||
assistant: '네, 편하게 진행해 보시면 돼요.',
|
||||
},
|
||||
{
|
||||
user: '감사합니다',
|
||||
assistant: '좋아요! 천천히 진행해 주세요.',
|
||||
},
|
||||
],
|
||||
'status-question': [
|
||||
{
|
||||
user: '이제 뭐 남았지?',
|
||||
assistant:
|
||||
'이제 디스코드 서버 프로필 닉네임 변경하시고 주민신청 채널에 메시지만 남겨주시면 돼요!',
|
||||
},
|
||||
{
|
||||
user: '이제 뭐 해야 할까요?',
|
||||
assistant: '카톡 닉네임 변경해 주시고 방 하트 인증해 주시면 됩니다!',
|
||||
},
|
||||
],
|
||||
'help-how': [
|
||||
{
|
||||
user: '하트 인증은 어떻게 해요?',
|
||||
assistant:
|
||||
'채팅방 오른쪽 상단 메뉴 버튼에서 "커버 보기"로 들어가 하트를 클릭하시고, 편집 없이 원본 스크린샷을 올려주시면 돼요.',
|
||||
},
|
||||
{
|
||||
user: '본인인증 방은 뭐에요?',
|
||||
assistant:
|
||||
'본인 계정을 사용하고 계신지 확인하는 절차가 있어요! 본인인증방은 담당 운영진이 확인 작업을 도와드리는 별도의 채팅방이에요.',
|
||||
},
|
||||
{
|
||||
user: '닉네임 형식 예시 알려줘',
|
||||
assistant:
|
||||
'닉네임은 이름/출생 연도 두 자리/성별/티어 형식이에요. 예를 들면 면정학/89/남/D처럼 쓰시면 돼요.',
|
||||
},
|
||||
],
|
||||
'help-where': [
|
||||
{
|
||||
user: '하트 어디서 바꿔요?',
|
||||
assistant:
|
||||
'채팅방 오른쪽 상단 메뉴 버튼을 누르면 "커버 보기"가 보여요. 거기서 프로필과 하트를 확인하실 수 있어요.',
|
||||
},
|
||||
],
|
||||
'nickname-question': [
|
||||
{
|
||||
user: '닉네임이 왜 안 돼요?',
|
||||
assistant: '티어는 한 글자 코드로 넣어야 해요. 예를 들면 D처럼 바꿔주시면 돼요.',
|
||||
},
|
||||
{
|
||||
user: '닉네임 형식이 뭐예요?',
|
||||
assistant: '닉네임은 이름/출생 연도 두 자리/성별/티어 형식으로 입력해 주시면 돼요.',
|
||||
},
|
||||
],
|
||||
'photo-question': [
|
||||
{
|
||||
user: '하트 인증이 뭐예요?',
|
||||
assistant:
|
||||
'채팅방 프로필에서 하트를 빨간색으로 바꾼 뒤, 그 화면이 보이게 원본 스크린샷을 보내주시면 돼요.',
|
||||
},
|
||||
],
|
||||
'discord-question': [
|
||||
{
|
||||
user: '디스코드는 언제 들어가요?',
|
||||
assistant:
|
||||
'카카오톡 닉네임 변경과 하트 인증을 완료하셨다면, 이제 카카오톡 본인인증방/구인방 입장과 디스코드 서버 프로필 설정을 진행하시면 돼요.',
|
||||
},
|
||||
],
|
||||
'discord-verify-question': [
|
||||
{
|
||||
user: '디코 닉변 확인해줘',
|
||||
assistant: '아직 디스코드 닉네임 변경은 확인되지 않았어요.',
|
||||
},
|
||||
{
|
||||
user: '디스코드 프로필 닉네임 설정 완료했어요',
|
||||
assistant:
|
||||
'디스코드 닉네임을 확인해봤는데 아직 올바른 형식으로 확인되지는 않았어요. 디스코드 서버 닉네임은 이름#태그/출생 연도/티어 형식이에요. 예: 할리#프렌치불독/88/D',
|
||||
},
|
||||
{
|
||||
user: '디스코드 닉네임 바꿨어요',
|
||||
assistant:
|
||||
'디스코드 닉네임이 아직 이름#태그/출생 연도/티어 형식으로 확인되지 않아요. 예: 할리#프렌치불독/88/D처럼 태그를 포함해서 설정해 주세요.',
|
||||
},
|
||||
],
|
||||
'age-question': [
|
||||
{
|
||||
user: '나이 제한 있나요?',
|
||||
assistant: '롤림푸스는 27세 이상만 가입이 가능해요.',
|
||||
},
|
||||
],
|
||||
chitchat: [
|
||||
{
|
||||
user: '오늘 날씨 좋네요',
|
||||
assistant: '[NO_RESPONSE]',
|
||||
},
|
||||
],
|
||||
'off-topic-to-other': [
|
||||
{
|
||||
user: '@프리리 이거 확인해줘',
|
||||
assistant: '[NO_RESPONSE]',
|
||||
},
|
||||
],
|
||||
unknown: [
|
||||
{
|
||||
user: '가입은 어떻게 하나요?',
|
||||
assistant: '톡 게시글의 공지를 참고하셔서 닉네임 변경과 하트 인증을 진행해 주세요!',
|
||||
},
|
||||
],
|
||||
};
|
||||
export const EXAMPLES_BY_INTENT = ONBOARDING_PROMPT_DATA.examples;
|
||||
@@ -3,20 +3,13 @@ import type { RoomMessage } from '@room/types';
|
||||
import type { DerivedState, Intent } from '../state/onboarding-state.js';
|
||||
import type { Blackboard, Example, OnboardingSession, PromptContext } from '../types.js';
|
||||
import type { UserProfile } from '../state/user-memory.js';
|
||||
import {
|
||||
HEART_RULE_TEXT,
|
||||
MIN_AGE,
|
||||
KAKAOTALK_NICKNAME_FORMAT_EXAMPLE,
|
||||
DISCORD_NICKNAME_FORMAT_EXAMPLE,
|
||||
TIER_CODES_TEXT,
|
||||
} from '../constants.js';
|
||||
import {
|
||||
formatRemainingSteps,
|
||||
getRemainingSteps,
|
||||
hasExtendedOnboardingTracking,
|
||||
isStep1Completed,
|
||||
} from '../state/progress.js';
|
||||
import { EXAMPLES_BY_INTENT } from './examples.js';
|
||||
import { ONBOARDING_PROMPT_DATA } from '../prompt-data.js';
|
||||
|
||||
function formatKstTimestamp(value: string | undefined): string {
|
||||
if (!value) {
|
||||
@@ -81,6 +74,7 @@ function formatRoomMessages(roomContext?: RoomMessage[]): string {
|
||||
}
|
||||
|
||||
function formatBlackboard(blackboard: Blackboard): string {
|
||||
const labels = ONBOARDING_PROMPT_DATA.sections.blackboard;
|
||||
const openQuestions =
|
||||
blackboard.openQuestions.length > 0 ? blackboard.openQuestions.join(', ') : '(없음)';
|
||||
const flaggedIssues =
|
||||
@@ -91,15 +85,16 @@ function formatBlackboard(blackboard: Blackboard): string {
|
||||
: '(없음)';
|
||||
|
||||
return [
|
||||
`- lastIntent: ${blackboard.lastIntent ?? '(없음)'}`,
|
||||
`- openQuestions: ${openQuestions}`,
|
||||
`- flaggedIssues: ${flaggedIssues}`,
|
||||
`- recentNicknameAttempts: ${nicknameAttempts}`,
|
||||
`${labels.lastIntent}: ${blackboard.lastIntent ?? '(없음)'}`,
|
||||
`${labels.openQuestions}: ${openQuestions}`,
|
||||
`${labels.flaggedIssues}: ${flaggedIssues}`,
|
||||
`${labels.recentNicknameAttempts}: ${nicknameAttempts}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
function formatExample(example: Example): string {
|
||||
return `유저: ${example.user}\n응답: ${example.assistant}`;
|
||||
const labels = ONBOARDING_PROMPT_DATA.sections.examples;
|
||||
return `${labels.user}: ${example.user}\n${labels.assistant}: ${example.assistant}`;
|
||||
}
|
||||
|
||||
function formatUserProfile(profile: UserProfile | null | undefined): string {
|
||||
@@ -129,86 +124,17 @@ function formatUserProfile(profile: UserProfile | null | undefined): string {
|
||||
}
|
||||
|
||||
export function personaLayer(): string {
|
||||
return `너는 롤림푸스(lolympus) 카카오톡 오픈채팅에서 새내기 등록을 도와주는 친절한 선배야.
|
||||
처음 온 멤버가 편안하게 등록을 마칠 수 있도록 자연스럽고 정확하게 안내해줘.
|
||||
|
||||
[롤림푸스 규칙]
|
||||
- 가입 가능 연령은 ${MIN_AGE}세 이상이야.
|
||||
- 새내기 등록 1단계는 카카오톡 닉네임 변경과 방 하트 인증이야.
|
||||
- 1단계 완료 후에는 카카오톡 본인인증방/구인방 입장과 디스코드 서버 프로필 설정, 디스코드 주민신청 채널 메시지 남기기가 남아 있을 수 있어.
|
||||
- 카카오톡 닉네임 형식은 닉네임/출생 연도 두 자리/성별/티어야. 예: ${KAKAOTALK_NICKNAME_FORMAT_EXAMPLE}
|
||||
- 디스코드 서버 닉네임 형식은 닉네임#태그/출생 연도 두 자리/티어야. 카카오톡 형식과 달리 성별은 빼고 태그(#)가 들어가. 예: ${DISCORD_NICKNAME_FORMAT_EXAMPLE}
|
||||
- 디스코드 관련 질문(디코 닉변, 서버 프로필 등)에는 절대 카카오톡 형식(성별 포함)을 예시로 들지 마. 반드시 디스코드 형식만 안내해.
|
||||
- 성별은 남 또는 여, 티어 코드는 ${TIER_CODES_TEXT} 중 하나야.
|
||||
- 방 하트 인증은 ${HEART_RULE_TEXT}
|
||||
- 세션에 디스코드 관련 미완료 항목이 있으면 전체 등록은 아직 완료가 아니야.
|
||||
- 디스코드 안내는 카카오톡 1단계가 완료된 뒤에만 해줘.`;
|
||||
return ONBOARDING_PROMPT_DATA.persona;
|
||||
}
|
||||
|
||||
export function policyLayer(intent: Intent, options?: { toolPolicy?: string | undefined }): string {
|
||||
const lines = [
|
||||
'[답변 원칙]',
|
||||
'- 마지막 메시지에서 직접 물은 내용에만 정확히 답해.',
|
||||
'- 사용자가 요청하지 않은 다음 단계, 방법, 위치, 예시는 먼저 붙이지 마.',
|
||||
'- 마크다운 문법, 링크, URL은 쓰지 마.',
|
||||
'- 온보딩과 무관한 잡담이거나 다른 사람에게 하는 말이면 "[NO_RESPONSE]"만 출력해.',
|
||||
...ONBOARDING_PROMPT_DATA.policy.base,
|
||||
...(ONBOARDING_PROMPT_DATA.policy.perIntent[intent.kind].length > 0
|
||||
? ONBOARDING_PROMPT_DATA.policy.perIntent[intent.kind]
|
||||
: ONBOARDING_PROMPT_DATA.policy.default),
|
||||
];
|
||||
|
||||
switch (intent.kind) {
|
||||
case 'greeting':
|
||||
lines.push('- 짧은 인사만 1문장으로 답해.');
|
||||
break;
|
||||
case 'acknowledgement':
|
||||
lines.push('- 짧은 확인이나 마무리만 1문장으로 답해.');
|
||||
break;
|
||||
case 'status-question':
|
||||
lines.push('- 완료된 것은 빼고 남은 절차만 간단하게 답해.');
|
||||
lines.push('- 방법 설명, 위치 설명, 예시는 넣지 마.');
|
||||
break;
|
||||
case 'help-where':
|
||||
lines.push('- 위치나 경로만 답하고, 요청하지 않은 다음 단계는 붙이지 마.');
|
||||
break;
|
||||
case 'help-how':
|
||||
lines.push(
|
||||
'- 어떤 절차가 남아있는지 묻는 질문에는 완료된 건 말하지 말고 남은 절차만 짧게 말해.',
|
||||
);
|
||||
lines.push('- 사용자가 물은 한 가지 절차나 방의 의미/방법만 답해.');
|
||||
lines.push(
|
||||
'- 본인인증방이나 구인방이 무엇인지 묻는 질문에는 간단히 답하고, 본인인증방/구인방에 들어가서 어떻게 해야 하는지 묻는 경우 공지사항/안내메시지를 참조하라고 답해..',
|
||||
);
|
||||
break;
|
||||
case 'nickname-question':
|
||||
lines.push('- 닉네임 형식 또는 오류 원인만 답하고 다른 절차는 언급하지 마.');
|
||||
break;
|
||||
case 'photo-question':
|
||||
lines.push('- 하트 인증에 대해서만 답하고 다른 절차는 언급하지 마.');
|
||||
break;
|
||||
case 'discord-question':
|
||||
lines.push(
|
||||
'- 디스코드 질문에만 답해. 카카오톡 1단계 전이라면 먼저 닉네임 변경과 하트 인증이 필요하다고 알려줘.',
|
||||
);
|
||||
lines.push(
|
||||
'- 주민신청 채널이나 서버 프로필처럼 디스코드 공간/설정을 묻는 질문에는 용도와 역할을 자연스럽게 설명해.',
|
||||
);
|
||||
break;
|
||||
case 'discord-verify-question':
|
||||
lines.push('- 확인되지 않았으면 확인되지 않았다고만 답하고, 추측해서 단정하지 마.');
|
||||
lines.push(
|
||||
`- 디스코드 닉네임 형식은 카카오톡과 달라. 반드시 이름#태그/출생 연도 두 자리/티어 형식(성별 없음, 태그 포함)으로 안내하고, 카카오톡 형식(이름/연도/성별/티어)을 절대 제시하지 마. 예시는 ${DISCORD_NICKNAME_FORMAT_EXAMPLE} 하나만 사용해.`,
|
||||
);
|
||||
lines.push(
|
||||
'- 디스코드 닉네임이 규칙에 맞지 않으면 위 형식과 예시를 1개만 들고 형식에 맞게 변경해 달라고 안내해.',
|
||||
);
|
||||
lines.push('- 사용자가 묻지 않은 디스코드 절차나 다음 단계는 먼저 붙이지 마.');
|
||||
break;
|
||||
case 'age-question':
|
||||
lines.push('- 나이 제한만 간단히 답해.');
|
||||
break;
|
||||
default:
|
||||
lines.push('- 질문 범위를 넘어서 먼저 설명하지 마.');
|
||||
break;
|
||||
}
|
||||
|
||||
if (options?.toolPolicy) {
|
||||
lines.push(options.toolPolicy);
|
||||
}
|
||||
@@ -218,20 +144,21 @@ export function policyLayer(intent: Intent, options?: { toolPolicy?: string | un
|
||||
|
||||
export function stateLayer(session: OnboardingSession | null, derived: DerivedState): string {
|
||||
const remaining = getRemainingSteps(session);
|
||||
const labels = ONBOARDING_PROMPT_DATA.sections.state;
|
||||
|
||||
return [
|
||||
'[현재 유저 상태]',
|
||||
`- phase: ${derived.phase.kind}`,
|
||||
`- step1(카카오톡): ${session ? (isStep1Completed(session) ? '완료' : '미완료') : '미완료'}`,
|
||||
`- 카카오톡 닉네임: ${formatNicknameStatus(session)}`,
|
||||
`- 방 하트 인증: ${formatPhotoStatus(session)}`,
|
||||
`- 카카오톡 본인인증방 입장: ${formatOptionalVerificationStatus(session?.identityRoomJoined)}`,
|
||||
`- 카카오톡 구인방 입장: ${formatOptionalVerificationStatus(session?.recruitingRoomJoined)}`,
|
||||
`- 디스코드 프로필 닉네임: ${formatOptionalVerificationStatus(session?.discordProfileNicknameVerified)}`,
|
||||
`- 디스코드 프로필 메시지: ${formatOptionalVerificationStatus(session?.discordProfileMessageVerified)}`,
|
||||
`- extendedTracking: ${hasExtendedOnboardingTracking(session) ? 'on' : 'off'}`,
|
||||
`- remaining: ${remaining.length > 0 ? formatRemainingSteps(remaining) : '없음'}`,
|
||||
`- deadline(KST): ${formatKstTimestamp(session?.deadlineAt)}`,
|
||||
labels.title,
|
||||
`${labels.phase}: ${derived.phase.kind}`,
|
||||
`${labels.step1}: ${session ? (isStep1Completed(session) ? '완료' : '미완료') : '미완료'}`,
|
||||
`${labels.nickname}: ${formatNicknameStatus(session)}`,
|
||||
`${labels.photo}: ${formatPhotoStatus(session)}`,
|
||||
`${labels.identityRoom}: ${formatOptionalVerificationStatus(session?.identityRoomJoined)}`,
|
||||
`${labels.recruitingRoom}: ${formatOptionalVerificationStatus(session?.recruitingRoomJoined)}`,
|
||||
`${labels.discordProfileNickname}: ${formatOptionalVerificationStatus(session?.discordProfileNicknameVerified)}`,
|
||||
`${labels.discordProfileMessage}: ${formatOptionalVerificationStatus(session?.discordProfileMessageVerified)}`,
|
||||
`${labels.extendedTracking}: ${hasExtendedOnboardingTracking(session) ? 'on' : 'off'}`,
|
||||
`${labels.remaining}: ${remaining.length > 0 ? formatRemainingSteps(remaining) : '없음'}`,
|
||||
`${labels.deadline}: ${formatKstTimestamp(session?.deadlineAt)}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
@@ -243,29 +170,34 @@ export function examplesLayer(
|
||||
},
|
||||
): string {
|
||||
const count = options?.count ?? 3;
|
||||
const examples = options?.examples ?? EXAMPLES_BY_INTENT[intent.kind].slice(0, count);
|
||||
const rendered = examples.length > 0 ? examples.map(formatExample).join('\n\n') : '(예시 없음)';
|
||||
const examples = options?.examples ?? ONBOARDING_PROMPT_DATA.examples[intent.kind].slice(0, count);
|
||||
const rendered =
|
||||
examples.length > 0
|
||||
? examples.map(formatExample).join('\n\n')
|
||||
: ONBOARDING_PROMPT_DATA.sections.examples.empty;
|
||||
|
||||
return `[응답 예시]\n${rendered}`;
|
||||
return `${ONBOARDING_PROMPT_DATA.sections.examples.title}\n${rendered}`;
|
||||
}
|
||||
|
||||
export function contextLayer(context: PromptContext): string {
|
||||
const labels = ONBOARDING_PROMPT_DATA.sections.context;
|
||||
|
||||
return [
|
||||
'[최근 요약]',
|
||||
labels.summary,
|
||||
context.summary ?? '(요약 없음)',
|
||||
'',
|
||||
'[최근 대화]',
|
||||
labels.history,
|
||||
formatHistory(context.conversationHistory),
|
||||
'',
|
||||
'[방 분위기]',
|
||||
labels.room,
|
||||
formatRoomMessages(context.roomContext),
|
||||
'',
|
||||
'[메모]',
|
||||
labels.blackboard,
|
||||
formatBlackboard(context.blackboard),
|
||||
...(context.userProfile
|
||||
? [
|
||||
'',
|
||||
'[유저 메모리]',
|
||||
labels.userMemory,
|
||||
formatUserProfile(context.userProfile),
|
||||
]
|
||||
: []),
|
||||
|
||||
@@ -1,35 +1,30 @@
|
||||
import type { Intent, OnboardingPhase } from "../state/onboarding-state.js";
|
||||
import { ONBOARDING_PROMPT_DATA } from "../prompt-data.js";
|
||||
|
||||
export function buildToolPolicy(
|
||||
intent: Intent["kind"],
|
||||
phase: OnboardingPhase["kind"],
|
||||
): string {
|
||||
if (intent === "nickname-question" && phase === "nickname-rejected") {
|
||||
return "- 닉네임 후보나 현재 닉네임을 설명할 때는 validate-nickname 도구를 먼저 사용한 뒤, 틀린 부분만 짚어.";
|
||||
const data = ONBOARDING_PROMPT_DATA.toolPolicy;
|
||||
const byIntentPhase: Partial<Record<`${Intent["kind"]}:${OnboardingPhase["kind"]}`, string>> =
|
||||
data.byIntentPhase;
|
||||
const byIntent: Partial<Record<Intent["kind"], string>> = data.byIntent;
|
||||
const byPhase: Partial<Record<OnboardingPhase["kind"], string>> =
|
||||
data.byPhase;
|
||||
const intentPhasePolicy = byIntentPhase[`${intent}:${phase}`];
|
||||
if (intentPhasePolicy) {
|
||||
return intentPhasePolicy;
|
||||
}
|
||||
|
||||
if (intent === "status-question") {
|
||||
return "- 진행 상태 질문은 check-onboarding-progress 도구를 우선 사용하고, 상태만 짧게 답해.";
|
||||
const intentPolicy = byIntent[intent];
|
||||
if (intentPolicy) {
|
||||
return intentPolicy;
|
||||
}
|
||||
|
||||
if (intent === "age-question" || intent === "discord-question") {
|
||||
return [
|
||||
"- 디스코드 일반 안내나 규칙 질문이면 lookup-community-rule 도구를 사용해 정확한 규칙만 답해.",
|
||||
"- 사용자가 디스코드 닉네임이나 프로필 설정을 끝냈다고 말하거나 반영 여부를 묻는다면 verify-discord-nickname 도구를 먼저 사용해 직접 확인해.",
|
||||
].join("\n");
|
||||
const phasePolicy = byPhase[phase];
|
||||
if (phasePolicy) {
|
||||
return phasePolicy;
|
||||
}
|
||||
|
||||
if (intent === "discord-verify-question") {
|
||||
return "- 디스코드 닉네임 확인 요청은 verify-discord-nickname 도구를 먼저 사용하고, 조회 결과만 짧게 답해.";
|
||||
}
|
||||
|
||||
if (intent === "help-where") {
|
||||
return "- 위치 안내가 모호할 때만 get-room-context 도구를 고려하고, 기본적으로는 절차 위치만 답해.";
|
||||
}
|
||||
|
||||
if (phase === "deadline-near") {
|
||||
return "- 마감이 가까운 상태에서는 남은 절차만 우선순위로 짧게 답해.";
|
||||
}
|
||||
|
||||
return "- 도구가 꼭 필요하지 않다면 호출하지 말고, 지금 질문에 대한 답만 간결하게 해.";
|
||||
return data.default;
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import type { Skill } from '@skills/skill';
|
||||
import { type ShadowEvalPublisher, ShadowEvalBus } from '@eval/shadow-bus';
|
||||
import { anonymizeProcessTrace } from '@eval/anonymize';
|
||||
import { meetsTrustTier } from '../../eval/governance/trust.js';
|
||||
import { createBuiltInToolRegistry } from '@tools/builtins/index';
|
||||
import { createOnboardingToolRegistry } from './tools.js';
|
||||
import type { ToolRegistry } from '@tools/registry';
|
||||
import type { Tool, ToolContext } from '@tools/tool';
|
||||
import { createToolSearchTool } from '@tools/tool-search';
|
||||
@@ -109,7 +109,7 @@ export class OnboardingSkill implements Skill {
|
||||
this.userMemoryStore = new UserMemoryStore(garnetClient);
|
||||
this.orchestrator = new OnboardingOrchestrator(llmClient);
|
||||
this.shadowEvalPublisher = shadowEvalPublisher ?? new ShadowEvalBus(garnetClient);
|
||||
this.toolRegistry = createBuiltInToolRegistry();
|
||||
this.toolRegistry = createOnboardingToolRegistry();
|
||||
this.tools = this.toolRegistry.list();
|
||||
}
|
||||
|
||||
|
||||
@@ -2,193 +2,33 @@ import { getClassifierMaxTokens } from "../../../config.js";
|
||||
import { withClassifierSpan } from "@obs/spans";
|
||||
import type { LlmClient } from "@llm/llm-client";
|
||||
import {
|
||||
detectLightweightIntent,
|
||||
isRemainingStatusQuestion,
|
||||
shouldSkipMessage,
|
||||
} from "../message-filter.js";
|
||||
import type { ClassifiedIntent, Intent } from "./onboarding-state.js";
|
||||
classifyByRegex,
|
||||
createIntent,
|
||||
LLM_INTENT_ALLOWLIST,
|
||||
mapTriggerToIntent,
|
||||
parseOnboardingIntent,
|
||||
UNKNOWN_INTENT_KIND,
|
||||
} from "../intents.js";
|
||||
import type { ClassifiedIntent } from "./onboarding-state.js";
|
||||
|
||||
interface ClassifierLlmShape {
|
||||
intent?: string;
|
||||
}
|
||||
|
||||
function intent(kind: Intent["kind"]): Intent {
|
||||
return { kind };
|
||||
}
|
||||
|
||||
function mapTriggerIntent(trigger: string): Intent | null {
|
||||
switch (trigger) {
|
||||
case "nickname-invalid":
|
||||
return intent("nickname-question");
|
||||
case "photo-failed":
|
||||
return intent("photo-question");
|
||||
case "progress-update":
|
||||
case "timeout-warning":
|
||||
return intent("status-question");
|
||||
case "completed":
|
||||
return intent("acknowledgement");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function classifyByRegex(userMessage: string): ClassifiedIntent {
|
||||
const trimmed = userMessage.trim();
|
||||
const lower = trimmed.toLowerCase();
|
||||
|
||||
if (!trimmed) {
|
||||
return { intent: intent("unknown"), confidence: 0, source: "regex" };
|
||||
}
|
||||
|
||||
if (/^@\S+/u.test(trimmed)) {
|
||||
return { intent: intent("off-topic-to-other"), confidence: 0.99, source: "regex" };
|
||||
}
|
||||
|
||||
if (shouldSkipMessage(trimmed)) {
|
||||
return { intent: intent("chitchat"), confidence: 0.95, source: "regex" };
|
||||
}
|
||||
|
||||
const lightweightIntent = detectLightweightIntent(trimmed);
|
||||
if (lightweightIntent === "greeting") {
|
||||
return { intent: intent("greeting"), confidence: 0.99, source: "regex" };
|
||||
}
|
||||
if (lightweightIntent === "acknowledgement") {
|
||||
return {
|
||||
intent: intent("acknowledgement"),
|
||||
confidence: 0.99,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (isRemainingStatusQuestion(trimmed)) {
|
||||
return {
|
||||
intent: intent("status-question"),
|
||||
confidence: 0.96,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (/(어디|위치|어딨어|찾겠|찾을)/u.test(trimmed)) {
|
||||
return { intent: intent("help-where"), confidence: 0.9, source: "regex" };
|
||||
}
|
||||
|
||||
if (/(어떻게|방법|어케|어케해|어케 함|어케함)/u.test(trimmed)) {
|
||||
return { intent: intent("help-how"), confidence: 0.9, source: "regex" };
|
||||
}
|
||||
|
||||
if (
|
||||
/(본인인증\s*방|본인인증방|구인\s*방|구인방)/u.test(trimmed)
|
||||
) {
|
||||
return {
|
||||
intent: intent("help-how"),
|
||||
confidence: 0.94,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
/(주민신청\s*채널|주민신청채널|서버\s*프로필)/u.test(
|
||||
trimmed,
|
||||
)
|
||||
) {
|
||||
return {
|
||||
intent: intent("discord-question"),
|
||||
confidence: 0.94,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
const mentionsDiscord = /(디스코드|디코|discord)/u.test(lower);
|
||||
const asksDiscordVerification =
|
||||
/(확인|조회|찾아|검색|검사|바뀌|변경|닉변|맞(?:아|나요)?|됐(?:나|나요)?|완료됐(?:나|나요)?)/u.test(
|
||||
trimmed,
|
||||
);
|
||||
const reportsDiscordNicknameCompletion =
|
||||
/(닉네임|닉변|프로필\s*닉네임|서버\s*닉네임)/u.test(trimmed) &&
|
||||
/(완료했(?:어|어요|습니다)?|끝냈(?:어|어요|습니다)?|설정했(?:어|어요|습니다)?|바꿨(?:어|어요|습니다)?|변경했(?:어|어요|습니다)?|다\s*했(?:어|어요|습니다)?|해놨(?:어|어요|습니다)?|해뒀(?:어|어요|습니다)?|적용됐(?:어|어요|습니다)?)/u.test(
|
||||
trimmed,
|
||||
);
|
||||
if (mentionsDiscord && (asksDiscordVerification || reportsDiscordNicknameCompletion)) {
|
||||
return {
|
||||
intent: intent("discord-verify-question"),
|
||||
confidence: 0.96,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (/(디스코드|디코|discord)/u.test(lower)) {
|
||||
return {
|
||||
intent: intent("discord-question"),
|
||||
confidence: 0.95,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (/(나이|연령|27세|나이\s*제한|몇\s*살|몇살)/u.test(trimmed)) {
|
||||
return { intent: intent("age-question"), confidence: 0.93, source: "regex" };
|
||||
}
|
||||
|
||||
if (/(닉네임|닉변|형식|이름)/u.test(trimmed)) {
|
||||
return {
|
||||
intent: intent("nickname-question"),
|
||||
confidence: 0.9,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (/(하트|인증|사진|스크린샷|스샷|프로필)/u.test(trimmed)) {
|
||||
return {
|
||||
intent: intent("photo-question"),
|
||||
confidence: 0.88,
|
||||
source: "regex",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
/(가입|등록|절차|도움|도와|뭐해야|뭐 해야|해야 돼|해야해|무엇을 해야)/u.test(trimmed)
|
||||
) {
|
||||
return { intent: intent("help-how"), confidence: 0.72, source: "regex" };
|
||||
}
|
||||
|
||||
return { intent: intent("unknown"), confidence: 0, source: "regex" };
|
||||
}
|
||||
|
||||
function parseIntent(raw: unknown): Intent {
|
||||
if (
|
||||
raw === "greeting" ||
|
||||
raw === "acknowledgement" ||
|
||||
raw === "status-question" ||
|
||||
raw === "help-how" ||
|
||||
raw === "help-where" ||
|
||||
raw === "nickname-question" ||
|
||||
raw === "photo-question" ||
|
||||
raw === "discord-question" ||
|
||||
raw === "discord-verify-question" ||
|
||||
raw === "age-question" ||
|
||||
raw === "chitchat" ||
|
||||
raw === "off-topic-to-other"
|
||||
) {
|
||||
return { kind: raw };
|
||||
}
|
||||
|
||||
return { kind: "unknown" };
|
||||
}
|
||||
|
||||
async function classifyByLlm(
|
||||
llmClient: LlmClient,
|
||||
trigger: string,
|
||||
userMessage: string,
|
||||
): Promise<ClassifiedIntent> {
|
||||
if (!llmClient.hasEndpoints()) {
|
||||
return { intent: intent("unknown"), confidence: 0, source: "llm" };
|
||||
return { intent: createIntent(UNKNOWN_INTENT_KIND), confidence: 0, source: "llm" };
|
||||
}
|
||||
|
||||
const response = await llmClient.chatCompletion(
|
||||
[
|
||||
{
|
||||
role: "system",
|
||||
content:
|
||||
'다음 유저 메시지의 intent를 JSON으로만 분류해. {"intent":"..."} 형식만 출력하고, intent는 greeting, acknowledgement, status-question, help-how, help-where, nickname-question, photo-question, discord-question, discord-verify-question, age-question, chitchat, off-topic-to-other, unknown 중 하나만 사용해.',
|
||||
content: `다음 유저 메시지의 intent를 JSON으로만 분류해. {"intent":"..."} 형식만 출력하고, intent는 ${LLM_INTENT_ALLOWLIST.join(", ")} 중 하나만 사용해.`,
|
||||
},
|
||||
{
|
||||
role: "user",
|
||||
@@ -203,18 +43,18 @@ async function classifyByLlm(
|
||||
);
|
||||
|
||||
if (!response) {
|
||||
return { intent: intent("unknown"), confidence: 0, source: "llm" };
|
||||
return { intent: createIntent(UNKNOWN_INTENT_KIND), confidence: 0, source: "llm" };
|
||||
}
|
||||
|
||||
try {
|
||||
const parsed = JSON.parse(response.content) as ClassifierLlmShape;
|
||||
return {
|
||||
intent: parseIntent(parsed.intent),
|
||||
intent: parseOnboardingIntent(parsed.intent),
|
||||
confidence: parsed.intent ? 0.75 : 0,
|
||||
source: "llm",
|
||||
};
|
||||
} catch {
|
||||
return { intent: intent("unknown"), confidence: 0, source: "llm" };
|
||||
return { intent: createIntent(UNKNOWN_INTENT_KIND), confidence: 0, source: "llm" };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -230,7 +70,7 @@ export class OnboardingIntentClassifier {
|
||||
"agent.trigger": trigger,
|
||||
},
|
||||
async (span) => {
|
||||
const triggerIntent = mapTriggerIntent(trigger);
|
||||
const triggerIntent = mapTriggerToIntent(trigger);
|
||||
if (triggerIntent) {
|
||||
span.setAttributes({
|
||||
"agent.classifier.confidence": 1,
|
||||
@@ -261,7 +101,7 @@ export class OnboardingIntentClassifier {
|
||||
);
|
||||
|
||||
const result =
|
||||
llmResult.intent.kind === "unknown" ? regexResult : llmResult;
|
||||
llmResult.intent.kind === UNKNOWN_INTENT_KIND ? regexResult : llmResult;
|
||||
span.setAttributes({
|
||||
"agent.classifier.confidence": result.confidence,
|
||||
"agent.classifier.source": result.source,
|
||||
|
||||
@@ -1,17 +1 @@
|
||||
import type { Intent } from "./onboarding-state.js";
|
||||
|
||||
export const EXPECTED_KEYWORDS: Record<Intent["kind"], string[]> = {
|
||||
acknowledgement: ["네", "좋아요", "천천히"],
|
||||
"age-question": ["27", "가입", "가능"],
|
||||
chitchat: [],
|
||||
"discord-question": ["디스코드", "주민신청", "프로필", "권한", "설정"],
|
||||
"discord-verify-question": ["디스코드", "확인", "닉네임"],
|
||||
greeting: ["반갑", "환영", "어서 오세요"],
|
||||
"help-how": ["하트", "닉네임", "스크린샷", "형식", "본인인증방", "구인방", "운영진"],
|
||||
"help-where": ["오른쪽 상단", "커버 보기", "프로필", "본인인증방", "구인방", "채팅방"],
|
||||
"nickname-question": ["닉네임", "형식", "티어", "/"],
|
||||
"off-topic-to-other": [],
|
||||
"photo-question": ["하트", "스크린샷", "프로필", "커버 보기"],
|
||||
"status-question": ["남았", "완료", "아직", "끝"],
|
||||
unknown: [],
|
||||
};
|
||||
export { EXPECTED_KEYWORDS } from "../intents.js";
|
||||
@@ -1,5 +1,8 @@
|
||||
import type { NicknameIssue } from "../types.js";
|
||||
import type { RoutingDecision } from "../runtime/router.js";
|
||||
import type { Intent } from "../intents.js";
|
||||
|
||||
export type { Intent } from "../intents.js";
|
||||
|
||||
export type RemainingStep =
|
||||
| "nickname"
|
||||
@@ -21,21 +24,6 @@ export type OnboardingPhase =
|
||||
| { kind: "completed" }
|
||||
| { kind: "timed-out" };
|
||||
|
||||
export type Intent =
|
||||
| { kind: "greeting" }
|
||||
| { kind: "acknowledgement" }
|
||||
| { kind: "status-question" }
|
||||
| { kind: "help-how" }
|
||||
| { kind: "help-where" }
|
||||
| { kind: "nickname-question" }
|
||||
| { kind: "photo-question" }
|
||||
| { kind: "discord-question" }
|
||||
| { kind: "discord-verify-question" }
|
||||
| { kind: "age-question" }
|
||||
| { kind: "chitchat" }
|
||||
| { kind: "off-topic-to-other" }
|
||||
| { kind: "unknown" };
|
||||
|
||||
export interface DerivedState {
|
||||
phase: OnboardingPhase;
|
||||
intent: Intent;
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { checkOnboardingProgressTool } from "@tools/onboarding/check-onboarding-progress";
|
||||
import { getRoomContextTool } from "@tools/onboarding/get-room-context";
|
||||
import { lookupCommunityRuleTool } from "@tools/onboarding/lookup-community-rule";
|
||||
import { validateNicknameTool } from "@tools/onboarding/validate-nickname";
|
||||
import { verifyDiscordNicknameTool } from "@tools/onboarding/verify-discord-nickname";
|
||||
import { ToolRegistry } from "@tools/registry";
|
||||
import type { Tool } from "@tools/tool";
|
||||
|
||||
const ONBOARDING_TOOLS = [
|
||||
validateNicknameTool,
|
||||
checkOnboardingProgressTool,
|
||||
lookupCommunityRuleTool,
|
||||
getRoomContextTool,
|
||||
verifyDiscordNicknameTool,
|
||||
] as const satisfies readonly Tool<unknown, unknown>[];
|
||||
|
||||
function readSkillManifestToolNames(): string[] {
|
||||
const skillPath = resolve(process.cwd(), "src", "skills", "onboarding", "SKILL.md");
|
||||
const raw = readFileSync(skillPath, "utf8");
|
||||
const match = raw.match(/^tools:\s*\[([^\]]*)\]/mu);
|
||||
if (!match?.[1]) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return match[1]
|
||||
.split(",")
|
||||
.map((item) => item.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function assertToolManifestMatchesRegistry(): void {
|
||||
const manifestNames = readSkillManifestToolNames().sort();
|
||||
const registryNames = ONBOARDING_TOOLS.map((tool) => tool.name).sort();
|
||||
if (manifestNames.join("\n") !== registryNames.join("\n")) {
|
||||
throw new Error(
|
||||
`Onboarding SKILL.md tools do not match registry: manifest=${manifestNames.join(",")} registry=${registryNames.join(",")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
assertToolManifestMatchesRegistry();
|
||||
|
||||
export function createOnboardingToolRegistry(): ToolRegistry {
|
||||
const registry = new ToolRegistry();
|
||||
for (const tool of ONBOARDING_TOOLS) {
|
||||
registry.register(tool as Tool<unknown, unknown>);
|
||||
}
|
||||
return registry;
|
||||
}
|
||||
|
||||
export {
|
||||
checkOnboardingProgressTool,
|
||||
getRoomContextTool,
|
||||
lookupCommunityRuleTool,
|
||||
validateNicknameTool,
|
||||
verifyDiscordNicknameTool,
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { GarnetClient } from "@common/garnet";
|
||||
import type { NatsClient } from "@common/nats";
|
||||
import type { ShadowEvalBus } from "@eval/shadow-bus";
|
||||
import type { LlmClient } from "@llm/llm-client";
|
||||
import type { RoomContextService } from "@room/room-context-service";
|
||||
import type { Skill } from "./skill.js";
|
||||
|
||||
export interface SkillDeps {
|
||||
garnetClient: GarnetClient;
|
||||
llmClient: LlmClient;
|
||||
natsClient: NatsClient;
|
||||
roomContextService?: RoomContextService | undefined;
|
||||
shadowEvalBus: ShadowEvalBus;
|
||||
}
|
||||
|
||||
export type SkillFactory = (deps: SkillDeps) => Skill;
|
||||
Reference in new issue
Block a user