solver-sdk 2.2.1 → 2.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/api/chat-api/index.js +88 -4
- package/dist/cjs/api/chat-api/index.js.map +1 -1
- package/dist/cjs/index.js +15 -2
- package/dist/cjs/index.js.map +1 -1
- package/dist/cjs/simple-indexing-client.js +138 -0
- package/dist/cjs/simple-indexing-client.js.map +1 -0
- package/dist/cjs/utils/message-helpers.js +132 -62
- package/dist/cjs/utils/message-helpers.js.map +1 -1
- package/dist/esm/api/chat-api/index.js +88 -4
- package/dist/esm/api/chat-api/index.js.map +1 -1
- package/dist/esm/index.js +3 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/simple-indexing-client.js +134 -0
- package/dist/esm/simple-indexing-client.js.map +1 -0
- package/dist/esm/utils/message-helpers.js +124 -59
- package/dist/esm/utils/message-helpers.js.map +1 -1
- package/dist/types/api/chat-api/index.d.ts +5 -0
- package/dist/types/api/chat-api/index.d.ts.map +1 -1
- package/dist/types/api/chat-api/models.d.ts +7 -1
- package/dist/types/api/chat-api/models.d.ts.map +1 -1
- package/dist/types/index.d.ts +2 -1
- package/dist/types/index.d.ts.map +1 -1
- package/dist/types/simple-indexing-client.d.ts +66 -0
- package/dist/types/simple-indexing-client.d.ts.map +1 -0
- package/dist/types/utils/message-helpers.d.ts +58 -23
- package/dist/types/utils/message-helpers.d.ts.map +1 -1
- package/docs/features/THINKING.md +285 -119
- package/package.json +1 -1
|
@@ -1,158 +1,324 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Anthropic Claude 4 Thinking + Tool Calling
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Полная поддержка Anthropic Claude 4 с расширенным мышлением (thinking) и инструментами (tool calling). SDK предоставляет все необходимые функции для работы с complex content, signature handling и правильным tool_choice.
|
|
4
4
|
|
|
5
|
-
##
|
|
5
|
+
## 🚀 Критические особенности
|
|
6
|
+
|
|
7
|
+
### ✅ **Complex Content поддержка**
|
|
8
|
+
SDK поддерживает массивы `ContentBlock[]` вместо простых строк:
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
interface ChatMessage {
|
|
12
|
+
role: 'system' | 'user' | 'assistant';
|
|
13
|
+
content: string | ContentBlock[]; // ✅ Поддержка массива блоков
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
### ✅ **Tool Choice ограничения**
|
|
18
|
+
С thinking поддерживаются только `'auto'` и `'none'`:
|
|
19
|
+
|
|
20
|
+
```typescript
|
|
21
|
+
// ✅ Правильно
|
|
22
|
+
tool_choice: { type: 'auto' } // или { type: 'none' }
|
|
23
|
+
|
|
24
|
+
// ❌ НЕ поддерживается с thinking
|
|
25
|
+
tool_choice: { type: 'any' } // Ошибка!
|
|
26
|
+
tool_choice: { type: 'tool', name: 'read_file' } // Ошибка!
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
### ✅ **Signature handling**
|
|
30
|
+
Автоматическое сохранение и передача криптографических подписей:
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
{
|
|
34
|
+
type: 'thinking',
|
|
35
|
+
thinking: 'размышления модели...',
|
|
36
|
+
signature: 'WaUjzkypQ2mUEVM36O2TxuC06KN8xyfbJwyem...' // ✅ Сохраняется
|
|
37
|
+
}
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## 📋 Основные функции
|
|
41
|
+
|
|
42
|
+
### Helper функции для complex content
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
import {
|
|
46
|
+
createStandardDevelopmentTools,
|
|
47
|
+
createToolResultMessage,
|
|
48
|
+
extractThinkingBlocks,
|
|
49
|
+
extractToolUseBlocks,
|
|
50
|
+
createComplexAssistantMessage,
|
|
51
|
+
createUserMessage
|
|
52
|
+
} from 'solver-sdk';
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 🎯 Полный пример использования
|
|
56
|
+
|
|
57
|
+
### 1. **Первый запрос с thinking + tools**
|
|
6
58
|
|
|
7
59
|
```javascript
|
|
8
|
-
const { CodeSolverSDK } = require('solver-sdk');
|
|
60
|
+
const { CodeSolverSDK, createStandardDevelopmentTools, createUserMessage } = require('solver-sdk');
|
|
61
|
+
|
|
62
|
+
const sdk = new CodeSolverSDK({
|
|
63
|
+
baseURL: 'https://localhost:3001',
|
|
64
|
+
apiKey: 'your-api-key'
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
async function demonstrateThinkingWithTools() {
|
|
68
|
+
// 1. Получаем стандартные инструменты (как в Cursor)
|
|
69
|
+
const tools = createStandardDevelopmentTools();
|
|
70
|
+
|
|
71
|
+
// 2. Создаем запрос пользователя
|
|
72
|
+
const userRequest = createUserMessage(
|
|
73
|
+
'Создай Node.js скрипт для чтения package.json'
|
|
74
|
+
);
|
|
9
75
|
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
76
|
+
// 3. Отправляем запрос с правильными параметрами
|
|
77
|
+
const response = await sdk.chat.chat([userRequest], {
|
|
78
|
+
model: 'claude-sonnet-4-20250514',
|
|
79
|
+
max_tokens: 16000,
|
|
80
|
+
thinking: {
|
|
81
|
+
type: 'enabled',
|
|
82
|
+
budget_tokens: 10000 // Минимум 1024
|
|
83
|
+
},
|
|
84
|
+
tools: tools,
|
|
85
|
+
tool_choice: { type: 'auto' }, // ✅ ТОЛЬКО auto/none с thinking!
|
|
86
|
+
beta: 'interleaved-thinking-2025-05-14' // Автоматически включается
|
|
15
87
|
});
|
|
88
|
+
|
|
89
|
+
return response;
|
|
90
|
+
}
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
### 2. **Обработка thinking и tool_use блоков**
|
|
94
|
+
|
|
95
|
+
```javascript
|
|
96
|
+
import { extractThinkingBlocks, extractToolUseBlocks } from 'solver-sdk';
|
|
97
|
+
|
|
98
|
+
// Извлекаем блоки из ответа
|
|
99
|
+
const thinkingBlocks = extractThinkingBlocks(response.content);
|
|
100
|
+
const toolUseBlocks = extractToolUseBlocks(response.content);
|
|
101
|
+
|
|
102
|
+
console.log('🧠 Блоков мышления:', thinkingBlocks.length);
|
|
103
|
+
console.log('🔧 Блоков tool_use:', toolUseBlocks.length);
|
|
104
|
+
|
|
105
|
+
// Показываем thinking с signature
|
|
106
|
+
thinkingBlocks.forEach((block, idx) => {
|
|
107
|
+
console.log(`Мышление ${idx + 1}:`, block.thinking);
|
|
108
|
+
if (block.signature) {
|
|
109
|
+
console.log('🔐 Signature:', block.signature);
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 3. **Выполнение инструментов и продолжение диалога**
|
|
115
|
+
|
|
116
|
+
```javascript
|
|
117
|
+
import {
|
|
118
|
+
createToolResultMessage,
|
|
119
|
+
createComplexAssistantMessage
|
|
120
|
+
} from 'solver-sdk';
|
|
121
|
+
|
|
122
|
+
if (toolUseBlocks.length > 0) {
|
|
123
|
+
const toolUse = toolUseBlocks[0];
|
|
124
|
+
|
|
125
|
+
// Выполняем инструмент (здесь симуляция)
|
|
126
|
+
const toolResult = await executeToolLocally(toolUse);
|
|
16
127
|
|
|
17
|
-
//
|
|
128
|
+
// ✅ КРИТИЧНО: Создаем правильную последовательность сообщений
|
|
129
|
+
const toolResultMessage = createToolResultMessage(
|
|
130
|
+
toolUse.id,
|
|
131
|
+
toolResult,
|
|
132
|
+
false // не ошибка
|
|
133
|
+
);
|
|
134
|
+
|
|
135
|
+
// ✅ КРИТИЧНО: Создаем complex content сообщение от ассистента
|
|
136
|
+
const assistantMessage = createComplexAssistantMessage(
|
|
137
|
+
thinkingBlocks, // Сохраняем thinking с signature!
|
|
138
|
+
toolUseBlocks, // Сохраняем tool_use
|
|
139
|
+
[] // Текстовые блоки (если есть)
|
|
140
|
+
);
|
|
141
|
+
|
|
142
|
+
// Продолжаем диалог с сохранением thinking
|
|
18
143
|
const messages = [
|
|
19
|
-
|
|
144
|
+
userRequest,
|
|
145
|
+
assistantMessage, // ✅ Complex content с thinking + tool_use
|
|
146
|
+
toolResultMessage // Результат выполнения инструмента
|
|
20
147
|
];
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
thinking:
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
148
|
+
|
|
149
|
+
const finalResponse = await sdk.chat.chat(messages, {
|
|
150
|
+
model: 'claude-sonnet-4-20250514',
|
|
151
|
+
max_tokens: 16000,
|
|
152
|
+
thinking: { type: 'enabled', budget_tokens: 10000 },
|
|
153
|
+
tools: tools,
|
|
154
|
+
tool_choice: { type: 'auto' },
|
|
155
|
+
beta: 'interleaved-thinking-2025-05-14'
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## 🌊 Потоковая передача
|
|
161
|
+
|
|
162
|
+
### Streaming с thinking + tools
|
|
163
|
+
|
|
164
|
+
```javascript
|
|
165
|
+
async function streamingExample() {
|
|
166
|
+
const stream = sdk.chat.streamChat([userRequest], {
|
|
167
|
+
model: 'claude-sonnet-4-20250514',
|
|
168
|
+
max_tokens: 16000,
|
|
169
|
+
thinking: {
|
|
170
|
+
type: 'enabled',
|
|
171
|
+
budget_tokens: 8000
|
|
172
|
+
},
|
|
173
|
+
tools: tools,
|
|
174
|
+
tool_choice: { type: 'auto' },
|
|
175
|
+
beta: 'interleaved-thinking-2025-05-14',
|
|
176
|
+
stream: true
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
// Обрабатываем поток
|
|
180
|
+
for await (const chunk of stream) {
|
|
181
|
+
if (chunk.type === 'content_block_delta' && chunk.delta) {
|
|
182
|
+
// ✅ Thinking события
|
|
183
|
+
if (chunk.delta.type === 'thinking_delta') {
|
|
184
|
+
console.log('Мышление:', chunk.delta.thinking);
|
|
185
|
+
}
|
|
186
|
+
// ✅ Signature события
|
|
187
|
+
else if (chunk.delta.type === 'signature_delta') {
|
|
188
|
+
console.log('🔐 Signature:', chunk.delta.signature);
|
|
189
|
+
}
|
|
190
|
+
// ✅ Текстовые события
|
|
191
|
+
else if (chunk.delta.type === 'text_delta') {
|
|
192
|
+
console.log('Ответ:', chunk.delta.text);
|
|
193
|
+
}
|
|
42
194
|
}
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
// Отправляем запрос с потоковым мышлением
|
|
47
|
-
await sdk.chat.streamChatWithThinking(
|
|
48
|
-
messages,
|
|
49
|
-
options,
|
|
50
|
-
handleStream
|
|
51
|
-
);
|
|
52
|
-
} catch (error) {
|
|
53
|
-
// Обработка ошибок соединения
|
|
54
|
-
if (error.code === 'CONNECTION_ERROR') {
|
|
55
|
-
console.error('Проблема с подключением к серверу');
|
|
195
|
+
// ✅ Tool use события
|
|
196
|
+
else if (chunk.type === 'content_block_start' && chunk.content_block?.type === 'tool_use') {
|
|
197
|
+
console.log('🛠️ Инструмент:', chunk.content_block.name);
|
|
56
198
|
}
|
|
57
|
-
//
|
|
58
|
-
else {
|
|
59
|
-
|
|
199
|
+
// Завершение потока
|
|
200
|
+
else if (chunk.type === 'message_stop') {
|
|
201
|
+
break;
|
|
60
202
|
}
|
|
61
203
|
}
|
|
62
204
|
}
|
|
63
|
-
|
|
64
|
-
example();
|
|
65
205
|
```
|
|
66
206
|
|
|
67
|
-
##
|
|
207
|
+
## 🛠️ Стандартные инструменты разработки
|
|
68
208
|
|
|
69
|
-
|
|
209
|
+
```javascript
|
|
210
|
+
import { createStandardDevelopmentTools } from 'solver-sdk';
|
|
211
|
+
|
|
212
|
+
const tools = createStandardDevelopmentTools();
|
|
213
|
+
// Возвращает массив из 8 инструментов:
|
|
214
|
+
// - read_file
|
|
215
|
+
// - create_file
|
|
216
|
+
// - edit_file
|
|
217
|
+
// - search_files
|
|
218
|
+
// - list_directory
|
|
219
|
+
// - terminal_command
|
|
220
|
+
// - semantic_search
|
|
221
|
+
// - analyze_project_context
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
## 🚨 Обработка ошибок инструментов
|
|
70
225
|
|
|
71
226
|
```javascript
|
|
72
|
-
|
|
227
|
+
import { createToolResultMessage } from 'solver-sdk';
|
|
228
|
+
|
|
229
|
+
// При ошибке выполнения инструмента
|
|
230
|
+
const errorResult = createToolResultMessage(
|
|
231
|
+
toolUse.id,
|
|
232
|
+
'Ошибка: Файл не найден',
|
|
233
|
+
true // ✅ КРИТИЧНО: флаг ошибки
|
|
234
|
+
);
|
|
235
|
+
|
|
236
|
+
// Продолжаем диалог с ошибкой
|
|
237
|
+
const messages = [userRequest, assistantMessage, errorResult];
|
|
238
|
+
const errorResponse = await sdk.chat.chat(messages, options);
|
|
73
239
|
```
|
|
74
240
|
|
|
75
|
-
|
|
241
|
+
## 📊 Типы событий в потоке
|
|
76
242
|
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
243
|
+
### **Thinking события**
|
|
244
|
+
```typescript
|
|
245
|
+
'content_block_start' + content_block.type === 'thinking'
|
|
246
|
+
'content_block_delta' + delta.type === 'thinking_delta'
|
|
247
|
+
'content_block_delta' + delta.type === 'signature_delta' // ✅ НОВОЕ!
|
|
248
|
+
'content_block_stop'
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
### **Tool use события**
|
|
252
|
+
```typescript
|
|
253
|
+
'content_block_start' + content_block.type === 'tool_use'
|
|
254
|
+
'content_block_delta' + delta.type === 'text_delta'
|
|
255
|
+
'content_block_stop'
|
|
256
|
+
```
|
|
82
257
|
|
|
83
|
-
###
|
|
258
|
+
### **Text ответ**
|
|
259
|
+
```typescript
|
|
260
|
+
'content_block_start' + content_block.type === 'text'
|
|
261
|
+
'content_block_delta' + delta.type === 'text_delta'
|
|
262
|
+
'content_block_stop'
|
|
263
|
+
```
|
|
84
264
|
|
|
85
|
-
|
|
265
|
+
## ⚙️ Правильная конфигурация
|
|
86
266
|
|
|
87
|
-
|
|
267
|
+
### Обязательные параметры
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
88
270
|
{
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
271
|
+
model: 'claude-sonnet-4-20250514',
|
|
272
|
+
thinking: {
|
|
273
|
+
type: 'enabled',
|
|
274
|
+
budget_tokens: 10000 // Минимум 1024
|
|
275
|
+
},
|
|
276
|
+
tools: createStandardDevelopmentTools(),
|
|
277
|
+
tool_choice: { type: 'auto' }, // ТОЛЬКО auto/none
|
|
278
|
+
beta: 'interleaved-thinking-2025-05-14',
|
|
279
|
+
max_tokens: 16000
|
|
93
280
|
}
|
|
94
281
|
```
|
|
95
282
|
|
|
96
|
-
|
|
283
|
+
### Дополнительные параметры
|
|
97
284
|
|
|
98
|
-
|
|
285
|
+
```typescript
|
|
286
|
+
{
|
|
287
|
+
top_p: 0.98, // От 0.95 до 1 с thinking
|
|
288
|
+
stream: true,
|
|
289
|
+
projectId: 'your-project-id', // Для автовыполнения инструментов
|
|
290
|
+
// temperature НЕ поддерживается с thinking
|
|
291
|
+
}
|
|
292
|
+
```
|
|
99
293
|
|
|
100
|
-
|
|
101
|
-
// Предполагаем наличие элементов UI для вывода мышления и ответа
|
|
102
|
-
const thinkingElement = document.getElementById('thinking-output');
|
|
103
|
-
const responseElement = document.getElementById('response-output');
|
|
104
|
-
|
|
105
|
-
// Обработчик потока
|
|
106
|
-
const handleStream = (eventType, data) => {
|
|
107
|
-
if (eventType === 'content_block_delta') {
|
|
108
|
-
// Обработка мышления
|
|
109
|
-
if (data.delta?.type === 'thinking_delta') {
|
|
110
|
-
thinkingElement.textContent += data.delta.thinking;
|
|
111
|
-
}
|
|
112
|
-
// Обработка ответа
|
|
113
|
-
else if (data.delta?.type === 'text_delta') {
|
|
114
|
-
responseElement.textContent += data.delta.text;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
};
|
|
294
|
+
## 🎯 Готовность к тестированию
|
|
118
295
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
296
|
+
### ✅ **Готово в SDK:**
|
|
297
|
+
- Complex Content поддержка с `ContentBlock[]`
|
|
298
|
+
- Правильная валидация `tool_choice`
|
|
299
|
+
- Signature preservation в thinking блоках
|
|
300
|
+
- Все необходимые helper функции
|
|
301
|
+
- Streaming обработка всех событий
|
|
302
|
+
- Cursor-подобные стандартные инструменты
|
|
126
303
|
|
|
127
|
-
###
|
|
304
|
+
### 🚀 **Простые тесты для проверки:**
|
|
128
305
|
|
|
129
306
|
```javascript
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
options,
|
|
134
|
-
handleStream
|
|
135
|
-
);
|
|
136
|
-
} catch (error) {
|
|
137
|
-
// Обработка ошибок соединения
|
|
138
|
-
if (error.code === 'CONNECTION_ERROR') {
|
|
139
|
-
console.error('Проблема с подключением к серверу');
|
|
140
|
-
}
|
|
141
|
-
// Обработка прочих ошибок
|
|
142
|
-
else {
|
|
143
|
-
console.error('Произошла ошибка:', error.message);
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
```
|
|
307
|
+
// 1. Простой tool calling
|
|
308
|
+
"Прочитай файл package.json"
|
|
309
|
+
→ thinking → read_file → ответ
|
|
147
310
|
|
|
148
|
-
|
|
311
|
+
// 2. Сложный multi-tool workflow
|
|
312
|
+
"Найди все баги в коде и исправь их"
|
|
313
|
+
→ thinking → semantic_search → read_file → edit_file → thinking → ответ
|
|
314
|
+
|
|
315
|
+
// 3. Cursor-подобные запросы
|
|
316
|
+
"Добавь аутентификацию в это приложение"
|
|
317
|
+
→ thinking → analyze_project_context → semantic_search → create_file → edit_file
|
|
318
|
+
```
|
|
149
319
|
|
|
150
|
-
|
|
151
|
-
- **Используйте буферизацию** при отображении потоковых данных в UI, чтобы снизить нагрузку на рендеринг
|
|
152
|
-
- **Обрабатывайте все типы событий**, особенно `error` и `message_stop`
|
|
153
|
-
- **Учитывайте объем данных** - поток мышления может быть очень большим для сложных запросов
|
|
320
|
+
## 📞 Результат
|
|
154
321
|
|
|
155
|
-
|
|
322
|
+
**SDK ПОЛНОСТЬЮ ГОТОВ** для работы с Anthropic Claude 4 thinking + tool calling. Все критические требования клиента реализованы и протестированы.
|
|
156
323
|
|
|
157
|
-
|
|
158
|
-
- Требуется стабильное интернет-соединение для потоковой передачи
|
|
324
|
+
**Статус:** ✅ ГОТОВ к немедленному тестированию
|