solver-sdk
Version:
SDK for API integration
255 lines • 9.98 kB
JavaScript
;
/**
* Помощники для создания complex content сообщений согласно Anthropic API
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAssistantMessageWithThinking = createAssistantMessageWithThinking;
exports.createTextMessage = createTextMessage;
exports.createAssistantMessage = createAssistantMessage;
exports.extractThinkingBlocks = extractThinkingBlocks;
exports.extractToolUseBlocks = extractToolUseBlocks;
exports.extractToolResultBlocks = extractToolResultBlocks;
exports.extractTextContent = extractTextContent;
exports.createToolDefinition = createToolDefinition;
exports.createStandardDevelopmentTools = createStandardDevelopmentTools;
exports.createThinkingBlock = createThinkingBlock;
exports.createToolResultMessage = createToolResultMessage;
exports.createToolUseBlock = createToolUseBlock;
exports.createComplexAssistantMessage = createComplexAssistantMessage;
exports.createTextBlock = createTextBlock;
exports.createUserMessage = createUserMessage;
exports.createSystemMessage = createSystemMessage;
const thinking_block_manager_1 = require("./thinking-block-manager");
/**
* Создает сообщение assistant с thinking и tool_use блоками
* @param thinkingContent Содержимое мышления
* @param signature Криптографическая подпись
* @param toolCall Вызов инструмента
* @returns Сообщение assistant с complex content
*/
function createAssistantMessageWithThinking(thinkingContent, toolCall, signature // ✅ ЦЕНТРАЛИЗОВАННОЕ: signature опциональная (последний параметр)
) {
// 🏗️ ЦЕНТРАЛИЗОВАННОЕ создание thinking блока
const thinkingBlock = thinking_block_manager_1.ThinkingBlockManager.createThinkingBlock(thinkingContent, signature);
const content = [
thinkingBlock,
{
type: 'tool_use',
id: toolCall.id,
name: toolCall.name,
input: toolCall.input
}
];
return {
role: 'assistant',
content: content
};
}
/**
* Создает простое текстовое сообщение
* @param role Роль отправителя
* @param text Текст сообщения
* @returns Простое сообщение
*/
function createTextMessage(role, text) {
return {
role: role,
content: text
};
}
/**
* Создает сообщение assistant с текстом и опциональным мышлением
* @param text Основной текст ответа
* @param thinkingContent Содержимое мышления (опционально)
* @param signature Подпись мышления (опционально)
* @returns Сообщение assistant с complex content
*/
function createAssistantMessage(text, thinkingContent, signature) {
const content = [];
// Добавляем thinking блок если есть
if (thinkingContent) {
// 🏗️ ЦЕНТРАЛИЗОВАННОЕ создание thinking блока
const thinkingBlock = thinking_block_manager_1.ThinkingBlockManager.createThinkingBlock(thinkingContent, signature);
content.push(thinkingBlock);
}
// Добавляем текстовый блок
content.push({
type: 'text',
text: text
});
return {
role: 'assistant',
content: content
};
}
/**
* Извлекает thinking блоки из сообщения
* @param message Сообщение с complex content
* @returns Массив thinking блоков
*/
function extractThinkingBlocks(message) {
const content = Array.isArray(message) ? message :
(Array.isArray(message.content) ? message.content : []);
return content.filter(block => block.type === 'thinking' || block.type === 'redacted_thinking');
}
/**
* Извлекает tool_use блоки из сообщения
* @param message Сообщение с complex content
* @returns Массив tool_use блоков
*/
function extractToolUseBlocks(message) {
const content = Array.isArray(message) ? message :
(Array.isArray(message.content) ? message.content : []);
return content.filter(block => block.type === 'tool_use');
}
/**
* Извлекает tool_result блоки из сообщения
* @param message Сообщение с complex content
* @returns Массив tool_result блоков
*/
function extractToolResultBlocks(message) {
const content = Array.isArray(message) ? message :
(Array.isArray(message.content) ? message.content : []);
return content.filter(block => block.type === 'tool_result');
}
/**
* Извлекает текстовое содержимое из сообщения
* @param message Сообщение
* @returns Текстовое содержимое
*/
function extractTextContent(message) {
if (typeof message.content === 'string') {
return message.content;
}
const textBlocks = message.content.filter(block => block.type === 'text');
return textBlocks.map(block => block.text).join('');
}
/**
* Создает определение инструмента для Anthropic API
* @param name Название инструмента
* @param description Описание функциональности
* @param properties Свойства входных параметров
* @param required Обязательные поля
* @returns Определение инструмента
*/
function createToolDefinition(name, description, properties, required = []) {
return {
name: name,
description: description,
input_schema: {
type: 'object',
properties: properties,
required: required
}
};
}
/**
* Получает схемы инструментов с backend сервера
* @param backendUrl URL backend сервера (по умолчанию из SDK опций)
* @returns Массив инструментов от backend
*/
async function createStandardDevelopmentTools(backendUrl) {
const url = `${backendUrl || 'http://localhost:3000'}/api/v1/tools/schemas`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Backend недоступен: HTTP ${response.status} - ${response.statusText}`);
}
const data = await response.json();
if (!data.tools || !Array.isArray(data.tools)) {
throw new Error('Неверный формат ответа от backend');
}
console.log(`Загружено ${data.count} схем инструментов с backend`);
return data.tools;
}
/**
* Создает сообщение с контентом мышления
* @param thinking Текст мышления
* @param signature Криптографическая подпись (опциональная)
* @returns Блок контента с мышлением
*/
function createThinkingBlock(thinking, signature) {
// 🏗️ ЦЕНТРАЛИЗОВАННОЕ создание через ThinkingBlockManager
return thinking_block_manager_1.ThinkingBlockManager.createThinkingBlock(thinking, signature);
}
/**
* Создает сообщение с результатом выполнения инструмента
* @param toolUseId ID вызова инструмента
* @param content Результат выполнения
* @param isError Признак ошибки
* @returns Сообщение с результатом инструмента
*/
function createToolResultMessage(toolUseId, content, isError = false) {
return {
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: toolUseId,
content: content,
is_error: isError
}
]
};
}
/**
* Создает блок использования инструмента
* @param id ID вызова инструмента
* @param name Название инструмента
* @param input Параметры инструмента
* @returns Блок использования инструмента
*/
function createToolUseBlock(id, name, input) {
return {
type: 'tool_use',
id: id,
name: name,
input: input
};
}
/**
* Создает complex content сообщение, комбинируя разные блоки
* @param thinkingBlocks Блоки мышления
* @param toolUseBlocks Блоки использования инструментов
* @param textBlocks Текстовые блоки (опционально)
* @returns Сообщение ассистента с complex content
*/
function createComplexAssistantMessage(thinkingBlocks = [], toolUseBlocks = [], textBlocks = []) {
return {
role: 'assistant',
content: [...thinkingBlocks, ...toolUseBlocks, ...textBlocks]
};
}
/**
* Конвертирует текст в ContentBlock
* @param text Текст сообщения
* @returns Блок текстового контента
*/
function createTextBlock(text) {
return {
type: 'text',
text: text
};
}
/**
* Создает сообщение пользователя с текстом
* @param text Текст сообщения
* @returns Сообщение пользователя
*/
function createUserMessage(text) {
return {
role: 'user',
content: text
};
}
/**
* Создает системное сообщение
* @param text Текст системного сообщения
* @returns Системное сообщение
*/
function createSystemMessage(text) {
return {
role: 'system',
content: text
};
}
//# sourceMappingURL=message-helpers.js.map