mirror of
https://github.com/dtzp555-max/olp.git
synced 2026-07-21 21:15:10 +00:00
feat(phase-1): land IR + plugin loader + server skeleton (D3)
Phase 1 Day 1. First executable code lands. Zero providers wired yet
(per ALIGNMENT.md "v0.1 ships 0 Enabled Providers"); the server starts
clean and POST /v1/chat/completions returns 503 with no_enabled_provider.
Files added:
lib/ir/types.mjs - IR v1.0 schema + validators (ADR 0003)
lib/ir/openai-to-ir.mjs - OpenAI Chat Completions to IR
lib/ir/ir-to-openai.mjs - IR chunks to OpenAI SSE / non-stream
lib/providers/base.mjs - Provider contract + validateProvider + ProviderError
lib/providers/index.mjs - Static empty registry stub (ADR 0002)
server.mjs - HTTP listener with createOlpServer factory + main guard
test-features.mjs - 61 tests across 7 suites (IR / provider / HTTP)
Files modified:
package.json - main and scripts.start/test added back; targets now exist.
Authority citations:
IR fields and translation direction: ADR 0003 sections Decision and
Translation direction model.
Provider contract (9 fields): ADR 0002 section Provider contract v1.0
interface.
Entry surface routes (health, v1/models, v1/chat/completions): OLP v0.1
spec section 4.1 single-protocol entry; ALIGNMENT.md Authority 2.
Zero-Enabled-Providers behaviour: ALIGNMENT.md Provider Inventory.
Architectural decisions worth recording:
1. server.mjs uses a createOlpServer factory plus an import.meta.url
main guard. The factory returns an unbound http.Server; only the
main-script invocation calls .listen(). Tests import the real
server.mjs and exercise the real router. No parallel implementation
in the test file.
This pattern was a fold-in from the orchestration step. The initial
sonnet draft put a top-level server.listen call in server.mjs, which
forced test-features.mjs to reimplement the router inline (a false-
confidence trap because the real server logic would never be tested).
Refactored before reviewer dispatch.
2. lib/providers/index.mjs ships an empty STATIC_REGISTRY array, not a
placeholder with dummy entries. ALIGNMENT.md Provider Inventory says
v0.1 ships zero Enabled Providers; the registry honors that exactly.
Phase 1 Day 2 adds the first import (Anthropic) when its plugin lands.
3. BadRequestError lives in openai-to-ir.mjs and ProviderError in
base.mjs. Reviewer suggested relocating to a shared lib/errors.mjs
once the count exceeds two; deferred to Phase 1 Day 2 to ship with
the third typed error class.
4. contractVersion: '1.0' on each provider plugin: not enforced at D3
because no providers exist yet. Reviewer flagged for Phase 1 Day 2
tightening when the first provider lands.
Reviewer chain (Iron Rule 10):
Initial implementer: sonnet (general-purpose).
Refactor (createOlpServer + main guard) by the orchestrator after
catching the inline-router parallel-implementation issue.
Fresh-context reviewer: opus (ecc:code-reviewer). Verdict
APPROVE_WITH_MINOR.
Reviewer's two non-blocking findings folded in:
F1: removed unused createServer import from test-features.mjs line 12,
left over from the refactor.
F2: replaced finish_reason value 'error' with 'stop' in both the
streaming error chunk path (lib/ir/ir-to-openai.mjs line 72) and
the non-streaming error aggregation path (lib/ir/ir-to-openai.mjs
line 153). The 'error' value is not in OpenAI's documented
finish_reason enum (stop / length / tool_calls / content_filter /
function_call / null), so emitting it would violate ALIGNMENT.md
Rule 2 (b). Provider errors are now surfaced via a top-level
response.error object plus an inline content marker. The matching
test assertion at test-features.mjs line 325 was updated to verify
finish_reason stays within the OpenAI enum.
Note on the F2 fold-in:
Reviewer pointed only at the streaming path (line 72). After applying
that fix I ran grep across lib/ and test-features.mjs for the same
invention pattern and caught a second hit at line 153 (non-streaming
aggregation). This is the "fold-in must grep the full repo, not only
the file the reviewer named" discipline from
~/.cc-rules/memory/feedback/evidence_first_under_speed_pressure.md.
Both hits are fixed in this commit.
Verification:
node --check on all 7 new files plus modified package.json plus
server.mjs plus lib/ir/ir-to-openai.mjs - all clean.
npm test - 61/61 pass in 209ms, no flakes, no skipped.
OLP_PORT=14001 node server.mjs followed by curl /health returns
proper JSON; curl /v1/models returns 200 empty list; server shuts
down cleanly on signal.
grep "finish_reason.*error" returns zero hits across lib/ and tests.
Co-Authored-By: Claude Opus 4.7 (noreply@anthropic.com)
This commit is contained in:
co-authored by
Claude Opus 4.7 (noreply@anthropic.com)
parent
dff428f3d0
commit
e2e67de23a
@@ -0,0 +1,198 @@
|
||||
/**
|
||||
* lib/ir/ir-to-openai.mjs — IR v1.0 → OpenAI Chat Completions response translation
|
||||
*
|
||||
* Authority: ADR 0003 § "Translation direction model" (symmetric)
|
||||
* Entry-surface authority: OpenAI Chat Completions API response shape
|
||||
* https://platform.openai.com/docs/api-reference/chat/object
|
||||
* https://platform.openai.com/docs/api-reference/chat/streaming
|
||||
*
|
||||
* Produces OpenAI-shaped responses from IR response chunks so that the
|
||||
* entry surface (server.mjs) can emit them to clients without knowing
|
||||
* which provider generated them.
|
||||
*/
|
||||
|
||||
import { randomBytes } from 'node:crypto';
|
||||
|
||||
// ── ID generation ─────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generates a random chat-completion request ID.
|
||||
* OpenAI format: chatcmpl-<alphanumeric>
|
||||
* @returns {string}
|
||||
*/
|
||||
export function generateRequestId() {
|
||||
return `chatcmpl-${randomBytes(12).toString('base64url')}`;
|
||||
}
|
||||
|
||||
// ── Streaming translation ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Converts a single IRResponseChunk to an OpenAI SSE event string.
|
||||
*
|
||||
* Per OpenAI streaming spec, each chunk is a `chat.completion.chunk` object
|
||||
* with a `choices[0].delta` field.
|
||||
*
|
||||
* @param {import('./types.mjs').IRResponseChunk} irChunk
|
||||
* @param {string} requestId - from generateRequestId()
|
||||
* @param {string} model - the model string from the IR request
|
||||
* @returns {string} SSE line in the form `data: {...}\n\n`
|
||||
*/
|
||||
export function irChunkToOpenAISSE(irChunk, requestId, model) {
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
|
||||
if (irChunk.type === 'stop') {
|
||||
const chunk = {
|
||||
id: requestId,
|
||||
object: 'chat.completion.chunk',
|
||||
created,
|
||||
model,
|
||||
choices: [{
|
||||
index: 0,
|
||||
delta: {},
|
||||
finish_reason: irChunk.finish_reason ?? 'stop',
|
||||
}],
|
||||
};
|
||||
// Include usage if the provider surfaced token counts on the final chunk
|
||||
if (irChunk.usage) {
|
||||
chunk.usage = irChunk.usage;
|
||||
}
|
||||
return `data: ${JSON.stringify(chunk)}\n\n`;
|
||||
}
|
||||
|
||||
if (irChunk.type === 'error') {
|
||||
// SSE error chunk. ALIGNMENT.md Rule 2 (b) forbids inventing
|
||||
// `finish_reason` values not in OpenAI's enum
|
||||
// (https://platform.openai.com/docs/api-reference/chat/streaming
|
||||
// enumerates: stop, length, tool_calls, content_filter, function_call,
|
||||
// null). Surface the error via the top-level `error` object and use
|
||||
// finish_reason: 'stop' on the choice — clients that respect the
|
||||
// enum see a valid terminator; clients that read the `error` field
|
||||
// see the failure detail.
|
||||
const chunk = {
|
||||
id: requestId,
|
||||
object: 'chat.completion.chunk',
|
||||
created,
|
||||
model,
|
||||
choices: [{
|
||||
index: 0,
|
||||
delta: { content: '' },
|
||||
finish_reason: 'stop',
|
||||
}],
|
||||
error: { message: irChunk.error ?? 'Unknown provider error', type: 'provider_error' },
|
||||
};
|
||||
return `data: ${JSON.stringify(chunk)}\n\n`;
|
||||
}
|
||||
|
||||
// type === 'delta'
|
||||
const delta = {};
|
||||
if (irChunk.role !== undefined) {
|
||||
delta.role = irChunk.role;
|
||||
}
|
||||
if (typeof irChunk.content === 'string' && irChunk.content !== '') {
|
||||
delta.content = irChunk.content;
|
||||
} else if (irChunk.content === '') {
|
||||
// Empty string delta is valid — pass through (first chunk often role-only + empty content)
|
||||
delta.content = '';
|
||||
}
|
||||
if (Array.isArray(irChunk.tool_calls) && irChunk.tool_calls.length > 0) {
|
||||
delta.tool_calls = irChunk.tool_calls;
|
||||
}
|
||||
|
||||
const chunk = {
|
||||
id: requestId,
|
||||
object: 'chat.completion.chunk',
|
||||
created,
|
||||
model,
|
||||
choices: [{
|
||||
index: 0,
|
||||
delta,
|
||||
finish_reason: null,
|
||||
}],
|
||||
};
|
||||
|
||||
return `data: ${JSON.stringify(chunk)}\n\n`;
|
||||
}
|
||||
|
||||
/** SSE stream terminator per OpenAI spec */
|
||||
export const SSE_DONE = 'data: [DONE]\n\n';
|
||||
|
||||
// ── Non-streaming translation ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Assembles a non-streaming OpenAI chat.completion object from an array of
|
||||
* IR response chunks (all chunks already collected from the provider).
|
||||
*
|
||||
* @param {import('./types.mjs').IRResponseChunk[]} irChunks
|
||||
* @param {string} requestId
|
||||
* @param {string} model
|
||||
* @returns {object} OpenAI chat.completion object
|
||||
*/
|
||||
export function irResponseToOpenAINonStream(irChunks, requestId, model) {
|
||||
let content = '';
|
||||
let finish_reason = 'stop';
|
||||
let usage = null;
|
||||
let errorChunk = null;
|
||||
const tool_calls = [];
|
||||
|
||||
for (const chunk of irChunks) {
|
||||
if (chunk.type === 'delta') {
|
||||
if (typeof chunk.content === 'string') {
|
||||
content += chunk.content;
|
||||
}
|
||||
if (Array.isArray(chunk.tool_calls)) {
|
||||
tool_calls.push(...chunk.tool_calls);
|
||||
}
|
||||
} else if (chunk.type === 'stop') {
|
||||
if (chunk.finish_reason) {
|
||||
finish_reason = chunk.finish_reason;
|
||||
}
|
||||
if (chunk.usage) {
|
||||
usage = chunk.usage;
|
||||
}
|
||||
} else if (chunk.type === 'error') {
|
||||
// Surface provider errors via the top-level `error` annotation on the
|
||||
// response object below + an inline content marker. `finish_reason`
|
||||
// stays 'stop' because ALIGNMENT.md Rule 2 (b) forbids inventing
|
||||
// enum values OpenAI's spec does not define
|
||||
// (https://platform.openai.com/docs/api-reference/chat/object —
|
||||
// finish_reason ∈ {stop, length, tool_calls, content_filter,
|
||||
// function_call, null}).
|
||||
content += chunk.error ? `[provider error: ${chunk.error}]` : '[provider error]';
|
||||
errorChunk = chunk;
|
||||
}
|
||||
}
|
||||
|
||||
const message = {
|
||||
role: 'assistant',
|
||||
content: content || null,
|
||||
};
|
||||
if (tool_calls.length > 0) {
|
||||
message.tool_calls = tool_calls;
|
||||
if (!content) message.content = null;
|
||||
}
|
||||
|
||||
const response = {
|
||||
id: requestId,
|
||||
object: 'chat.completion',
|
||||
created: Math.floor(Date.now() / 1000),
|
||||
model,
|
||||
choices: [{
|
||||
index: 0,
|
||||
message,
|
||||
finish_reason,
|
||||
}],
|
||||
};
|
||||
|
||||
if (usage) {
|
||||
response.usage = usage;
|
||||
}
|
||||
|
||||
if (errorChunk) {
|
||||
response.error = {
|
||||
message: errorChunk.error ?? 'Unknown provider error',
|
||||
type: 'provider_error',
|
||||
};
|
||||
}
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* lib/ir/openai-to-ir.mjs — OpenAI Chat Completions → IR v1.0 translation
|
||||
*
|
||||
* Authority: ADR 0003 § "Translation direction model" and § "Required/Optional fields"
|
||||
* Entry-surface authority: OpenAI Chat Completions API
|
||||
* https://platform.openai.com/docs/api-reference/chat/create
|
||||
*
|
||||
* This is the entry adapter — the single point where an OpenAI-shaped request
|
||||
* is normalized into the IR. Provider plugins never see the OpenAI shape;
|
||||
* they receive only the IR (ADR 0003 § "IR is not exposed externally").
|
||||
*/
|
||||
|
||||
import { IR_VERSION, validateIRRequest } from './types.mjs';
|
||||
|
||||
// ── Custom error ──────────────────────────────────────────────────────────
|
||||
|
||||
export class BadRequestError extends Error {
|
||||
/** @param {string} message */
|
||||
constructor(message) {
|
||||
super(message);
|
||||
this.name = 'BadRequestError';
|
||||
this.statusCode = 400;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Role normalization ────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* OpenAI deprecated role='function' in favour of role='tool'.
|
||||
* Per ADR 0003, IR supports system/user/assistant/tool.
|
||||
* @param {string} role
|
||||
* @returns {string}
|
||||
*/
|
||||
function normalizeRole(role) {
|
||||
if (role === 'function') return 'tool';
|
||||
return role;
|
||||
}
|
||||
|
||||
// ── Message translation ───────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @param {object} msg - an OpenAI message object
|
||||
* @returns {import('./types.mjs').IRMessage}
|
||||
*/
|
||||
function translateMessage(msg) {
|
||||
if (!msg || typeof msg !== 'object') {
|
||||
throw new BadRequestError('Each message must be an object');
|
||||
}
|
||||
|
||||
const irMsg = {
|
||||
role: normalizeRole(msg.role),
|
||||
content: msg.content ?? '',
|
||||
};
|
||||
|
||||
// content can be null for tool/function calls in OpenAI shape — normalise to ''
|
||||
if (irMsg.content === null) {
|
||||
irMsg.content = '';
|
||||
}
|
||||
|
||||
if (msg.name !== undefined) {
|
||||
irMsg.name = String(msg.name);
|
||||
}
|
||||
if (msg.tool_call_id !== undefined) {
|
||||
irMsg.tool_call_id = String(msg.tool_call_id);
|
||||
}
|
||||
// OpenAI also uses function_call (deprecated) — treat as equivalent to tool_calls
|
||||
if (Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
|
||||
irMsg.tool_calls = msg.tool_calls.map(tc => ({
|
||||
id: tc.id,
|
||||
type: 'function',
|
||||
function: {
|
||||
name: tc.function?.name ?? '',
|
||||
arguments: tc.function?.arguments ?? '',
|
||||
},
|
||||
}));
|
||||
} else if (msg.function_call && typeof msg.function_call === 'object') {
|
||||
// Deprecated OpenAI function_call field — map to single tool_calls entry
|
||||
irMsg.tool_calls = [{
|
||||
id: `fc-${Date.now()}`,
|
||||
type: 'function',
|
||||
function: {
|
||||
name: msg.function_call.name ?? '',
|
||||
arguments: msg.function_call.arguments ?? '',
|
||||
},
|
||||
}];
|
||||
}
|
||||
|
||||
return irMsg;
|
||||
}
|
||||
|
||||
// ── Tool definitions ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @param {object[]} tools - OpenAI tools array
|
||||
* @returns {import('./types.mjs').IRToolDefinition[]}
|
||||
*/
|
||||
function translateTools(tools) {
|
||||
if (!Array.isArray(tools)) return [];
|
||||
return tools.map((t, i) => {
|
||||
if (t.type !== 'function' || !t.function) {
|
||||
throw new BadRequestError(`tools[${i}]: only type='function' tools are supported in IR v1.0`);
|
||||
}
|
||||
return {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: t.function.name,
|
||||
...(t.function.description !== undefined && { description: t.function.description }),
|
||||
...(t.function.parameters !== undefined && { parameters: t.function.parameters }),
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// ── Main translator ───────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Translates an OpenAI Chat Completions request body into IR v1.0.
|
||||
*
|
||||
* Throws BadRequestError on validation failure.
|
||||
*
|
||||
* @param {object} openAIRequest - parsed JSON body from POST /v1/chat/completions
|
||||
* @returns {import('./types.mjs').IRRequest}
|
||||
*/
|
||||
export function openAIToIR(openAIRequest) {
|
||||
if (!openAIRequest || typeof openAIRequest !== 'object') {
|
||||
throw new BadRequestError('Request body must be a JSON object');
|
||||
}
|
||||
|
||||
if (!openAIRequest.model || typeof openAIRequest.model !== 'string') {
|
||||
throw new BadRequestError('Request body must include a non-empty "model" string');
|
||||
}
|
||||
|
||||
if (!Array.isArray(openAIRequest.messages) || openAIRequest.messages.length === 0) {
|
||||
throw new BadRequestError('Request body must include a non-empty "messages" array');
|
||||
}
|
||||
|
||||
/** @type {import('./types.mjs').IRRequest} */
|
||||
const ir = {
|
||||
irVersion: IR_VERSION,
|
||||
model: openAIRequest.model,
|
||||
stream: openAIRequest.stream === true,
|
||||
messages: openAIRequest.messages.map((m, i) => {
|
||||
try {
|
||||
return translateMessage(m);
|
||||
} catch (e) {
|
||||
throw new BadRequestError(`messages[${i}]: ${e.message}`);
|
||||
}
|
||||
}),
|
||||
};
|
||||
|
||||
// Optional numeric fields — type-coerce if needed
|
||||
if (openAIRequest.max_tokens !== undefined && openAIRequest.max_tokens !== null) {
|
||||
const v = Number(openAIRequest.max_tokens);
|
||||
if (!Number.isInteger(v) || v <= 0) {
|
||||
throw new BadRequestError('max_tokens must be a positive integer');
|
||||
}
|
||||
ir.max_tokens = v;
|
||||
}
|
||||
|
||||
if (openAIRequest.temperature !== undefined && openAIRequest.temperature !== null) {
|
||||
const v = Number(openAIRequest.temperature);
|
||||
if (isNaN(v) || v < 0 || v > 2) {
|
||||
throw new BadRequestError('temperature must be a number in [0, 2]');
|
||||
}
|
||||
ir.temperature = v;
|
||||
}
|
||||
|
||||
if (openAIRequest.top_p !== undefined && openAIRequest.top_p !== null) {
|
||||
const v = Number(openAIRequest.top_p);
|
||||
if (isNaN(v) || v < 0 || v > 1) {
|
||||
throw new BadRequestError('top_p must be a number in [0, 1]');
|
||||
}
|
||||
ir.top_p = v;
|
||||
}
|
||||
|
||||
if (openAIRequest.stop !== undefined && openAIRequest.stop !== null) {
|
||||
if (typeof openAIRequest.stop !== 'string' && !Array.isArray(openAIRequest.stop)) {
|
||||
throw new BadRequestError('stop must be a string or array of strings');
|
||||
}
|
||||
ir.stop = openAIRequest.stop;
|
||||
}
|
||||
|
||||
if (openAIRequest.tools !== undefined && openAIRequest.tools !== null) {
|
||||
ir.tools = translateTools(openAIRequest.tools);
|
||||
}
|
||||
|
||||
if (openAIRequest.tool_choice !== undefined && openAIRequest.tool_choice !== null) {
|
||||
ir.tool_choice = openAIRequest.tool_choice;
|
||||
}
|
||||
|
||||
if (openAIRequest.response_format !== undefined && openAIRequest.response_format !== null) {
|
||||
ir.response_format = openAIRequest.response_format;
|
||||
}
|
||||
|
||||
// Validate the constructed IR — belt-and-suspenders
|
||||
const { valid, errors } = validateIRRequest(ir);
|
||||
if (!valid) {
|
||||
throw new BadRequestError(`IR validation failed: ${errors.join('; ')}`);
|
||||
}
|
||||
|
||||
return ir;
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* lib/ir/types.mjs — IR v1.0 type definitions and validators
|
||||
*
|
||||
* Authority: ADR 0003 § "Required fields" and "Optional fields"
|
||||
* The IR is OLP-internal; there is no external IR endpoint.
|
||||
* Per ADR 0003, the IR encodes the common subset that every provider
|
||||
* plugin can consume, with lossy edges documented per-provider.
|
||||
*/
|
||||
|
||||
// ── Constants ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const IR_VERSION = '1.0';
|
||||
|
||||
/** Per ADR 0003 § Required fields. role='function' is OpenAI-deprecated; openai-to-ir.mjs maps it to 'tool'. */
|
||||
export const VALID_ROLES = ['system', 'user', 'assistant', 'tool'];
|
||||
|
||||
// ── JSDoc typedefs ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @typedef {Object} IRToolCall
|
||||
* @property {string} id
|
||||
* @property {'function'} type
|
||||
* @property {{ name: string, arguments: string }} function
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} IRMessage
|
||||
* @property {'system'|'user'|'assistant'|'tool'} role
|
||||
* @property {string|Array<{type:string,[key:string]:any}>} content
|
||||
* @property {string} [name]
|
||||
* @property {IRToolCall[]} [tool_calls]
|
||||
* @property {string} [tool_call_id]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} IRToolDefinition
|
||||
* @property {'function'} type
|
||||
* @property {{ name: string, description?: string, parameters?: object }} function
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} IRRequest
|
||||
* @property {string} irVersion - always IR_VERSION
|
||||
* @property {IRMessage[]} messages
|
||||
* @property {string} model
|
||||
* @property {boolean} stream
|
||||
* @property {number} [max_tokens]
|
||||
* @property {number} [temperature]
|
||||
* @property {number} [top_p]
|
||||
* @property {string|string[]} [stop]
|
||||
* @property {IRToolDefinition[]} [tools]
|
||||
* @property {string|object} [tool_choice]
|
||||
* @property {object} [response_format]
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {Object} IRResponseChunk
|
||||
* @property {'delta'|'stop'|'error'} type
|
||||
* @property {string} [content] - present when type==='delta'
|
||||
* @property {string} [role] - present on first delta
|
||||
* @property {IRToolCall[]} [tool_calls] - present when provider emits tool-use in stream
|
||||
* @property {string} [finish_reason] - present when type==='stop'
|
||||
* @property {string} [error] - present when type==='error'
|
||||
* @property {Object} [usage]
|
||||
* @property {number} [usage.prompt_tokens]
|
||||
* @property {number} [usage.completion_tokens]
|
||||
* @property {number} [usage.total_tokens]
|
||||
*/
|
||||
|
||||
// ── Validators ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @param {*} obj
|
||||
* @returns {{ valid: boolean, errors: string[] }}
|
||||
*/
|
||||
export function validateIRMessage(obj) {
|
||||
const errors = [];
|
||||
if (obj === null || typeof obj !== 'object') {
|
||||
errors.push('message must be an object');
|
||||
return { valid: false, errors };
|
||||
}
|
||||
if (!VALID_ROLES.includes(obj.role)) {
|
||||
errors.push(`role must be one of ${VALID_ROLES.join('|')}, got ${JSON.stringify(obj.role)}`);
|
||||
}
|
||||
if (obj.content === undefined || obj.content === null) {
|
||||
errors.push('content is required');
|
||||
} else if (typeof obj.content !== 'string' && !Array.isArray(obj.content)) {
|
||||
errors.push('content must be a string or array of content parts');
|
||||
}
|
||||
if (obj.name !== undefined && typeof obj.name !== 'string') {
|
||||
errors.push('name must be a string when present');
|
||||
}
|
||||
if (obj.tool_call_id !== undefined && typeof obj.tool_call_id !== 'string') {
|
||||
errors.push('tool_call_id must be a string when present');
|
||||
}
|
||||
if (obj.tool_calls !== undefined) {
|
||||
if (!Array.isArray(obj.tool_calls)) {
|
||||
errors.push('tool_calls must be an array when present');
|
||||
}
|
||||
}
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {*} obj
|
||||
* @returns {{ valid: boolean, errors: string[] }}
|
||||
*/
|
||||
export function validateIRRequest(obj) {
|
||||
const errors = [];
|
||||
if (obj === null || typeof obj !== 'object') {
|
||||
errors.push('IR request must be an object');
|
||||
return { valid: false, errors };
|
||||
}
|
||||
|
||||
// Required: messages
|
||||
if (!Array.isArray(obj.messages)) {
|
||||
errors.push('messages must be an array');
|
||||
} else {
|
||||
obj.messages.forEach((m, i) => {
|
||||
const r = validateIRMessage(m);
|
||||
if (!r.valid) {
|
||||
r.errors.forEach(e => errors.push(`messages[${i}]: ${e}`));
|
||||
}
|
||||
});
|
||||
if (obj.messages.length === 0) {
|
||||
errors.push('messages must not be empty');
|
||||
}
|
||||
}
|
||||
|
||||
// Required: model
|
||||
if (typeof obj.model !== 'string' || obj.model.trim() === '') {
|
||||
errors.push('model must be a non-empty string');
|
||||
}
|
||||
|
||||
// Required: stream
|
||||
if (typeof obj.stream !== 'boolean') {
|
||||
errors.push('stream must be a boolean');
|
||||
}
|
||||
|
||||
// Optional: max_tokens
|
||||
if (obj.max_tokens !== undefined && (!Number.isInteger(obj.max_tokens) || obj.max_tokens <= 0)) {
|
||||
errors.push('max_tokens must be a positive integer when present');
|
||||
}
|
||||
|
||||
// Optional: temperature [0,2]
|
||||
if (obj.temperature !== undefined) {
|
||||
if (typeof obj.temperature !== 'number' || obj.temperature < 0 || obj.temperature > 2) {
|
||||
errors.push('temperature must be a number in [0,2] when present');
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: top_p [0,1]
|
||||
if (obj.top_p !== undefined) {
|
||||
if (typeof obj.top_p !== 'number' || obj.top_p < 0 || obj.top_p > 1) {
|
||||
errors.push('top_p must be a number in [0,1] when present');
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: stop
|
||||
if (obj.stop !== undefined) {
|
||||
if (typeof obj.stop !== 'string' && !Array.isArray(obj.stop)) {
|
||||
errors.push('stop must be a string or array of strings when present');
|
||||
}
|
||||
}
|
||||
|
||||
// Optional: tools
|
||||
if (obj.tools !== undefined && !Array.isArray(obj.tools)) {
|
||||
errors.push('tools must be an array when present');
|
||||
}
|
||||
|
||||
return { valid: errors.length === 0, errors };
|
||||
}
|
||||
Reference in New Issue
Block a user