파일 첨부: CSV/텍스트/엑셀을 서버(uploads/)에 올리고 큰 파일은 미리보기+경로만 전달(컨텍스트·비용 보호), python_eval 안내 보강; OpenAI 호환 provider에서 tool 메시지 이미지를 user 메시지로 이동(Gemini 400 수정)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
b2ebd9beec
commit
46ead601ff
4 files changed
+123
-5
No files matched your search
@@ -202,7 +202,7 @@ RULES: 현재날씨/예보 → 한국은 weather_kma, 해외는 weather_openmete
|
||||
|
||||
image_ocr: `IMAGE OCR TOOL: image_read(path, lang?) → extract text from an image file via OCR. Supported formats: PNG, JPG, WEBP, BMP, TIFF. lang: "eng" (English, default), "kor" (Korean), "kor+eng" (both). Returns extracted text and confidence score. Useful for screenshots, scanned documents, and diagrams containing text.`,
|
||||
|
||||
python: `PYTHON TOOL: python_eval(code, timeout?, packages?) → execute Python code in the workspace directory. Returns stdout/stderr. timeout default 15s, max 60s. packages: comma-separated pip packages to install if missing (e.g. "numpy,pandas"). Runs in an offline Docker sandbox (no internet unless network:true; host files outside the workspace are invisible; pip install is unavailable). Preinstalled (no pip needed): numpy pandas scipy sympy scikit-learn scikit-image statsmodels pingouin lifelines numpy-financial pint | matplotlib seaborn wordcloud imageio pillow opencv | openpyxl xlsxwriter xlrd pyarrow python-docx python-pptx pdfplumber pymupdf pypdf reportlab markdown jinja2 | requests beautifulsoup4 lxml xmltodict yfinance | trimesh numpy-stl manifold3d shapely networkx ezdxf svgwrite pyclipper rtree | pyproj xarray netCDF4 haversine | mido pretty_midi soundfile | korean-lunar-calendar holidays jamo rapidfuzz phonenumbers python-stdnum qrcode tqdm pyyaml. For Korean text in matplotlib: fm.fontManager.addfont('/usr/share/fonts/truetype/nanum/NanumGothic.ttf'); plt.rc('font', family='NanumGothic'). Use for math, data analysis, CSV/JSON processing, charting (save chart to workspace file). IMAGE EDITING: input path = exact string from [IMAGE PATH for image_edit/python_eval — use EXACTLY this string: ...] hint in the message. Save output to uploads/<name>.jpg. FONT: For Korean/CJK text in Pillow (speech bubbles, watermarks, etc.) use ImageFont.truetype("/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", size) — DejaVuSans does NOT support Korean.`,
|
||||
python: `PYTHON TOOL: python_eval(code, timeout?, packages?) → execute Python code in the workspace directory. Returns stdout/stderr. timeout default 15s, max 60s. packages: comma-separated pip packages to install if missing (e.g. "numpy,pandas"). User-uploaded files are in uploads/ (read data files from disk, e.g. pandas.read_csv('uploads/x.csv') — never retype data into code). Save deliverables (xlsx/csv/png/docx) in the workspace root; they come back as download links automatically — mention each file by name. Runs in an offline Docker sandbox (no internet unless network:true; host files outside the workspace are invisible; pip install is unavailable). Preinstalled (no pip needed): numpy pandas scipy sympy scikit-learn scikit-image statsmodels pingouin lifelines numpy-financial pint | matplotlib seaborn wordcloud imageio pillow opencv | openpyxl xlsxwriter xlrd pyarrow python-docx python-pptx pdfplumber pymupdf pypdf reportlab markdown jinja2 | requests beautifulsoup4 lxml xmltodict yfinance | trimesh numpy-stl manifold3d shapely networkx ezdxf svgwrite pyclipper rtree | pyproj xarray netCDF4 haversine | mido pretty_midi soundfile | korean-lunar-calendar holidays jamo rapidfuzz phonenumbers python-stdnum qrcode tqdm pyyaml. For Korean text in matplotlib: fm.fontManager.addfont('/usr/share/fonts/truetype/nanum/NanumGothic.ttf'); plt.rc('font', family='NanumGothic'). Use for math, data analysis, CSV/JSON processing, charting (save chart to workspace file). IMAGE EDITING: input path = exact string from [IMAGE PATH for image_edit/python_eval — use EXACTLY this string: ...] hint in the message. Save output to uploads/<name>.jpg. FONT: For Korean/CJK text in Pillow (speech bubbles, watermarks, etc.) use ImageFont.truetype("/usr/share/fonts/truetype/nanum/NanumGothicBold.ttf", size) — DejaVuSans does NOT support Korean.`,
|
||||
|
||||
sqlite: `SQLITE TOOL: sqlite_query(db_path, query, write?, max_rows?) → query a SQLite .db file in the workspace. SELECT queries allowed by default. Set write=true for INSERT/UPDATE/DELETE/CREATE/DROP. Returns formatted table. db_path is relative to workspace or absolute (must be inside workspace).`,
|
||||
};
|
||||
|
||||
@@ -24,6 +24,39 @@ export interface OpenAICompatConfig {
|
||||
disableThinking?: boolean;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* OpenAI 규격(Gemini 호환 엔드포인트 포함)은 role:'tool' 메시지에 이미지 파트를 허용하지 않는다 — 텍스트만 된다.
|
||||
* 홈클로는 python_eval 차트·nvr_snapshot 같은 도구 결과 이미지를 tool 메시지의 image_url 파트로 싣는데(Ollama는 허용),
|
||||
* 2026-10-17 Gemini로 돌 때 차트를 만든 직후 "Invalid content part type: image_url"(400)로 턴이 통째로 죽었다.
|
||||
* 그래서 이미지 파트는 tool 메시지에서 빼고, 그 tool 묶음 바로 뒤에 user 메시지로 옮긴다. 한 라운드에 도구 호출이
|
||||
* 여러 개면 tool 메시지가 연속이어야 하므로 이미지는 마지막 tool 뒤에 한꺼번에 둔다.
|
||||
*/
|
||||
export function hoistToolImages(messages: ChatMessage[]): ChatMessage[] {
|
||||
const hasToolImages = messages.some(m => m.role === 'tool' && Array.isArray(m.content) && m.content.some((p: any) => p?.type === 'image_url'));
|
||||
if (!hasToolImages) return messages;
|
||||
const out: ChatMessage[] = [];
|
||||
let pending: any[] = [];
|
||||
const flush = () => {
|
||||
if (!pending.length) return;
|
||||
out.push({ role: 'user', content: [{ type: 'text', text: '[직전 도구 결과에 포함된 이미지]' }, ...pending] } as ChatMessage);
|
||||
pending = [];
|
||||
};
|
||||
for (const m of messages) {
|
||||
if (m.role === 'tool' && Array.isArray(m.content)) {
|
||||
const parts = m.content as any[];
|
||||
const text = parts.filter(p => p?.type === 'text').map(p => p.text).join('\n');
|
||||
pending.push(...parts.filter(p => p?.type === 'image_url'));
|
||||
out.push({ ...m, content: text || '(이미지 결과 — 아래 이미지 참조)' });
|
||||
continue;
|
||||
}
|
||||
if (m.role !== 'tool') flush();
|
||||
out.push(m);
|
||||
}
|
||||
flush();
|
||||
return out;
|
||||
}
|
||||
|
||||
export class OpenAICompatAdapter implements LLMProvider {
|
||||
readonly id: ProviderID;
|
||||
private config: OpenAICompatConfig;
|
||||
@@ -100,7 +133,7 @@ export class OpenAICompatAdapter implements LLMProvider {
|
||||
}
|
||||
const body: any = {
|
||||
model,
|
||||
messages: finalMessages,
|
||||
messages: hoistToolImages(finalMessages),
|
||||
temperature: options?.temperature ?? 0.25,
|
||||
// 512 was too low for reasoning models (Gemini 3.6 Flash burns budget on internal
|
||||
// "thinking"/drafting tokens before the visible answer — verified empirically: 512
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* hoistToolImages — OpenAI 규격은 tool 메시지에 이미지를 못 싣는다(Gemini 400 "Invalid content part type: image_url" 실측).
|
||||
*/
|
||||
import { test, describe } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { hoistToolImages } from '../src/providers/openai-compat-adapter';
|
||||
|
||||
const IMG = { type: 'image_url', image_url: { url: 'data:image/png;base64,AAAA' } };
|
||||
|
||||
describe('hoistToolImages', () => {
|
||||
test('tool 메시지의 이미지를 빼서 tool 뒤 user 메시지로 옮긴다', () => {
|
||||
const out = hoistToolImages([
|
||||
{ role: 'user', content: '차트 그려줘' },
|
||||
{ role: 'assistant', content: '', tool_calls: [{ id: 'c1', type: 'function', function: { name: 'python_eval', arguments: '{}' } }] } as any,
|
||||
{ role: 'tool', tool_call_id: 'c1', content: [{ type: 'text', text: 'ok' }, IMG] } as any,
|
||||
]);
|
||||
assert.equal(out.length, 4);
|
||||
assert.equal(out[2].role, 'tool');
|
||||
assert.equal(out[2].content, 'ok');
|
||||
assert.equal(out[3].role, 'user');
|
||||
assert.ok((out[3].content as any[]).some(p => p.type === 'image_url'));
|
||||
});
|
||||
test('도구 호출이 둘이면 tool 메시지는 연속, 이미지는 마지막 tool 뒤에 한 번', () => {
|
||||
const out = hoistToolImages([
|
||||
{ role: 'assistant', content: '', tool_calls: [{ id: 'a' }, { id: 'b' }] } as any,
|
||||
{ role: 'tool', tool_call_id: 'a', content: [{ type: 'text', text: 'A' }, IMG] } as any,
|
||||
{ role: 'tool', tool_call_id: 'b', content: [{ type: 'text', text: 'B' }, IMG] } as any,
|
||||
{ role: 'user', content: '다음' },
|
||||
]);
|
||||
assert.deepEqual(out.map(m => m.role), ['assistant', 'tool', 'tool', 'user', 'user']);
|
||||
assert.equal((out[3].content as any[]).filter(p => p.type === 'image_url').length, 2);
|
||||
});
|
||||
test('이미지 없으면 그대로(동일 참조)', () => {
|
||||
const msgs = [{ role: 'user', content: 'hi' }, { role: 'tool', content: 'text only' }] as any;
|
||||
assert.equal(hoistToolImages(msgs), msgs);
|
||||
});
|
||||
});
|
||||
+51
-3
@@ -401,6 +401,41 @@ function handleImageUpload(input) {
|
||||
.catch(function(e) { alert('Upload error: ' + e.message); });
|
||||
}
|
||||
|
||||
// ── 큰 첨부 처리 ────────────────────────────────────────────────────────────
|
||||
// 예전엔 CSV·텍스트·엑셀의 전체 내용을 사용자 메시지에 그대로 붙였다. 수 MB짜리 CSV는 컨텍스트를 터뜨리고
|
||||
// (유료 모델이면 매 호출 비용), CSV는 서버에 올리지도 않아서 python_eval이 파일 경로로 읽을 수도 없었다.
|
||||
// 이제 모든 데이터 파일을 서버(uploads/)에 올리고, 작으면 본문까지, 크면 미리보기+경로만 모델에게 준다.
|
||||
var ATTACH_INLINE_MAX = 30000; // 이 글자 수 이하면 전체 본문을 메시지에 싣는다
|
||||
var ATTACH_PREVIEW_ROWS = 25; // 넘으면 앞 N행(줄)만
|
||||
|
||||
function uploadAttachmentFile(file) {
|
||||
var f = new FormData();
|
||||
f.append('file', file);
|
||||
return fetch('/api/upload/file', { method: 'POST', headers: authHeaders(), body: f })
|
||||
.then(function(r) { return r.json(); }).catch(function() { return {}; });
|
||||
}
|
||||
|
||||
function attachPathNote(d) {
|
||||
if (!(d && d.success && d.path)) return '';
|
||||
return '\n[서버 저장 경로: ' + d.path + ' — 분석·가공은 python_eval에서 이 상대경로로 읽으세요(예: pandas.read_csv("' + d.path + '")). 데이터를 답변에 다시 옮겨 적지 마세요.]';
|
||||
}
|
||||
|
||||
function stageTextFile(file, text, lang, type) {
|
||||
uploadAttachmentFile(file).then(function(d) {
|
||||
var big = text.length > ATTACH_INLINE_MAX;
|
||||
var body = text;
|
||||
var note = '';
|
||||
if (big) {
|
||||
var lines = text.split(/\r?\n/);
|
||||
var keep = lang === 'csv' ? ATTACH_PREVIEW_ROWS + 1 : 60; // csv는 헤더 + 25행
|
||||
body = lines.slice(0, keep).join('\n');
|
||||
note = '\n(큰 파일 — 전체 약 ' + lines.length.toLocaleString() + '줄, ' + Math.round(text.length / 1024).toLocaleString() + 'KB 중 앞 ' + keep + '줄만 표시)';
|
||||
}
|
||||
var fileUrl = (d && d.success && d.path) ? '/api/files/' + d.path : null;
|
||||
stageAttachment(file.name, fileUrl, '**[파일: ' + file.name + ']**' + attachPathNote(d) + note + '\n```' + lang + '\n' + body + '\n```', type);
|
||||
});
|
||||
}
|
||||
|
||||
// ── 파일 첨부 (이미지·PDF·Excel·txt·csv 등) ─────────────────────────────────
|
||||
function handleFileUpload(input) {
|
||||
var file = input.files && input.files[0];
|
||||
@@ -432,7 +467,7 @@ function handleFileUpload(input) {
|
||||
var r1 = new FileReader();
|
||||
r1.onload = function(e) {
|
||||
var ext = name.split('.').pop();
|
||||
stageAttachment(file.name, null, '**[파일: ' + file.name + ']**\n```' + ext + '\n' + e.target.result + '\n```', 'text');
|
||||
stageTextFile(file, e.target.result, ext, 'text');
|
||||
};
|
||||
r1.readAsText(file, 'UTF-8');
|
||||
|
||||
@@ -440,7 +475,7 @@ function handleFileUpload(input) {
|
||||
} else if (/\.csv$/.test(name)) {
|
||||
var r2 = new FileReader();
|
||||
r2.onload = function(e) {
|
||||
stageAttachment(file.name, null, '**[파일: ' + file.name + ']**\n```csv\n' + e.target.result + '\n```', 'csv');
|
||||
stageTextFile(file, e.target.result, 'csv', 'csv');
|
||||
};
|
||||
r2.readAsText(file, 'UTF-8');
|
||||
|
||||
@@ -458,8 +493,10 @@ function handleFileUpload(input) {
|
||||
var wb = XLSX.read(e.target.result, { type: 'array' });
|
||||
var markdownContent = '**[파일: ' + xlsxFile.name + ']**\n\n';
|
||||
var previewHtml = '';
|
||||
var sheetRows = [];
|
||||
wb.SheetNames.forEach(function(sn) {
|
||||
var rows = XLSX.utils.sheet_to_json(wb.Sheets[sn], { header: 1 });
|
||||
sheetRows.push({ sn: sn, rows: rows });
|
||||
markdownContent += '### ' + sn + '\n';
|
||||
rows.forEach(function(row) { markdownContent += '| ' + row.map(function(c) { return String(c ?? ''); }).join(' | ') + ' |\n'; });
|
||||
markdownContent += '\n';
|
||||
@@ -478,7 +515,18 @@ function handleFileUpload(input) {
|
||||
});
|
||||
xlsxUploadPromise.then(function(d) {
|
||||
var fileUrl = (d.success && d.path) ? '/api/files/' + d.path : null;
|
||||
stageAttachment(xlsxFile.name, fileUrl, markdownContent, 'excel', { excelPreviewHtml: previewHtml });
|
||||
var aiMarkdown = markdownContent;
|
||||
if (aiMarkdown.length > ATTACH_INLINE_MAX) { // 큰 통합문서: 시트별 앞 N행만
|
||||
aiMarkdown = '**[파일: ' + xlsxFile.name + ']**\n\n';
|
||||
sheetRows.forEach(function(sh) {
|
||||
var cols = sh.rows.length ? sh.rows[0].length : 0;
|
||||
aiMarkdown += '### ' + sh.sn + ' (전체 ' + sh.rows.length.toLocaleString() + '행 × ' + cols + '열 중 앞 ' + ATTACH_PREVIEW_ROWS + '행만 표시)\n';
|
||||
sh.rows.slice(0, ATTACH_PREVIEW_ROWS).forEach(function(row) { aiMarkdown += '| ' + row.map(function(c) { return String(c ?? ''); }).join(' | ') + ' |\n'; });
|
||||
aiMarkdown += '\n';
|
||||
});
|
||||
}
|
||||
aiMarkdown = aiMarkdown.replace('**\n\n', '**' + attachPathNote(d) + '\n\n'); // 경로 안내를 제목 바로 아래에
|
||||
stageAttachment(xlsxFile.name, fileUrl, aiMarkdown, 'excel', { excelPreviewHtml: previewHtml });
|
||||
});
|
||||
} catch(err) { alert('Excel 파싱 오류: ' + err.message); }
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user