@veris-ai/sdk
Version:
A TypeScript package for Veris AI tools
213 lines • 9.42 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.veris = exports.ToolMock = void 0;
const axios_1 = __importDefault(require("axios"));
const zod_to_json_schema_1 = require("zod-to-json-schema");
const types_1 = require("./types");
class ToolMock {
_sessionId;
_threadId;
_baseUrl;
get sessionId() {
return this._sessionId || null;
}
get threadId() {
return this._threadId || null;
}
get baseUrl() {
return this._baseUrl || null;
}
setSessionId(sessionId) {
this._sessionId = sessionId;
}
setThreadId(threadId) {
this._threadId = threadId;
}
setBaseUrl(url) {
this._baseUrl = url;
}
parseToken(token) {
try {
// Decode base64 JSON token
const decoded = Buffer.from(token, 'base64').toString('utf-8');
const tokenData = JSON.parse(decoded);
if (typeof tokenData !== 'object' || tokenData === null) {
throw new Error('Token must decode to a JSON object');
}
if (!('session_id' in tokenData)) {
throw new Error("Token must contain 'session_id' field");
}
if (!('thread_id' in tokenData)) {
throw new Error("Token must contain 'thread_id' field");
}
this.setSessionId(tokenData.session_id);
this.setThreadId(tokenData.thread_id);
this.setBaseUrl(tokenData.api_url);
console.log(`Session ID set to ${this._sessionId}, Thread ID set to ${this._threadId}, Base URL set to ${this._baseUrl} - mocking enabled`);
}
catch (error) {
throw new Error(`Invalid token format: ${error instanceof Error ? error.message : String(error)}`);
}
}
clearSessionId() {
this._sessionId = undefined;
}
clearThreadId() {
this._threadId = undefined;
}
clearBaseUrl() {
this._baseUrl = undefined;
}
clearContext() {
this.clearSessionId();
this.clearThreadId();
this.clearBaseUrl();
console.log('Session ID and Thread ID cleared - mocking disabled');
}
createMockPayload(functionName, description, args, parametersSchema, outputSchema, mode = 'tool', expectsResponse, cacheResponse) {
const returnType = outputSchema ? JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(outputSchema)) : 'any';
// Convert arguments to Python SDK format with value and type
const parameters = {};
const schemaObject = (0, zod_to_json_schema_1.zodToJsonSchema)(parametersSchema);
const properties = schemaObject.properties || {};
for (const [key, value] of Object.entries(args)) {
const propSchema = properties[key] || {};
parameters[key] = {
value: typeof value === 'object' ? JSON.stringify(value) : String(value),
type: propSchema.type || typeof value
};
}
// Determine response expectation based on mode and expectsResponse
let responseExpectation;
if (expectsResponse === false || (expectsResponse === undefined && mode === 'function')) {
responseExpectation = types_1.ResponseExpectation.NONE;
}
else if (expectsResponse === true) {
responseExpectation = types_1.ResponseExpectation.REQUIRED;
}
else {
responseExpectation = types_1.ResponseExpectation.AUTO;
}
// Use thread_id as session_id in the payload
const payloadSessionId = this._threadId;
const payload = {
session_id: payloadSessionId,
response_expectation: responseExpectation,
cache_response: cacheResponse || false,
tool_call: {
function_name: functionName,
parameters,
return_type: returnType,
docstring: description
}
};
return payload;
}
async executeMockRequest(payload) {
const baseUrl = this._baseUrl || process.env.VERIS_API_URL || "https://simulator.api.veris.ai/";
const endpoint = new URL("v3/tool_mock", baseUrl).href;
const apiKey = process.env.VERIS_API_KEY || "";
const timeout = parseFloat(process.env.VERIS_API_TIMEOUT || '300000');
try {
const response = await axios_1.default.post(endpoint, payload, { timeout, headers: { 'x-api-key': apiKey } });
let mockResult = response.data;
console.log(`Mock response: ${JSON.stringify(mockResult)}`);
if (typeof mockResult === 'string') {
try {
mockResult = JSON.parse(mockResult);
}
catch (error) {
// Keep as string if not valid JSON
}
}
return mockResult;
}
catch (error) {
console.error('Mock request failed:', error);
throw error;
}
}
createMockWrapper(originalFunc, { name, description, parametersSchema, outputSchema, mode = 'tool', expectsResponse, cacheResponse }) {
return async (args) => {
// Check if we have a session ID - if not, execute original function
// Session ID presence determines whether mocking is enabled
if (!this._sessionId) {
return originalFunc(args);
}
// Mock mode is enabled when session ID is present
console.log(`Mocking function: ${name} (session: ${this._sessionId})`);
const payload = this.createMockPayload(name, description, args, parametersSchema, outputSchema, mode, expectsResponse, cacheResponse);
return this.executeMockRequest(payload);
};
}
mockFunction(func, params) {
return this.createMockWrapper(func, params);
}
// Decorator support
mock(options = { mode: 'tool' }) {
return (_target, propertyKey, descriptor) => {
const originalMethod = descriptor.value;
descriptor.value = async function (...args) {
// Check if we have a session ID - if not, execute original function
// Session ID presence determines whether mocking is enabled
if (!exports.veris._sessionId) {
return originalMethod.apply(this, args);
}
// Mock mode is enabled when session ID is present
console.log(`Mocking function: ${propertyKey} (session: ${exports.veris._sessionId})`);
// Convert parameters to the expected format if parametersSchema is provided
let parameters = args[0] || {};
if (options.parametersSchema) {
const schemaObject = (0, zod_to_json_schema_1.zodToJsonSchema)(options.parametersSchema);
const properties = schemaObject.properties || {};
const formattedParams = {};
for (const [key, value] of Object.entries(parameters)) {
const propSchema = properties[key] || {};
formattedParams[key] = {
value: typeof value === 'object' ? JSON.stringify(value) : String(value),
type: propSchema.type || typeof value
};
}
parameters = formattedParams;
}
// Generate return_type from outputSchema if provided
const returnType = options.outputSchema
? JSON.stringify((0, zod_to_json_schema_1.zodToJsonSchema)(options.outputSchema))
: 'any';
// Determine response expectation
let responseExpectation;
if (options.expectsResponse === false || (options.expectsResponse === undefined && options.mode === 'function')) {
responseExpectation = types_1.ResponseExpectation.NONE;
}
else if (options.expectsResponse === true) {
responseExpectation = types_1.ResponseExpectation.REQUIRED;
}
else {
responseExpectation = types_1.ResponseExpectation.AUTO;
}
// Use thread_id as session_id in the payload
const payloadSessionId = exports.veris._threadId;
// Create payload with proper format
const payload = {
session_id: payloadSessionId,
response_expectation: responseExpectation,
cache_response: options.cacheResponse || false,
tool_call: {
function_name: propertyKey,
parameters,
return_type: returnType,
docstring: options.description || ''
}
};
return exports.veris.executeMockRequest(payload);
};
return descriptor;
};
}
}
exports.ToolMock = ToolMock;
exports.veris = new ToolMock();
//# sourceMappingURL=toolMock.js.map