Initialize onboarding agent scaffold
This commit is contained in:
commit
4294f3c92e
57 files changed
+14388
No files matched your search
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PromptBuilder } from "./builder.js";
|
||||
import type { DerivedState } from "../state/onboarding-state.js";
|
||||
import type { OnboardingSession, PromptContext } from "../types.js";
|
||||
|
||||
function makeDerived(
|
||||
overrides?: Partial<DerivedState>,
|
||||
): DerivedState {
|
||||
return {
|
||||
phase: { kind: "photo-pending" },
|
||||
intent: { kind: "photo-question" },
|
||||
shouldRespond: true,
|
||||
responseMode: "llm",
|
||||
suggestedMaxTokens: 256,
|
||||
allowShortResponse: false,
|
||||
tier: 0,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeSession(
|
||||
overrides?: Partial<OnboardingSession>,
|
||||
): OnboardingSession {
|
||||
return {
|
||||
chatroomId: "room-1",
|
||||
deadlineAt: "2026-04-16T12:00:00.000Z",
|
||||
joinedAt: "2026-04-16T10:00:00.000Z",
|
||||
lastEventAt: "2026-04-16T10:30:00.000Z",
|
||||
nickname: "프리리/95/여/D",
|
||||
nicknameVerified: true,
|
||||
photoVerified: false,
|
||||
status: "pending",
|
||||
userId: "user-1",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function makeContext(
|
||||
overrides?: Partial<PromptContext>,
|
||||
): PromptContext {
|
||||
return {
|
||||
blackboard: {
|
||||
flaggedIssues: [],
|
||||
openQuestions: [],
|
||||
recentNicknameAttempts: [],
|
||||
toneMemory: {},
|
||||
},
|
||||
conversationHistory: Array.from({ length: 7 }, (_, index) => ({
|
||||
role: index % 2 === 0 ? "user" : "assistant",
|
||||
content: `message-${index + 1}`,
|
||||
timestamp: `2026-04-16T10:0${index}:00.000Z`,
|
||||
})),
|
||||
summary: "이전 대화 요약",
|
||||
userMessage: "하트 인증은 어떻게 해요?",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("PromptBuilder", () => {
|
||||
it("includes intent-matched examples in system prompt", () => {
|
||||
const messages = PromptBuilder.forDerived(
|
||||
makeDerived(),
|
||||
makeSession(),
|
||||
makeContext(),
|
||||
).build();
|
||||
|
||||
expect(messages[0]?.role).toBe("system");
|
||||
expect(messages[0]?.content).toContain("하트 인증이 뭐예요?");
|
||||
expect(messages[0]?.content).not.toContain("나이 제한 있나요?");
|
||||
});
|
||||
|
||||
it("limits prompt history to the latest five turns when summary exists", () => {
|
||||
const messages = PromptBuilder.forDerived(
|
||||
makeDerived(),
|
||||
makeSession(),
|
||||
makeContext(),
|
||||
).build();
|
||||
|
||||
expect(messages).toHaveLength(7);
|
||||
expect(messages[1]?.content).toBe("message-3");
|
||||
expect(messages[5]?.content).toBe("message-7");
|
||||
expect(messages[0]?.content).toContain("이전 대화 요약");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { ChatMessage } from "@llm/types";
|
||||
import type { DerivedState } from "../state/onboarding-state.js";
|
||||
import type { OnboardingSession, PromptContext } from "../types.js";
|
||||
import {
|
||||
contextLayer,
|
||||
examplesLayer,
|
||||
personaLayer,
|
||||
policyLayer,
|
||||
stateLayer,
|
||||
} from "./layers.js";
|
||||
|
||||
export class PromptBuilder {
|
||||
private constructor(
|
||||
private readonly derived: DerivedState,
|
||||
private readonly session: OnboardingSession | null,
|
||||
private readonly context: PromptContext,
|
||||
) {}
|
||||
|
||||
static forDerived(
|
||||
derived: DerivedState,
|
||||
session: OnboardingSession | null,
|
||||
context: PromptContext,
|
||||
): PromptBuilder {
|
||||
return new PromptBuilder(derived, session, context);
|
||||
}
|
||||
|
||||
build(): ChatMessage[] {
|
||||
const promptHistory = this.context.summary
|
||||
? this.context.conversationHistory.slice(-5)
|
||||
: this.context.conversationHistory;
|
||||
const promptContext: PromptContext = {
|
||||
...this.context,
|
||||
conversationHistory: promptHistory,
|
||||
};
|
||||
|
||||
const systemPrompt = [
|
||||
personaLayer(),
|
||||
policyLayer(this.derived.intent),
|
||||
stateLayer(this.session, this.derived),
|
||||
examplesLayer(this.derived.intent),
|
||||
contextLayer(promptContext),
|
||||
].join("\n\n");
|
||||
|
||||
return [
|
||||
{ role: "system", content: systemPrompt },
|
||||
...promptHistory.map((message) => ({
|
||||
role: message.role,
|
||||
content: message.content,
|
||||
})),
|
||||
{ role: "user", content: this.context.userMessage },
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { Intent } from "../state/onboarding-state.js";
|
||||
import type { Example } from "../types.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:
|
||||
"닉네임은 이름/출생 연도 두 자리/성별/티어 형식이에요. 예를 들면 홍길동/95/여/D처럼 쓰시면 돼요.",
|
||||
},
|
||||
],
|
||||
"help-where": [
|
||||
{
|
||||
user: "하트 어디서 바꿔요?",
|
||||
assistant:
|
||||
'채팅방 오른쪽 상단 메뉴 버튼을 누르면 "커버 보기"가 보여요. 거기서 프로필과 하트를 확인하실 수 있어요.',
|
||||
},
|
||||
],
|
||||
"nickname-question": [
|
||||
{
|
||||
user: "닉네임이 왜 안 돼요?",
|
||||
assistant:
|
||||
"티어는 한 글자 코드로 넣어야 해요. 예를 들면 D처럼 바꿔주시면 돼요.",
|
||||
},
|
||||
{
|
||||
user: "닉네임 형식이 뭐예요?",
|
||||
assistant:
|
||||
"닉네임은 이름/출생 연도 두 자리/성별/티어 형식으로 입력해 주시면 돼요.",
|
||||
},
|
||||
],
|
||||
"photo-question": [
|
||||
{
|
||||
user: "하트 인증이 뭐예요?",
|
||||
assistant:
|
||||
"채팅방 프로필에서 하트를 빨간색으로 바꾼 뒤, 그 화면이 보이게 원본 스크린샷을 보내주시면 돼요.",
|
||||
},
|
||||
],
|
||||
"discord-question": [
|
||||
{
|
||||
user: "디스코드는 언제 들어가요?",
|
||||
assistant:
|
||||
"닉네임 변경과 하트 인증을 모두 완료하신 뒤에 디스코드 안내를 받으실 수 있어요.",
|
||||
},
|
||||
],
|
||||
"age-question": [
|
||||
{
|
||||
user: "나이 제한 있나요?",
|
||||
assistant: "롤림푸스는 27세 이상만 가입이 가능해요.",
|
||||
},
|
||||
],
|
||||
chitchat: [
|
||||
{
|
||||
user: "오늘 날씨 좋네요",
|
||||
assistant: "[NO_RESPONSE]",
|
||||
},
|
||||
],
|
||||
"off-topic-to-other": [
|
||||
{
|
||||
user: "@프리리 이거 확인해줘",
|
||||
assistant: "[NO_RESPONSE]",
|
||||
},
|
||||
],
|
||||
unknown: [
|
||||
{
|
||||
user: "가입은 어떻게 하나요?",
|
||||
assistant:
|
||||
"톡 게시글의 공지를 참고하셔서 닉네임 변경과 하트 인증을 진행해 주세요!",
|
||||
},
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,194 @@
|
||||
import type { ConversationMessage } from "@agent/types";
|
||||
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 { EXAMPLES_BY_INTENT } from "./examples.js";
|
||||
|
||||
function formatKstTimestamp(value: string | undefined): string {
|
||||
if (!value) {
|
||||
return "없음";
|
||||
}
|
||||
|
||||
const timestamp = Date.parse(value);
|
||||
if (!Number.isFinite(timestamp)) {
|
||||
return "없음";
|
||||
}
|
||||
|
||||
return new Intl.DateTimeFormat("ko-KR", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "short",
|
||||
timeZone: "Asia/Seoul",
|
||||
}).format(new Date(timestamp));
|
||||
}
|
||||
|
||||
function formatNicknameStatus(session: OnboardingSession | null): string {
|
||||
if (!session) {
|
||||
return "미완료";
|
||||
}
|
||||
|
||||
return session.nicknameVerified
|
||||
? `완료 (${session.nickname})`
|
||||
: `미완료 (현재: ${session.nickname})`;
|
||||
}
|
||||
|
||||
function formatPhotoStatus(session: OnboardingSession | null): string {
|
||||
if (!session) {
|
||||
return "미완료";
|
||||
}
|
||||
|
||||
return session.photoVerified ? "완료" : "미완료";
|
||||
}
|
||||
|
||||
function formatHistory(history: ConversationMessage[]): string {
|
||||
if (history.length === 0) {
|
||||
return "(최근 대화 없음)";
|
||||
}
|
||||
|
||||
return history.map((message) => `${message.role}: ${message.content}`).join("\n");
|
||||
}
|
||||
|
||||
function formatRoomMessages(roomContext?: RoomMessage[]): string {
|
||||
if (!roomContext || roomContext.length === 0) {
|
||||
return "(방 분위기 정보 없음)";
|
||||
}
|
||||
|
||||
return roomContext
|
||||
.slice(-5)
|
||||
.map((message) => `${message.nickname}: ${message.message}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
function formatBlackboard(blackboard: Blackboard): string {
|
||||
const openQuestions =
|
||||
blackboard.openQuestions.length > 0
|
||||
? blackboard.openQuestions.join(", ")
|
||||
: "(없음)";
|
||||
const flaggedIssues =
|
||||
blackboard.flaggedIssues.length > 0
|
||||
? blackboard.flaggedIssues.join(", ")
|
||||
: "(없음)";
|
||||
const nicknameAttempts =
|
||||
blackboard.recentNicknameAttempts.length > 0
|
||||
? blackboard.recentNicknameAttempts.join(", ")
|
||||
: "(없음)";
|
||||
|
||||
return [
|
||||
`- lastIntent: ${blackboard.lastIntent ?? "(없음)"}`,
|
||||
`- openQuestions: ${openQuestions}`,
|
||||
`- flaggedIssues: ${flaggedIssues}`,
|
||||
`- recentNicknameAttempts: ${nicknameAttempts}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function formatExample(example: Example): string {
|
||||
return `유저: ${example.user}\n응답: ${example.assistant}`;
|
||||
}
|
||||
|
||||
export function personaLayer(): string {
|
||||
return `너는 롤림푸스(lolympus) 카카오톡 오픈채팅에서 새내기 등록을 도와주는 친절한 선배야.
|
||||
처음 온 멤버가 편안하게 등록을 마칠 수 있도록 자연스럽고 정확하게 안내해줘.
|
||||
|
||||
[커뮤니티 규칙]
|
||||
- 가입 가능 연령은 27세 이상이야.
|
||||
- 새내기 등록은 닉네임 변경과 방 하트 인증 두 가지를 모두 완료하면 돼.
|
||||
- 닉네임 형식은 이름/출생 연도 두 자리/성별/티어야. 예: 홍길동/95/남/G
|
||||
- 성별은 남 또는 여, 티어 코드는 GM, I, B, S, G, P, E, D, M, C, U 중 하나야.
|
||||
- 방 하트 인증은 채팅방 프로필에서 하트를 빨간색으로 바꾼 뒤 편집 없는 원본 스크린샷을 보내는 절차야.
|
||||
- 디스코드 안내는 닉네임 변경과 하트 인증이 모두 완료된 뒤에만 해줘.`;
|
||||
}
|
||||
|
||||
export function policyLayer(
|
||||
intent: Intent,
|
||||
options?: { toolPolicy?: string | undefined },
|
||||
): string {
|
||||
const lines = [
|
||||
"[답변 원칙]",
|
||||
"- 마지막 메시지에서 직접 물은 내용에만 정확히 답해.",
|
||||
"- 사용자가 요청하지 않은 다음 단계, 방법, 위치, 예시는 먼저 붙이지 마.",
|
||||
"- 마크다운 문법, 링크, URL은 쓰지 마.",
|
||||
'- 온보딩과 무관한 잡담이거나 다른 사람에게 하는 말이면 "[NO_RESPONSE]"만 출력해.',
|
||||
];
|
||||
|
||||
switch (intent.kind) {
|
||||
case "greeting":
|
||||
lines.push("- 짧은 인사만 1문장으로 답해.");
|
||||
break;
|
||||
case "acknowledgement":
|
||||
lines.push("- 짧은 확인이나 마무리만 1문장으로 답해.");
|
||||
break;
|
||||
case "status-question":
|
||||
lines.push("- 현재 남은 절차나 완료 상태만 1문장으로 짧게 답해.");
|
||||
lines.push("- 방법 설명, 위치 설명, 예시는 넣지 마.");
|
||||
break;
|
||||
case "help-where":
|
||||
lines.push("- 위치나 경로만 답하고, 요청하지 않은 다음 단계는 붙이지 마.");
|
||||
break;
|
||||
case "help-how":
|
||||
lines.push("- 사용자가 물은 한 가지 절차의 방법만 답해.");
|
||||
break;
|
||||
case "nickname-question":
|
||||
lines.push("- 닉네임 형식 또는 오류 원인만 답하고 다른 절차는 언급하지 마.");
|
||||
break;
|
||||
case "photo-question":
|
||||
lines.push("- 하트 인증에 대해서만 답하고 다른 절차는 언급하지 마.");
|
||||
break;
|
||||
case "discord-question":
|
||||
lines.push("- 디스코드 질문에만 답해. 완료 전이라면 먼저 온보딩 완료가 필요하다고만 알려줘.");
|
||||
break;
|
||||
case "age-question":
|
||||
lines.push("- 나이 제한만 간단히 답해.");
|
||||
break;
|
||||
default:
|
||||
lines.push("- 질문 범위를 넘어서 먼저 설명하지 마.");
|
||||
break;
|
||||
}
|
||||
|
||||
if (options?.toolPolicy) {
|
||||
lines.push(options.toolPolicy);
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function stateLayer(
|
||||
session: OnboardingSession | null,
|
||||
derived: DerivedState,
|
||||
): string {
|
||||
return [
|
||||
"[현재 유저 상태]",
|
||||
`- phase: ${derived.phase.kind}`,
|
||||
`- nickname: ${formatNicknameStatus(session)}`,
|
||||
`- photo: ${formatPhotoStatus(session)}`,
|
||||
`- deadline(KST): ${formatKstTimestamp(session?.deadlineAt)}`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
export function examplesLayer(intent: Intent, count = 3): string {
|
||||
const examples = EXAMPLES_BY_INTENT[intent.kind].slice(0, count);
|
||||
const rendered = examples.length > 0
|
||||
? examples.map(formatExample).join("\n\n")
|
||||
: "(예시 없음)";
|
||||
|
||||
return `[응답 예시]\n${rendered}`;
|
||||
}
|
||||
|
||||
export function contextLayer(context: PromptContext): string {
|
||||
return [
|
||||
"[최근 요약]",
|
||||
context.summary ?? "(요약 없음)",
|
||||
"",
|
||||
"[최근 대화]",
|
||||
formatHistory(context.conversationHistory),
|
||||
"",
|
||||
"[방 분위기]",
|
||||
formatRoomMessages(context.roomContext),
|
||||
"",
|
||||
"[메모]",
|
||||
formatBlackboard(context.blackboard),
|
||||
].join("\n");
|
||||
}
|
||||
Reference in new issue
Block a user