feat(place_search): 카카오맵 장소검색 채팅 도구 (기준 위치 구미)
카카오 로컬 키워드검색으로 국내 장소의 실제 주소·전화·거리·카카오맵 링크를 돌려준다. 기준 위치 기본값은 구미시, location으로 지역·역·건물 지정, category·radius·sort 지원. 지도·근처·맛집·약국·전화번호 등 키워드로만 도구를 열고(tool-scope), 시스템 프롬프트에 "주소를 기억으로 짓지 말고 place_search 먼저" 규칙을 추가했다. 기존 구글맵 임베드 규칙은 유지. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e4fe7edd61
commit
74c323e9da
6 files changed
+237
-1
No files matched your search
@@ -1091,6 +1091,24 @@ export function createBuildTools(isOrchestrationSkillEnabled: () => boolean) {
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'place_search',
|
||||
description: '카카오맵으로 국내 장소(식당·카페·약국·병원·주유소·편의점·관광지·역·건물 등)를 검색해 실제 주소·전화·거리·카카오맵 링크를 돌려준다. "구미역 근처 약국", "현풍 맛집", "가까운 주유소", "OO 전화번호/주소/위치" 요청에 사용. 장소 주소를 기억으로 지어내지 말고 이 도구로 찾을 것. 기준 위치 기본값은 구미시, 다른 지역·역·건물 기준이면 location에 넣는다. "근처/가까운"이면 sort="distance". 영업시간·리뷰는 결과의 상세 링크로 안내(이 도구는 영업시간을 직접 주지 않음). 한국 밖은 지원하지 않는다.',
|
||||
parameters: {
|
||||
type: 'object', required: ['query'],
|
||||
properties: {
|
||||
query: { type: 'string', description: '검색어. 장소명·업종·메뉴 등(예: "약국", "칼국수", "구미역")' },
|
||||
location: { type: 'string', description: '기준 지역·역·건물 이름(선택, 기본 구미시). 예: "현풍", "대구 동성로", "구미역"' },
|
||||
category: { type: 'string', description: '업종 필터(선택): 음식점/카페/약국/병원/편의점/주유소/은행/주차장/숙박/관광명소/지하철역/마트' },
|
||||
radius: { type: 'number', description: '반경 미터(선택, 최대 20000)' },
|
||||
sort: { type: 'string', enum: ['accuracy', 'distance'], description: '정렬(기본 accuracy). "근처/가까운"이면 distance' },
|
||||
size: { type: 'number', description: '결과 수(기본 8, 최대 15)' },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'function',
|
||||
function: {
|
||||
|
||||
@@ -221,6 +221,10 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
// keyless (maps.google.com/maps?q=...&output=embed) so nothing needs configuring. markdown.js
|
||||
// only converts /maps/search/ and /maps/place/ forms — do NOT promise route rendering here,
|
||||
// /maps/dir/ is not embedded.
|
||||
// place_search(카카오맵)가 있을 때: 장소 주소·전화·거리는 도구로 찾는다. 기억으로 주소를 짓지 않는다.
|
||||
const placeSearchRuleBlock = toolNames.has('place_search')
|
||||
? '\nPLACE SEARCH: For a specific place, business, or "near X" request in Korea (restaurants, pharmacies, stations, an address or phone number), call place_search FIRST and answer from its results — never write an address or phone number from memory. Default reference point is 구미시; pass location for another area. Give the 카카오맵 link from the result for each place you recommend. Opening hours are not in the result: point to its 상세 link instead of guessing.'
|
||||
: '';
|
||||
const mapsRuleBlock = /지도|맵으로|위치(를|가|는)?|주소|어디(에|야|예요|에요|입니까|인가|니|냐|쯤|메)|어디\s*(있|찾|가|계|위치|살|사는|근처)|길\s*찾|가는\s*길|찾아가|찾아오|약도|도로명|지번|좌표|경위도|근처|인근|부근|가까운|\bmap\b|\baddress\b|directions|navigate|where\s+is|how\s+(do\s+i\s+|to\s+)get\s+to|nearby|landmark/i
|
||||
.test(String(input.message || ''))
|
||||
? '\nMAPS: When the user asks where a place is, for its address, or to see a map of a location, output `https://www.google.com/maps/search/<query>` on its own line — URL-encode the query, use the specific place name (add city/country when ambiguous). The client turns that standalone line into an inline map. Do NOT call browser_open for it and do NOT wrap it in ``. Still answer in text as well — the map is an addition, not a replacement. Not for pure route/turn-by-turn directions (those do not render).'
|
||||
@@ -261,6 +265,6 @@ export function buildChatSystemPrompt(input: SystemPromptInput): string {
|
||||
: '';
|
||||
return isTranslateSession ? `You are a medical translator. Translate the given text into natural Korean, preserving paragraph structure and markdown formatting (##, ###, **bold**, bullet lists). Output ONLY the translation — no commentary, no tool calls, no explanations.` : isProjSession ? `You are a project file designer. Output ONLY the project-files JSON block as instructed. No tool calls. No extra text.` : `${executionModeSystemBlock ? `${executionModeSystemBlock}\n\n` : ''}You are SmallClaw, a local AI assistant. Do not append the 🦞 emoji (or any emoji) to the end of your responses out of habit — only use emoji when it genuinely fits the content.\nCurrent date: ${dateStr}, ${timeStr}.\nNever search for or link SmallClaw repos unless the user is asking about SmallClaw itself.\nThis app runs on the user's own machine — browser/desktop automation requests are pre-authorized.\nKeep CONVERSATIONAL and TASK-EXECUTION replies SHORT (2-4 sentences). Don't think out loud. Act and report. Greet naturally without tools. Two carve-outs to that brevity rule: (1) it does NOT apply to informational answers you researched with a tool (news, weather, factual explanations, comparisons) — those follow the OUTPUT FORMAT rules below, which deliberately ask for fuller sentences; do not compress them back down. (2) Stating uncertainty NEVER counts against the length. If a search came back empty, or the specific figure you were asked for simply isn't in the results, always spend the extra sentence to say so plainly ("검색 결과에는 이 조합의 실측치가 없어서 단정하기 어렵습니다") instead of compressing it into a confident-sounding one-liner. Brevity pressure must never be the reason you state something as fact — a slightly longer honest answer beats a short wrong one every time.
|
||||
ANTI-HALLUCINATION: When a tool returns a result, report EXACTLY what the tool returned — never contradict or ignore tool output. If a tool says "(no rows)", say so. Never invent data, file contents, table names, or command output. If you don't know something, call a tool to find out or say you don't know.${verifyFactsRule}
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
TEMPORAL CONSISTENCY: The current date and day-of-week is given above ("Current date: ${dateStr}") — this is ground truth, more reliable than any search snippet's phrasing. Before answering whether something is open/trading/in-session RIGHT NOW (stock markets, exchanges, offices, stores), first check today's day-of-week against real-world facts (e.g. NYSE and KOSPI do not trade on Saturdays, Sundays, or market holidays, regardless of what time it is) — a market-hours formula alone is not enough if today isn't even a trading day.${searchReadingRule}${searchPersistenceRule}${fileSearchRule}${imageEditRuleBlock}${mediaGenRuleBlock}${browserRuleBlock}${chemistryRuleBlock}${mapsRuleBlock}${placeSearchRuleBlock}${codeOutputRuleBlock}${packageInstallRuleBlock}
|
||||
OUTPUT FORMAT: When presenting 3+ items (emails, search results, lists), always use a markdown table or structured bullet list with clear headers. Never dump them as a long paragraph.${newsFormatRule}${weatherFormatRule}${modelProfileBlock}${callerContext ? '\n\n' + callerContext : ''}${browserStateCtx}${personalityCtx}${skillsCtx}`;
|
||||
}
|
||||
@@ -188,6 +188,10 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
|
||||
// 돌았는데, 바로 다음 "아니다 cam2" / "사진 보여줘" 후속턴엔 키워드가 없어 도구가 사라지자
|
||||
// 모델이 "저는 그런 툴이 없습니다"라고 3턴 연속 답했다. 스테일 매치 비용은 작은 스키마 토큰뿐.
|
||||
const hasCctvKeyword = /cctv|감시\s*카메라|카메라(로|에|를|\s|$)|웹캠|현관(?:문|앞|쪽)?|마당|주차장|차고|대문|택배|초인종|스냅샷|캡처해|누가?\s*(?:왔|있|지나)|누구\s*(?:있|왔)|밖에?\s*(?:누구|뭐|무슨)|집\s*(?:앞|밖|상황)|\bcam\s*\d|채널\s*\d.*(?:봐|보여|확인|찍)|door\s*cam|security\s*cam|who'?s?\s*(?:at\s*the\s*door|outside)/i.test(topicText);
|
||||
// place_search — 카카오맵 장소검색(2026-10-14). "근처·맛집·약국·주소·전화번호·길찾기" 류에만 연다.
|
||||
// 후속 발화("거기 전화번호는?")가 앞 턴의 주제를 물려받으므로 topicText로 검사한다. 스테일 매치 비용은
|
||||
// 스키마 토큰뿐. "병원"은 CMS 병원 성과 질문과 겹쳐서 단독으로는 넣지 않고 근처·위치 어휘와 함께만 본다.
|
||||
const hasPlaceKeyword = /근처|주변|가까운|인근|맛집|약국|식당|카페|편의점|주유소|마트|주차장|지도|길\s*찾|가는\s*길|어디(?:에|야|예요|있)|전화\s*번호|영업\s*시간|몇\s*시까지|주소|위치/i.test(topicText);
|
||||
// print3d_model — STL 슬라이싱+K2 프린터 업로드. topicText로 검사(prepare→start 확인
|
||||
// 왕복이 여러 턴 걸치므로 nvr_snapshot과 같은 이유로 최근 대화 전체를 봄).
|
||||
const hasPrint3dKeyword = /3d\s*프린트|3d\s*print|stl|슬라이싱|슬라이서|g-?code|출력해|프린터로|k2\s*(?:콤보|프린터)?/i.test(topicText);
|
||||
@@ -396,6 +400,7 @@ export function buildSkillToolFilter(input: ToolScopeInput): (toolName: string)
|
||||
if (name === 'schedule_job' && !hasScheduleKeyword) return false;
|
||||
if ((name === 'eonet_events' || name === 'satellite_snapshot') && !hasSatelliteKeyword) return false;
|
||||
if (name === 'nvr_snapshot' && !hasCctvKeyword) return false;
|
||||
if (name === 'place_search' && !hasPlaceKeyword) return false;
|
||||
if (name === 'print3d_model' && !hasPrint3dKeyword) return false;
|
||||
// model_search/model_download — 09-23: 3D 모델 저장소(Printables/MakerWorld/Thingiverse)
|
||||
// 검색·다운로드. 작업실 세션(ws_)에선 항상 노출, 메인 채팅에선 print3d_model과 같은
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
/**
|
||||
* kakao-places.ts — 카카오 로컬 키워드·카테고리 장소검색 채팅 도구(place_search).
|
||||
*
|
||||
* "구미역 근처 약국", "현풍 맛집", "가까운 주유소" 류. 모델이 주소를 짐작해 구글맵 링크만 만들던
|
||||
* MAPS 규칙(system-prompt.ts)을 대체한다 — 실제로 존재하는 장소를 찾아 주소·전화·거리·카카오맵 링크를 준다.
|
||||
*
|
||||
* 기준 위치 기본값은 구미시(사용자 결정 2026-10-14). location을 주면 그 지역(주소검색 REGION, 없으면
|
||||
* 키워드 첫 결과)을 기준점으로 쓴다. 키는 kakao-geocode.ts와 같은 REST 키(vault channels.kakao.appKey).
|
||||
*/
|
||||
import path from 'path';
|
||||
import { ToolResult } from '../types.js';
|
||||
import { getConfig } from '../config/config.js';
|
||||
import { getVault } from '../security/vault.js';
|
||||
import { kakaoGeocode, inKoreaBox } from './kakao-geocode.js';
|
||||
|
||||
const LOCAL_BASE = 'https://dapi.kakao.com/v2/local/search';
|
||||
export const DEFAULT_CENTER = { lat: 36.1196, lon: 128.3442, name: '경북 구미시' };
|
||||
|
||||
/** 카카오 카테고리 그룹 코드. 이름은 모델이 쓰기 쉬운 한글로 받아 코드로 바꾼다. */
|
||||
const CATEGORY_CODES: Record<string, string> = {
|
||||
'대형마트': 'MT1', '마트': 'MT1', '편의점': 'CS2', '어린이집': 'PS3', '유치원': 'PS3', '학교': 'SC4',
|
||||
'학원': 'AC5', '주차장': 'PK6', '주유소': 'OL7', '충전소': 'OL7', '지하철역': 'SW8', '은행': 'BK9',
|
||||
'문화시설': 'CT1', '중개업소': 'AG2', '공공기관': 'PO3', '관광명소': 'AT4', '숙박': 'AD5',
|
||||
'음식점': 'FD6', '식당': 'FD6', '맛집': 'FD6', '카페': 'CE7', '병원': 'HP8', '약국': 'PM9',
|
||||
};
|
||||
|
||||
export function categoryCodeFor(name: string): string | undefined {
|
||||
const k = String(name || '').trim();
|
||||
if (/^[A-Z]{2}\d$/.test(k)) return k;
|
||||
return CATEGORY_CODES[k];
|
||||
}
|
||||
|
||||
function getRestKey(): string | undefined {
|
||||
try {
|
||||
const cm = getConfig();
|
||||
return cm.resolveSecret((cm.getConfig() as any).channels?.kakao?.appKey)
|
||||
|| getVault(cm.getConfigDir()).get('channels.kakao.appKey', 'kakao:places')?.expose();
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
function fmtDistance(m: string | undefined): string {
|
||||
const n = Number(m);
|
||||
if (!Number.isFinite(n) || n < 0 || m === '' || m == null) return '';
|
||||
return n >= 1000 ? `${(n / 1000).toFixed(1)}km` : `${Math.round(n)}m`;
|
||||
}
|
||||
|
||||
export interface PlaceDoc {
|
||||
place_name?: string; category_name?: string; address_name?: string; road_address_name?: string;
|
||||
phone?: string; place_url?: string; distance?: string; x?: string; y?: string;
|
||||
}
|
||||
|
||||
/** 검색 결과를 모델이 그대로 옮겨 쓰기 쉬운 줄로 바꾼다. 지도 링크는 좌표로 항상 만든다. */
|
||||
export function formatPlaces(docs: PlaceDoc[], originName: string, total?: number): string {
|
||||
if (!docs.length) return '';
|
||||
const lines: string[] = [`기준: ${originName}${total != null ? ` · 총 ${total}건 중 ${docs.length}건 표시` : ''}`, ''];
|
||||
docs.forEach((d, i) => {
|
||||
const name = d.place_name || '(이름 없음)';
|
||||
const cat = String(d.category_name || '').split('>').map(s => s.trim()).filter(Boolean).slice(-2).join(' > ');
|
||||
const addr = d.road_address_name || d.address_name || '';
|
||||
const dist = fmtDistance(d.distance);
|
||||
const map = d.y && d.x ? `https://map.kakao.com/link/map/${encodeURIComponent(name)},${d.y},${d.x}` : (d.place_url || '');
|
||||
lines.push(`${i + 1}. ${name}${cat ? ` (${cat})` : ''}${dist ? ` — ${dist}` : ''}`);
|
||||
if (addr) lines.push(` 주소: ${addr}`);
|
||||
if (d.phone) lines.push(` 전화: ${d.phone}`);
|
||||
if (d.place_url) lines.push(` 상세(영업시간·리뷰): ${d.place_url}`);
|
||||
if (map) lines.push(` 지도: ${map}`);
|
||||
});
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
async function kakaoGet(endpoint: string, params: Record<string, string>, key: string): Promise<any> {
|
||||
const qs = new URLSearchParams(params);
|
||||
const res = await fetch(`${LOCAL_BASE}/${endpoint}?${qs}`, {
|
||||
headers: { Authorization: `KakaoAK ${key}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const text = await res.text();
|
||||
if (!res.ok) {
|
||||
let msg = text.slice(0, 160);
|
||||
try { msg = JSON.parse(text)?.message || msg; } catch { /* keep */ }
|
||||
throw new Error(`카카오 로컬 API ${res.status}: ${msg}`);
|
||||
}
|
||||
return JSON.parse(text);
|
||||
}
|
||||
|
||||
async function resolveCenter(location: string, key: string): Promise<{ lat: number; lon: number; name: string; found: boolean }> {
|
||||
const loc = String(location || '').trim();
|
||||
if (!loc) return { ...DEFAULT_CENTER, found: true };
|
||||
const cm = getConfig();
|
||||
const g = await kakaoGeocode(loc, {
|
||||
getKey: () => key,
|
||||
cacheFile: path.join(cm.getConfigDir(), 'geocode-kakao-cache.json'),
|
||||
});
|
||||
if (g) return { lat: g.lat, lon: g.lon, name: g.displayName.replace(/, 대한민국$/, ''), found: true };
|
||||
// 역·건물·상호처럼 행정구역이 아닌 기준점은 키워드 첫 결과를 쓴다.
|
||||
try {
|
||||
const j = await kakaoGet('keyword.json', { query: loc, size: '1' }, key);
|
||||
const d = j?.documents?.[0];
|
||||
const lat = Number(d?.y), lon = Number(d?.x);
|
||||
if (d && inKoreaBox(lat, lon)) return { lat, lon, name: String(d.place_name || loc), found: true };
|
||||
} catch { /* 아래 기본값 */ }
|
||||
return { ...DEFAULT_CENTER, found: false };
|
||||
}
|
||||
|
||||
export const placeSearchTool = {
|
||||
name: 'place_search',
|
||||
description:
|
||||
'카카오맵으로 국내 장소(식당·카페·약국·병원·주유소·편의점·관광지·역·건물 등)를 검색해 실제 주소·전화·거리·카카오맵 링크를 돌려준다. ' +
|
||||
'"구미역 근처 약국", "현풍 맛집", "가까운 주유소", "OO 전화번호/주소/위치" 같은 요청에 사용. 장소 주소를 기억으로 지어내지 말고 이 도구로 찾을 것. ' +
|
||||
'기준 위치 기본값은 구미시이며, 다른 지역·역·건물을 기준으로 하려면 location에 넣는다. "근처/가까운"이면 sort="distance". ' +
|
||||
'영업시간·리뷰는 결과의 상세 링크(place_url)로 안내한다 — 이 도구는 영업시간을 직접 주지 않는다. 한국 밖 장소는 지원하지 않는다.',
|
||||
schema: { query: 'string', location: 'string?', category: 'string?', radius: 'number?', sort: 'string?', size: 'number?' },
|
||||
jsonSchema: {
|
||||
type: 'object',
|
||||
required: ['query'],
|
||||
properties: {
|
||||
query: { type: 'string', description: '검색어. 장소명·업종·메뉴 등(예: "약국", "칼국수", "구미역")' },
|
||||
location: { type: 'string', description: '기준 지역·역·건물 이름(선택, 기본 구미시). 예: "현풍", "대구 동성로", "구미역"' },
|
||||
category: { type: 'string', description: '업종 필터(선택): 음식점/카페/약국/병원/편의점/주유소/은행/주차장/숙박/관광명소/지하철역/마트 등' },
|
||||
radius: { type: 'number', description: '반경 미터(선택, 최대 20000). 주면 그 반경 안으로 제한' },
|
||||
sort: { type: 'string', enum: ['accuracy', 'distance'], description: '정렬(기본 accuracy). "근처/가까운"이면 distance' },
|
||||
size: { type: 'number', description: '결과 수(기본 8, 최대 15)' },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
execute: async (args: any): Promise<ToolResult> => {
|
||||
const query = String(args?.query || '').trim();
|
||||
if (!query) return { success: false, error: 'query is required' };
|
||||
const key = getRestKey();
|
||||
if (!key) return { success: false, error: '카카오 REST 키가 없습니다(vault channels.kakao.appKey).' };
|
||||
const size = Math.min(Math.max(1, Math.round(Number(args?.size) || 8)), 15);
|
||||
const radius = Math.min(Math.max(0, Math.round(Number(args?.radius) || 0)), 20000);
|
||||
const sort = args?.sort === 'distance' ? 'distance' : 'accuracy';
|
||||
const cat = args?.category ? categoryCodeFor(String(args.category)) : undefined;
|
||||
try {
|
||||
const c = await resolveCenter(String(args?.location || ''), key);
|
||||
const params: Record<string, string> = {
|
||||
query, x: String(c.lon), y: String(c.lat), size: String(size), sort,
|
||||
};
|
||||
if (radius) params.radius = String(radius);
|
||||
if (cat) params.category_group_code = cat;
|
||||
const j = await kakaoGet('keyword.json', params, key);
|
||||
const docs: PlaceDoc[] = j?.documents || [];
|
||||
const total = j?.meta?.total_count;
|
||||
if (!docs.length) {
|
||||
return { success: true, stdout: `"${query}" 검색 결과가 없습니다(기준: ${c.name}${radius ? `, 반경 ${radius}m` : ''}). 검색어를 줄이거나 지역을 바꿔 다시 시도할 것.` };
|
||||
}
|
||||
const note = c.found ? '' : `\n※ 기준 위치 "${args?.location}"를 찾지 못해 기본값(${DEFAULT_CENTER.name})을 기준으로 했다.`;
|
||||
return { success: true, stdout: formatPlaces(docs, c.name, total) + note };
|
||||
} catch (err: any) {
|
||||
return { success: false, error: err.message };
|
||||
}
|
||||
},
|
||||
};
|
||||
@@ -31,6 +31,7 @@ import { excelReadTool, excelWriteTool } from './excel.js';
|
||||
import { cmsHospitalCompareTool } from './cms.js';
|
||||
import { drugDurCheckTool } from './mfds.js';
|
||||
import { nvrSnapshotTool } from './nvr.js';
|
||||
import { placeSearchTool } from './kakao-places.js';
|
||||
import { print3dModelTool } from './print3d.js';
|
||||
import { modelSearchTool, modelDownloadTool } from './model-search.js';
|
||||
import { workshopProjectTool } from './workshop-project.js';
|
||||
@@ -240,6 +241,7 @@ class ToolRegistry {
|
||||
this.registerSafe(satelliteSnapshotTool);
|
||||
// 집 CCTV 한 프레임 캡처 → 비전 모델이 직접 확인 (감시카메라/마당/현관/택배 확인 요청)
|
||||
this.registerSafe(nvrSnapshotTool);
|
||||
this.registerSafe(placeSearchTool);
|
||||
this.registerSafe(print3dModelTool);
|
||||
// 3D 모델 저장소 검색+다운로드 (Printables/MakerWorld/Thingiverse, 2026-09-23)
|
||||
this.registerSafe(modelSearchTool);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* place_search — 업종 코드·결과 포맷·툴 스코프 게이트(네트워크 없음).
|
||||
*/
|
||||
import { describe, test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { categoryCodeFor, formatPlaces, DEFAULT_CENTER } from '../src/tools/kakao-places';
|
||||
import { buildSkillToolFilter } from '../src/gateway/chat/tool-scope';
|
||||
|
||||
describe('categoryCodeFor', () => {
|
||||
test('한글 업종명과 코드 직접 지정', () => {
|
||||
assert.equal(categoryCodeFor('약국'), 'PM9');
|
||||
assert.equal(categoryCodeFor('카페'), 'CE7');
|
||||
assert.equal(categoryCodeFor('FD6'), 'FD6');
|
||||
assert.equal(categoryCodeFor('없는업종'), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatPlaces', () => {
|
||||
const docs = [{
|
||||
place_name: '온누리약국', category_name: '의료,건강 > 약국', address_name: '경북 구미시 송정동 1',
|
||||
road_address_name: '경북 구미시 송정로 1', phone: '054-000-0000', place_url: 'http://place.map.kakao.com/1',
|
||||
distance: '420', x: '128.34', y: '36.12',
|
||||
}];
|
||||
test('이름·거리·주소·전화·지도 링크를 모두 낸다', () => {
|
||||
const t = formatPlaces(docs, '경북 구미시', 12);
|
||||
assert.match(t, /기준: 경북 구미시 · 총 12건 중 1건 표시/);
|
||||
assert.match(t, /1\. 온누리약국 \(의료,건강 > 약국\) — 420m/);
|
||||
assert.match(t, /주소: 경북 구미시 송정로 1/);
|
||||
assert.match(t, /전화: 054-000-0000/);
|
||||
assert.match(t, /map\.kakao\.com\/link\/map\/%EC%98%A8%EB%88%84%EB%A6%AC%EC%95%BD%EA%B5%AD,36\.12,128\.34/);
|
||||
});
|
||||
test('1km 이상은 km로, 빈 결과는 빈 문자열', () => {
|
||||
assert.match(formatPlaces([{ ...docs[0], distance: '2300' }], 'x'), /— 2\.3km/);
|
||||
assert.equal(formatPlaces([], 'x'), '');
|
||||
});
|
||||
test('기본 기준점은 구미', () => {
|
||||
assert.match(DEFAULT_CENTER.name, /구미/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('place_search 툴 스코프', () => {
|
||||
const base = { sessionId: 's', userWorkspace: null, isSkillEnabledForUser: () => true };
|
||||
const f = (message: string, recentUserText?: string) => buildSkillToolFilter({ ...base, message, recentUserText })('place_search');
|
||||
test('장소 질문엔 열린다', () => {
|
||||
for (const m of ['구미역 근처 약국 알려줘', '현풍 맛집 추천', '가까운 주유소', '그 약국 전화번호 알려줘']) assert.equal(f(m), true, m);
|
||||
});
|
||||
test('무관한 질문엔 닫힌다', () => {
|
||||
for (const m of ['안녕', '이 코드 고쳐줘', '내일 구미 날씨 어때']) assert.equal(f(m), false, m);
|
||||
});
|
||||
test('후속 발화는 앞 턴 주제를 물려받는다', () => {
|
||||
assert.equal(f('거긴 몇 시에 열어?', '구미역 근처 약국 알려줘\n거긴 몇 시에 열어?'), true);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user