UNPKG

solver-sdk

Version:

SDK for WorkAI API - AI-powered code analysis with WorkCoins billing system

159 lines 7.86 kB
/** * Помощники для создания complex content сообщений согласно Anthropic API */ import { ChatMessage, ContentBlock, Tool } from '../api/chat-api/models'; /** * Создает сообщение assistant с thinking и tool_use блоками * @param thinkingContent Содержимое мышления * @param signature Криптографическая подпись * @param toolCall Вызов инструмента * @returns Сообщение assistant с complex content */ export declare function createAssistantMessageWithThinking(thinkingContent: string, toolCall: { id: string; name: string; input: any; }, signature?: string): ChatMessage; /** * Создает простое текстовое сообщение * @param role Роль отправителя * @param text Текст сообщения * @returns Простое сообщение */ export declare function createTextMessage(role: 'user' | 'system' | 'assistant', text: string): ChatMessage; /** * Создает сообщение assistant с текстом и опциональным мышлением * @param text Основной текст ответа * @param thinkingContent Содержимое мышления (опционально) * @param signature Подпись мышления (опционально) * @returns Сообщение assistant с complex content */ export declare function createAssistantMessage(text: string, thinkingContent?: string, signature?: string): ChatMessage; /** * Извлекает thinking блоки из сообщения * @param message Сообщение с complex content * @returns Массив thinking блоков */ export declare function extractThinkingBlocks(message: ChatMessage | ContentBlock[]): ContentBlock[]; /** * Извлекает tool_use блоки из сообщения * @param message Сообщение с complex content * @returns Массив tool_use блоков */ export declare function extractToolUseBlocks(message: ChatMessage | ContentBlock[]): ContentBlock[]; /** * Извлекает tool_result блоки из сообщения * @param message Сообщение с complex content * @returns Массив tool_result блоков */ export declare function extractToolResultBlocks(message: ChatMessage | ContentBlock[]): ContentBlock[]; /** * Извлекает текстовое содержимое из сообщения * @param message Сообщение * @returns Текстовое содержимое */ export declare function extractTextContent(message: ChatMessage): string; /** * Создает определение инструмента для Anthropic API * @param name Название инструмента * @param description Описание функциональности * @param properties Свойства входных параметров * @param required Обязательные поля * @returns Определение инструмента */ export declare function createToolDefinition(name: string, description: string, properties: Record<string, any>, required?: string[]): Tool; /** * Получает схемы инструментов с backend сервера * @param backendUrl URL backend сервера (по умолчанию из SDK опций) * @returns Массив инструментов от backend */ export declare function createStandardDevelopmentTools(backendUrl?: string): Promise<Tool[]>; /** * Создает сообщение с контентом мышления * @param thinking Текст мышления * @param signature Криптографическая подпись (опциональная) * @returns Блок контента с мышлением */ export declare function createThinkingBlock(thinking: string, signature?: string): ContentBlock; /** * Создает user message с результатами выполнения инструментов * * ⚠️ КРИТИЧНО: Anthropic API требует, чтобы ВСЕ tool_result для одного assistant message * были отправлены ВМЕСТЕ в одном user message! * * @example * // Один результат: * messages.push(createBatchToolResultMessage([ * { toolUseId: 'toolu_123', content: 'File content...' } * ])); * * // Множество результатов (ПРАВИЛЬНО): * const toolResults = await Promise.all( * toolUses.map(async tool => ({ * toolUseId: tool.id, * content: await executeTool(tool), * })) * ); * messages.push(createBatchToolResultMessage(toolResults)); * * // С обработкой ошибок: * messages.push(createBatchToolResultMessage([ * { toolUseId: 'toolu_123', content: 'Success result' }, * { toolUseId: 'toolu_456', content: 'Error: file not found', isError: true } * ])); * * @param toolResults Массив результатов инструментов (минимум 1) * @returns User message со всеми tool_result блоками * @throws {Error} Если массив toolResults пустой */ export declare function createBatchToolResultMessage(toolResults: Array<{ toolUseId: string; content: string; isError?: boolean; }>): ChatMessage; /** * Создает блок использования инструмента * @param id ID вызова инструмента * @param name Название инструмента * @param input Параметры инструмента * @returns Блок использования инструмента */ export declare function createToolUseBlock(id: string, name: string, input: Record<string, any>): ContentBlock; /** * Создает complex content сообщение, комбинируя разные блоки * @param thinkingBlocks Блоки мышления * @param toolUseBlocks Блоки использования инструментов * @param textBlocks Текстовые блоки (опционально) * @returns Сообщение ассистента с complex content */ export declare function createComplexAssistantMessage(thinkingBlocks?: ContentBlock[], toolUseBlocks?: ContentBlock[], textBlocks?: ContentBlock[]): ChatMessage; /** * ✅ КРИТИЧНО: Сортирует блоки в assistant message согласно требованиям Anthropic API * При thinking mode: thinking блоки ВСЕГДА ПЕРВЫМИ! */ export declare function ensureCorrectBlockOrder(content: ContentBlock[]): ContentBlock[]; /** * ✅ Валидирует структуру assistant message перед отправкой * 🚨 ERROR FIRST: Только валидация, БЕЗ автоисправлений! * Кидает exception с детальной диагностикой и инструкциями по исправлению */ export declare function validateAndFixAssistantMessage(message: ChatMessage): ChatMessage; /** * Конвертирует текст в ContentBlock * @param text Текст сообщения * @returns Блок текстового контента */ export declare function createTextBlock(text: string): ContentBlock; /** * Создает сообщение пользователя с текстом * @param text Текст сообщения * @returns Сообщение пользователя */ export declare function createUserMessage(text: string): ChatMessage; /** * Создает системное сообщение * @param text Текст системного сообщения * @returns Системное сообщение */ export declare function createSystemMessage(text: string): ChatMessage; //# sourceMappingURL=message-helpers.d.ts.map