[chore] docker-compose,ontology: 온톨로지를 이 레포로 들여 compose 한 벌로 띄운다 — 앱 Dockerfile 신설
발행이 SiteOntology 를 부르는데 서버는 따로 띄워야 했다. 실측(2026-09-14): 서버가 없으면 `[seo] SiteOntology 실패 — 키워드 없이 발행: ConnectError` 로 빌드는 성공하고 메타만 빈다 — 화면으로는 안 보이는 종류다. 한 벌로 묶어 "코드는 올라갔는데 서버가 없는" 상태를 없앤다. - ontology/: gitea.o2o.kr/Web4ai/o2o-site-ontology 를 이 레포로 편입(그 원격은 그대로 남는다) - ontology/Dockerfile(신규): 베이스는 node:22-slim. alpine 은 임베딩 런타임(onnxruntime)이 musl 바이너리를 안 줘서 적재가 ERR_DLOPEN_FAILED 로 죽는다 — 빌드는 성공하고 실행에서만 터진다 - docker-compose.yml: ontology · ontology-postgres(pgvector) · ontology-redis 추가. 자체 DB 를 쓰는 이유는 pgvector 확장 때문이다 — web4ai_db 를 남의 서비스 확장에 묶지 않는다 - 임베딩 모델(120MB)은 이미지에 굽지 않고 볼륨(ontology-model)에 남긴다 - 컨테이너끼리는 `http://ontology:3100` 으로 만난다. `.env` 의 127.0.0.1 은 컨테이너 자기 자신이라 안 닿는다 검증: 3개 기동 · 백엔드 컨테이너에서 ontology:3100/demo HTTP 200 · 마이그레이션·시드 완료 Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
bdc69a80f2
commit
01098835e9
70 files changed
+105484
No files matched your search
@@ -0,0 +1,16 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { env } from '../config/env';
|
||||
import { MockLlmProvider } from './mock.provider';
|
||||
import { OpenAiLlmProvider } from './openai.provider';
|
||||
import { LlmProvider } from './types';
|
||||
|
||||
@Module({
|
||||
providers: [
|
||||
{
|
||||
provide: LlmProvider,
|
||||
useClass: env.llm.provider === 'openai' ? OpenAiLlmProvider : MockLlmProvider,
|
||||
},
|
||||
],
|
||||
exports: [LlmProvider],
|
||||
})
|
||||
export class LlmModule {}
|
||||
@@ -0,0 +1,160 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { EMBEDDING_DIM } from '../config/env';
|
||||
import { normalizeKeyword } from '../keywords/normalize';
|
||||
import {
|
||||
GenerationOutput,
|
||||
KeywordCandidate,
|
||||
KeywordIntent,
|
||||
LlmProvider,
|
||||
MerchantContext,
|
||||
QaCandidate,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* API 키 없이 로컬에서 전체 파이프라인(생성 → 중복제거 → 서빙)을 돌리기 위한 대체 구현.
|
||||
*
|
||||
* embed(): 문자 bigram 해싱 + L2 정규화.
|
||||
* 랜덤이 아니라 "비슷한 문자열이면 비슷한 벡터"가 나오므로
|
||||
* 코사인 임계값 기반 중복제거 동작을 실제와 유사하게 검증할 수 있다.
|
||||
*/
|
||||
@Injectable()
|
||||
export class MockLlmProvider extends LlmProvider {
|
||||
readonly name = 'mock';
|
||||
readonly model = 'mock-keyword-v1';
|
||||
|
||||
|
||||
async generate(ctx: MerchantContext): Promise<GenerationOutput> {
|
||||
const region = ctx.regionName ?? '';
|
||||
const industry = ctx.industryName ?? '업체';
|
||||
const p = ctx.profile;
|
||||
const services = toStringArray(p['services']);
|
||||
const features = toStringArray(p['features']);
|
||||
const audiences = toStringArray(p['audiences']);
|
||||
const nearby = toStringArray(p['nearby']);
|
||||
const seasons = toStringArray(p['seasons']);
|
||||
|
||||
const MODIFIERS = ['추천', '예약', '가격', '후기', '저렴한곳', '깨끗한', '인기', '순위', '위치', '실시간예약'];
|
||||
const out: Array<[string, KeywordIntent, number]> = [];
|
||||
const push = (k: string, intent: KeywordIntent, rel: number) => out.push([k, intent, rel]);
|
||||
|
||||
// 실제 로컬 검색 패턴을 프로필 배열의 조합으로 전개한다.
|
||||
push(ctx.name, 'brand', 0.99);
|
||||
push(`${region} ${ctx.name}`, 'brand', 0.97);
|
||||
push(`${region} ${industry}`, 'local', 0.95);
|
||||
push(`${region} ${industry} 추천`, 'local', 0.93);
|
||||
|
||||
for (const m of MODIFIERS) {
|
||||
push(`${region} ${industry} ${m}`, intentOf(m), 0.86);
|
||||
}
|
||||
for (const a of audiences) {
|
||||
push(`${region} ${a} ${industry}`, 'local', 0.88);
|
||||
for (const m of MODIFIERS.slice(0, 4)) push(`${region} ${a} ${industry} ${m}`, intentOf(m), 0.74);
|
||||
push(`${a} ${industry} 추천`, 'informational', 0.62);
|
||||
}
|
||||
for (const f of features) {
|
||||
push(`${region} ${f} ${industry}`, 'local', 0.84);
|
||||
push(`${industry} ${f}`, 'informational', 0.6);
|
||||
push(`${region} ${industry} ${f}`, 'local', 0.7);
|
||||
}
|
||||
for (const s of services) {
|
||||
push(`${region} ${s}`, 'local', 0.82);
|
||||
for (const m of MODIFIERS.slice(0, 4)) push(`${s} ${m}`, intentOf(m), 0.66);
|
||||
}
|
||||
for (const n of nearby) {
|
||||
push(`${n} 근처 ${industry}`, 'local', 0.8);
|
||||
push(`${n} ${industry} 추천`, 'local', 0.76);
|
||||
push(`${n} 숙소`, 'local', 0.68);
|
||||
}
|
||||
for (const s of seasons) {
|
||||
push(`${s} ${region} ${industry}`, 'local', 0.72);
|
||||
push(`${region} ${s} ${industry} 예약`, 'transactional', 0.64);
|
||||
}
|
||||
// 동반자 × 시설 롱테일 — 여기서부터 검색량이 급격히 얇아진다
|
||||
for (const a of audiences) {
|
||||
for (const f of features) push(`${region} ${a} ${f} ${industry}`, 'local', 0.42);
|
||||
}
|
||||
for (const a of audiences) {
|
||||
for (const s of services) push(`${a} ${s}`, 'informational', 0.38);
|
||||
}
|
||||
// 질문형 (AEO 유입)
|
||||
for (const a of audiences) push(`${region} ${a} ${industry} 어디가 좋을까요`, 'informational', 0.5);
|
||||
for (const n of nearby) push(`${n} 여행 ${industry} 어디`, 'informational', 0.44);
|
||||
|
||||
const seen = new Set<string>();
|
||||
const keywords: KeywordCandidate[] = [];
|
||||
for (const [raw, intent, relevance] of out) {
|
||||
const k = raw.replace(/\s+/g, ' ').trim();
|
||||
if (!k || seen.has(k)) continue;
|
||||
seen.add(k);
|
||||
keywords.push({ keyword: k, intent, relevance, rationale: `mock: ${intent}` });
|
||||
if (keywords.length >= ctx.targetCount) break;
|
||||
}
|
||||
|
||||
const qaPairs: QaCandidate[] = [
|
||||
{
|
||||
question: `${ctx.name}은(는) 어디에 있나요?`,
|
||||
answer: `${ctx.name}은(는) ${region || '해당 지역'}에 위치한 ${industry}입니다.`,
|
||||
},
|
||||
{
|
||||
question: `${ctx.name} 예약은 어떻게 하나요?`,
|
||||
answer: `${ctx.name}은(는) 사이트 예약 페이지 또는 전화로 예약할 수 있습니다.`,
|
||||
},
|
||||
{
|
||||
question: `${ctx.name}의 주요 서비스는 무엇인가요?`,
|
||||
answer: services.length
|
||||
? `주요 서비스는 ${services.join(', ')} 입니다.`
|
||||
: `${industry} 관련 서비스를 제공합니다.`,
|
||||
},
|
||||
{
|
||||
question: `${ctx.name} 근처에 가볼 만한 곳은 어디인가요?`,
|
||||
answer: nearby.length
|
||||
? `${nearby.join(', ')} 등이 가깝습니다.`
|
||||
: `${region} 주요 명소가 인근에 있습니다.`,
|
||||
},
|
||||
{
|
||||
question: `${ctx.name}에 ${audiences[0] ?? '반려동물'}도 갈 수 있나요?`,
|
||||
answer: features.length
|
||||
? `${features.join(', ')} 조건을 제공합니다. 예약 전 상세 조건을 확인해 주세요.`
|
||||
: `예약 전 상세 조건을 확인해 주세요.`,
|
||||
},
|
||||
];
|
||||
|
||||
return { keywords, qaPairs, model: this.model, provider: this.name };
|
||||
}
|
||||
}
|
||||
|
||||
function intentOf(modifier: string): KeywordIntent {
|
||||
if (modifier === '예약' || modifier === '실시간예약' || modifier === '가격') return 'transactional';
|
||||
if (modifier === '후기' || modifier === '순위') return 'informational';
|
||||
return 'local';
|
||||
}
|
||||
|
||||
function toStringArray(v: unknown): string[] {
|
||||
return Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
|
||||
}
|
||||
|
||||
/** 문자 bigram 해싱 임베딩 (결정적, L2 정규화) */
|
||||
export function hashEmbedding(text: string, dim = EMBEDDING_DIM): number[] {
|
||||
const s = ` ${normalizeKeyword(text)} `;
|
||||
const vec = new Float64Array(dim);
|
||||
for (let i = 0; i < s.length - 1; i++) {
|
||||
const gram = s.slice(i, i + 2);
|
||||
const h = fnv1a(gram);
|
||||
vec[h % dim] += 1;
|
||||
// 부호 해싱으로 충돌 편향 완화
|
||||
vec[(h >>> 8) % dim] += h & 1 ? 1 : -1;
|
||||
}
|
||||
let norm = 0;
|
||||
for (let i = 0; i < dim; i++) norm += vec[i] * vec[i];
|
||||
norm = Math.sqrt(norm) || 1;
|
||||
return Array.from(vec, (x) => x / norm);
|
||||
}
|
||||
|
||||
function fnv1a(str: string): number {
|
||||
let h = 0x811c9dc5;
|
||||
for (let i = 0; i < str.length; i++) {
|
||||
h ^= str.charCodeAt(i);
|
||||
h = Math.imul(h, 0x01000193) >>> 0;
|
||||
}
|
||||
return h >>> 0;
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
import { Injectable, Logger } from '@nestjs/common';
|
||||
import OpenAI from 'openai';
|
||||
import { env } from '../config/env';
|
||||
import { GenerationOutput, LlmProvider, MerchantContext } from './types';
|
||||
|
||||
/** Structured Outputs 로 강제하는 응답 스키마 — 자유 텍스트 파싱 금지 */
|
||||
const RESPONSE_SCHEMA = {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['keywords', 'qa_pairs'],
|
||||
properties: {
|
||||
keywords: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['keyword', 'intent', 'relevance', 'rationale'],
|
||||
properties: {
|
||||
keyword: { type: 'string' },
|
||||
intent: {
|
||||
type: 'string',
|
||||
enum: ['informational', 'navigational', 'transactional', 'local', 'brand'],
|
||||
},
|
||||
relevance: { type: 'number' },
|
||||
rationale: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
qa_pairs: {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['question', 'answer'],
|
||||
properties: {
|
||||
question: { type: 'string' },
|
||||
answer: { type: 'string' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
@Injectable()
|
||||
export class OpenAiLlmProvider extends LlmProvider {
|
||||
readonly name = 'openai';
|
||||
readonly model = env.llm.model;
|
||||
private readonly logger = new Logger(OpenAiLlmProvider.name);
|
||||
private readonly client = new OpenAI({ apiKey: env.llm.apiKey });
|
||||
|
||||
|
||||
async generate(ctx: MerchantContext): Promise<GenerationOutput> {
|
||||
const res = await this.client.chat.completions.create({
|
||||
model: this.model,
|
||||
temperature: 0.7,
|
||||
messages: [
|
||||
{ role: 'system', content: SYSTEM_PROMPT },
|
||||
{ role: 'user', content: buildUserPrompt(ctx) },
|
||||
],
|
||||
response_format: {
|
||||
type: 'json_schema',
|
||||
json_schema: { name: 'seo_aeo_keywords', strict: true, schema: RESPONSE_SCHEMA as any },
|
||||
},
|
||||
});
|
||||
|
||||
const content = res.choices[0]?.message?.content ?? '{}';
|
||||
const parsed = JSON.parse(content) as {
|
||||
keywords?: GenerationOutput['keywords'];
|
||||
qa_pairs?: GenerationOutput['qaPairs'];
|
||||
};
|
||||
|
||||
return {
|
||||
keywords: parsed.keywords ?? [],
|
||||
qaPairs: parsed.qa_pairs ?? [],
|
||||
model: this.model,
|
||||
provider: this.name,
|
||||
usage: {
|
||||
prompt_tokens: res.usage?.prompt_tokens ?? 0,
|
||||
completion_tokens: res.usage?.completion_tokens ?? 0,
|
||||
total_tokens: res.usage?.total_tokens ?? 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const SYSTEM_PROMPT = `당신은 한국 로컬 비즈니스 SEO/AEO 전문가입니다.
|
||||
주어진 업체 정보를 바탕으로 검색 유입에 실제로 도움이 되는 키워드와,
|
||||
답변엔진(AI 검색)이 인용하기 좋은 질문-답변 쌍을 생성합니다.
|
||||
|
||||
규칙:
|
||||
- 실제 사용자가 검색창에 입력할 법한 자연스러운 한국어 표현만 사용합니다.
|
||||
- 지역명 + 업종 + 의도어 조합을 적극 활용합니다.
|
||||
- 과장광고 표현(최고, 1위, 100%, 무조건, 완치 등)은 절대 사용하지 않습니다.
|
||||
- 제공된 "이미 보유한 키워드"와 의미가 겹치는 것은 생성하지 않습니다.
|
||||
- relevance 는 해당 업체와의 관련도를 0.0~1.0 으로 매깁니다.
|
||||
- 답변(answer)은 2~3문장, 업체 정보에 근거한 사실만 씁니다.`;
|
||||
|
||||
function buildUserPrompt(ctx: MerchantContext): string {
|
||||
return [
|
||||
`# 업체 정보`,
|
||||
`- 상호: ${ctx.name}`,
|
||||
`- 업종: ${ctx.industryName ?? '미상'} (${ctx.industryPath ?? '-'})`,
|
||||
`- 지역: ${ctx.regionName ?? '미상'} (${ctx.regionPath ?? '-'})`,
|
||||
`- 소개: ${ctx.description || '없음'}`,
|
||||
`- 상세: ${JSON.stringify(ctx.profile, null, 2)}`,
|
||||
``,
|
||||
`# 이미 보유한 키워드 (이것들과 겹치지 않는 새 후보만 생성)`,
|
||||
ctx.existingKeywords.length ? ctx.existingKeywords.map((k) => `- ${k}`).join('\n') : '- (없음)',
|
||||
``,
|
||||
`# 요청`,
|
||||
`- 키워드 ${ctx.targetCount}개`,
|
||||
`- 질문-답변 쌍 5개`,
|
||||
].join('\n');
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
export type KeywordIntent =
|
||||
| 'informational'
|
||||
| 'navigational'
|
||||
| 'transactional'
|
||||
| 'local'
|
||||
| 'brand';
|
||||
|
||||
export interface MerchantContext {
|
||||
externalId: string;
|
||||
name: string;
|
||||
description: string;
|
||||
industryName?: string | null;
|
||||
industryPath?: string | null;
|
||||
regionName?: string | null;
|
||||
regionPath?: string | null;
|
||||
profile: Record<string, unknown>;
|
||||
/** 이미 보유한 키워드 — 프롬프트에 넣어 중복 후보 생성 자체를 줄인다 */
|
||||
existingKeywords: string[];
|
||||
targetCount: number;
|
||||
}
|
||||
|
||||
export interface KeywordCandidate {
|
||||
keyword: string;
|
||||
intent: KeywordIntent;
|
||||
relevance: number; // 0..1
|
||||
rationale: string;
|
||||
}
|
||||
|
||||
export interface QaCandidate {
|
||||
question: string;
|
||||
answer: string;
|
||||
}
|
||||
|
||||
export interface GenerationOutput {
|
||||
keywords: KeywordCandidate[];
|
||||
qaPairs: QaCandidate[];
|
||||
model: string;
|
||||
provider: string;
|
||||
usage?: Record<string, number>;
|
||||
}
|
||||
|
||||
export abstract class LlmProvider {
|
||||
abstract readonly name: string;
|
||||
abstract readonly model: string;
|
||||
abstract generate(ctx: MerchantContext): Promise<GenerationOutput>;
|
||||
}
|
||||
Reference in new issue
Block a user