feat(chat): 앱이 붙이는 근거 텍스트(skillContext)의 길이 한도를 모델 컨텍스트에 비례해 가변(12,000~80,000자) — /api/chat/skill-context-budget, 치과 저널 앱은 지정 논문 최대 3→8편, 목록 25→80건, 초록 길이도 한도에 맞춰 배분
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
3c7b133d2a
commit
e5ab7b1eb5
5 files changed
+52
-6
No files matched your search
@@ -0,0 +1,21 @@
|
||||
// 앱이 매 질문에 붙여 보내는 근거 텍스트(skillContext)의 최대 길이 — 모델 컨텍스트 크기에 비례해 가변.
|
||||
// 컨텍스트의 일부(기본 25%)까지만 쓰고, 토큰당 글자 수는 한글·영문 혼합을 보수적으로 2.5자로 잡는다.
|
||||
// 하한은 옛 고정값(12,000자)이라 작은 컨텍스트 모델에서도 예전보다 줄지 않고, 상한은 80,000자(약 3만 토큰)다.
|
||||
// 컨텍스트 크기를 모르면(known=false) 옛 값 그대로.
|
||||
import { resolveNumCtxInfo } from '../session';
|
||||
|
||||
export const SKILL_CTX_MIN_CHARS = 12000;
|
||||
export const SKILL_CTX_MAX_CHARS = 80000;
|
||||
const SHARE = 0.25, CHARS_PER_TOKEN = 2.5;
|
||||
|
||||
export function budgetFromNumCtx(numCtx: number, known = true): number {
|
||||
if (!known || !Number.isFinite(numCtx) || numCtx <= 0) return SKILL_CTX_MIN_CHARS;
|
||||
const chars = Math.floor(numCtx * SHARE * CHARS_PER_TOKEN);
|
||||
return Math.min(SKILL_CTX_MAX_CHARS, Math.max(SKILL_CTX_MIN_CHARS, chars));
|
||||
}
|
||||
|
||||
export function skillContextBudget(): { chars: number; numCtx: number; known: boolean } {
|
||||
let info = { value: 0, known: false };
|
||||
try { info = resolveNumCtxInfo(); } catch { /* 모르면 기본값 */ }
|
||||
return { chars: budgetFromNumCtx(info.value, info.known), numCtx: info.value, known: info.known };
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { skillContextBudget } from '../chat/skill-context-budget';
|
||||
import express from 'express';
|
||||
import fs from 'fs';
|
||||
import fsp from 'fs/promises';
|
||||
@@ -20,6 +21,9 @@ export function registerChatSessionRoutes(app: express.Application): void {
|
||||
// 대조해서 확인할 것(`grep -rn "Math.random" web-ui/html/*.html | grep sessionId`).
|
||||
const APP_SESSION_PREFIXES = ['iv_', 'dt_', 'lw_', 'mn_', 'ac_', 'wt_', 'dr_', 'ws_', 'music_', 'dental_', 'dj_'];
|
||||
|
||||
// GET /api/chat/skill-context-budget — 앱이 질문마다 붙일 수 있는 근거 텍스트의 최대 글자 수(모델 컨텍스트에 비례)
|
||||
app.get('/api/chat/skill-context-budget', (_req, res) => { res.json(skillContextBudget()); });
|
||||
|
||||
// GET /api/chat/sessions — list current user's sessions from disk
|
||||
app.get('/api/chat/sessions', async (req, res) => {
|
||||
const user = (req as any).user;
|
||||
|
||||
@@ -61,6 +61,7 @@ import { registerSkillsRoutes } from './routes/routes-skills';
|
||||
import { registerCodeRoutes } from './routes/routes-code';
|
||||
import { registerClaudeFsRoutes } from './routes/routes-claude-fs';
|
||||
import { getBuildInfo, buildLabel } from './build-info';
|
||||
import { skillContextBudget } from './chat/skill-context-budget';
|
||||
import { ptyStore, ptyAppend, ptyAttach, ptyDetach } from './pty-store';
|
||||
import { ptyAccessDecision, resolveWorkshopCwd, resolvePcbCwd, allowedAutorun } from './pty-guard';
|
||||
import { ensureSharedClaudeMemory, ensureProjectClaudeMd, ensurePcbClaudeMd } from './claude-memory';
|
||||
@@ -3270,7 +3271,7 @@ app.post('/api/chat', async (req, res) => {
|
||||
// call lost the last 1,861 — the [필수] source_files rule and the entire 금지 사항 block
|
||||
// (never hand-write PPTX python, one call only, edit_presentation for edits, no spawn_agent).
|
||||
// Those are the highest-value constraints in the skill and they never reached the model.
|
||||
const SKILL_CTX_MAX = 12000;
|
||||
const SKILL_CTX_MAX = skillContextBudget().chars; // 모델 컨텍스트에 비례(12,000~80,000자)
|
||||
const _skillCtx = skillContext ? String(skillContext) : '';
|
||||
if (_skillCtx.length > SKILL_CTX_MAX) {
|
||||
console.warn(`[v2] skillContext truncated: ${_skillCtx.length} → ${SKILL_CTX_MAX} chars (tail rules lost)`);
|
||||
|
||||
@@ -463,3 +463,20 @@ describe('shouldForceUnverifiedSpecRetry — 수치 규격·찾았다 헛보고
|
||||
assert.match(p, /from memory, unverified/);
|
||||
});
|
||||
});
|
||||
|
||||
import { budgetFromNumCtx, SKILL_CTX_MIN_CHARS, SKILL_CTX_MAX_CHARS } from '../src/gateway/chat/skill-context-budget';
|
||||
describe('skillContext 길이 한도 — 모델 컨텍스트에 비례', () => {
|
||||
test('컨텍스트를 모르면 옛 값(12,000자)', () => {
|
||||
assert.equal(budgetFromNumCtx(0, false), SKILL_CTX_MIN_CHARS);
|
||||
assert.equal(budgetFromNumCtx(262144, false), SKILL_CTX_MIN_CHARS);
|
||||
});
|
||||
test('작은 컨텍스트도 옛 값보다 줄지 않는다', () => {
|
||||
assert.equal(budgetFromNumCtx(8192), SKILL_CTX_MIN_CHARS);
|
||||
assert.equal(budgetFromNumCtx(16384), SKILL_CTX_MIN_CHARS);
|
||||
});
|
||||
test('컨텍스트가 커지면 비례해 늘고 상한에서 멈춘다', () => {
|
||||
assert.equal(budgetFromNumCtx(65536), Math.floor(65536 * 0.25 * 2.5));
|
||||
assert.ok(budgetFromNumCtx(65536) > SKILL_CTX_MIN_CHARS);
|
||||
assert.equal(budgetFromNumCtx(1048576), SKILL_CTX_MAX_CHARS);
|
||||
});
|
||||
});
|
||||
@@ -114,6 +114,7 @@ const esc=s=>String(s??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'&
|
||||
let lastInfo=null, shown=[], journals=[], sel=new Set(), offset=0, total=0, busy=false, pending=false, baseQ='', subs=[];
|
||||
|
||||
async function init(){
|
||||
loadBudget();
|
||||
try{
|
||||
const d=await (await fetch('/api/dental-journals/list',{credentials:'include'})).json();
|
||||
journals=d.journals||[];
|
||||
@@ -238,7 +239,7 @@ function toggleChat(){ document.body.classList.toggle('chat-open'); $('cclose').
|
||||
function findPaper(pmid){ return shown.find(x=>x.pmid===pmid)||pinned.find(x=>x.pmid===pmid); }
|
||||
async function pinPaper(pmid){
|
||||
const a=findPaper(pmid); if(!a) return;
|
||||
if(!pinned.some(x=>x.pmid===pmid)){ if(pinned.length>=3) pinned.shift(); pinned.push(a); }
|
||||
if(!pinned.some(x=>x.pmid===pmid)){ if(pinned.length>=maxPins()) pinned.shift(); pinned.push(a); }
|
||||
renderPins();
|
||||
if(window.innerWidth<=1000 && !document.body.classList.contains('chat-open')) toggleChat();
|
||||
$('cin').focus();
|
||||
@@ -258,7 +259,9 @@ function paperLine(a,i){
|
||||
const doi=(a.doi||'').replace(/^doi:\s*/i,'');
|
||||
return `${i}. [PMID ${a.pmid}] ${a.title} — ${a.authors||'저자 미상'} — ${a.journal} ${a.year}${a.pmcid?` — ${a.pmcid}(PMC 전문 가능)`:''}${doi?` — DOI ${doi}`:''}`;
|
||||
}
|
||||
const CAPMAX=12000; // 서버 한도(SKILL_CTX_MAX)와 같다
|
||||
let CAPMAX=12000; // 서버가 받아 주는 근거 텍스트 최대 글자 수 — 모델 컨텍스트에 비례해 서버가 정한다(/api/chat/skill-context-budget)
|
||||
const maxPins=()=>Math.min(8,Math.max(3,Math.floor(CAPMAX/4500)));
|
||||
async function loadBudget(){ try{ const d=await (await fetch('/api/chat/skill-context-budget',{credentials:'include',headers:authH()})).json(); if(d&&d.chars>=12000) CAPMAX=d.chars; }catch(e){} }
|
||||
function buildContext(){
|
||||
const L=[];
|
||||
L.push('[치과 저널 검색 앱 — 논문 대화 컨텍스트]');
|
||||
@@ -275,17 +278,17 @@ function buildContext(){
|
||||
}
|
||||
if(pinned.length){
|
||||
L.push('\n▶ 사용자가 지정한 논문(대화의 주 대상):');
|
||||
const absMax=Math.min(3500,Math.floor(6500/pinned.length)); // 지정 논문이 여러 편이면 초록 길이를 나눠 목록 자리를 남긴다
|
||||
const absMax=Math.min(6000,Math.floor(CAPMAX*0.55/pinned.length)); // 지정 논문이 여러 편이면 초록 길이를 나눠 목록 자리를 남긴다
|
||||
pinned.forEach((a,i)=>{
|
||||
L.push(paperLine(a,i+1));
|
||||
const ab=absCache[a.pmid];
|
||||
L.push(ab?` 초록: ${ab.slice(0,absMax)}${ab.length>absMax?' …(초록 일부 생략 — 전체는 pubmed_fetch로)':''}`:' 초록: (아직 불러오지 못함 — 필요하면 pubmed_fetch로 PMID 조회)');
|
||||
});
|
||||
}
|
||||
const rest=shown.filter(a=>!pinned.some(p=>p.pmid===a.pmid)).slice(0,25);
|
||||
const rest=shown.filter(a=>!pinned.some(p=>p.pmid===a.pmid)).slice(0,80);
|
||||
if(rest.length){
|
||||
// 서버는 skillContext를 12,000자에서 자른다. 지정 논문(초록)이 길수록 목록이 먼저 밀리므로, 남는 자리만큼만 넣고 생략한 건수를 모델에게 알린다.
|
||||
const CAP=11500, used=L.join('\n').length, lines=[]; let acc=used+90;
|
||||
const CAP=CAPMAX-500, used=L.join('\n').length, lines=[]; let acc=used+90;
|
||||
for(let i=0;i<rest.length;i++){ const ln=paperLine(rest[i],i+1); if(acc+ln.length+1>CAP) break; lines.push(ln); acc+=ln.length+1; }
|
||||
L.push(`\n▶ 화면에 표시된 검색 결과 목록(${rest.length}건 중 ${lines.length}건 수록, 초록 없음 — 필요하면 도구로 조회):`);
|
||||
lines.forEach(x=>L.push(x));
|
||||
|
||||
Reference in new issue
Block a user