@tungoai/sdk 0.0.0-stage → 0.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/CHANGELOG.md +93 -0
- package/LICENSE +21 -0
- package/README.kk.md +327 -0
- package/README.md +346 -2
- package/README.ru.md +327 -0
- package/dist/cjs/chat.d.ts +85 -0
- package/dist/cjs/chat.js +152 -0
- package/dist/cjs/client.d.ts +117 -0
- package/dist/cjs/client.js +225 -0
- package/dist/cjs/core.d.ts +217 -0
- package/dist/cjs/core.js +779 -0
- package/dist/cjs/errors.d.ts +237 -0
- package/dist/cjs/errors.js +446 -0
- package/dist/cjs/generated/resources.d.ts +1149 -0
- package/dist/cjs/generated/resources.js +1145 -0
- package/dist/cjs/generated/types.d.ts +5435 -0
- package/dist/cjs/generated/types.js +11 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +81 -0
- package/dist/cjs/json.d.ts +16 -0
- package/dist/cjs/json.js +137 -0
- package/dist/cjs/money.d.ts +32 -0
- package/dist/cjs/money.js +141 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/pagination.d.ts +47 -0
- package/dist/cjs/pagination.js +114 -0
- package/dist/cjs/streaming.d.ts +76 -0
- package/dist/cjs/streaming.js +291 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +6 -0
- package/dist/cjs/webhooks.d.ts +79 -0
- package/dist/cjs/webhooks.js +262 -0
- package/dist/esm/chat.d.ts +85 -0
- package/dist/esm/chat.js +144 -0
- package/dist/esm/client.d.ts +117 -0
- package/dist/esm/client.js +221 -0
- package/dist/esm/core.d.ts +217 -0
- package/dist/esm/core.js +763 -0
- package/dist/esm/errors.d.ts +237 -0
- package/dist/esm/errors.js +416 -0
- package/dist/esm/generated/resources.d.ts +1149 -0
- package/dist/esm/generated/resources.js +1129 -0
- package/dist/esm/generated/types.d.ts +5435 -0
- package/dist/esm/generated/types.js +10 -0
- package/dist/esm/index.d.ts +12 -0
- package/dist/esm/index.js +11 -0
- package/dist/esm/json.d.ts +16 -0
- package/dist/esm/json.js +132 -0
- package/dist/esm/money.d.ts +32 -0
- package/dist/esm/money.js +137 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/pagination.d.ts +47 -0
- package/dist/esm/pagination.js +108 -0
- package/dist/esm/streaming.d.ts +76 -0
- package/dist/esm/streaming.js +285 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +3 -0
- package/dist/esm/webhooks.d.ts +79 -0
- package/dist/esm/webhooks.js +253 -0
- package/package.json +67 -4
package/README.ru.md
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
<!-- Generated by tungo-sdkgen. Do not edit: the file is rewritten on every generation. -->
|
|
2
|
+
|
|
3
|
+
<div align="center">
|
|
4
|
+
|
|
5
|
+
<picture>
|
|
6
|
+
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo02.svg" />
|
|
7
|
+
<source media="(prefers-color-scheme: light)" srcset="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" />
|
|
8
|
+
<img alt="Tungo AI" src="https://raw.githubusercontent.com/TungoAI/.github/main/assets/logo03.svg" width="240" />
|
|
9
|
+
</picture>
|
|
10
|
+
|
|
11
|
+
# Tungo SDK для TypeScript
|
|
12
|
+
|
|
13
|
+
**Официальная библиотека TypeScript для API платформы Tungo**
|
|
14
|
+
|
|
15
|
+
[](https://www.npmjs.com/package/@tungoai/sdk)
|
|
16
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/actions/workflows/ci.yml)
|
|
17
|
+
[](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|
|
18
|
+
|
|
19
|
+
[English](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md) · **Русский** · [Қазақша](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.kk.md)
|
|
20
|
+
|
|
21
|
+
[tungo.kz](https://tungo.kz) · [Быстрый старт](#быстрый-старт) · [Справочник API](#справочник-api) · [История изменений](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md) · [Обращения](https://github.com/TungoAI/tungo-sdk-typescript/issues)
|
|
22
|
+
|
|
23
|
+
</div>
|
|
24
|
+
|
|
25
|
+
---
|
|
26
|
+
|
|
27
|
+
Официальная библиотека TypeScript для API платформы Tungo (`https://api.tungo.kz`): ИИ-бухгалтер, работа с 1С, банковские выписки, электронные счета-фактуры, налоговые формы и автоматизации [Tungo AI](https://tungo.kz).
|
|
28
|
+
|
|
29
|
+
Библиотека создаётся из OpenAPI-контракта API, поэтому её методы и модели всегда соответствуют контракту, из которого она собрана.
|
|
30
|
+
|
|
31
|
+
> Полная версия с примечаниями, относящимися только к этому языку, — в [английском README](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md).
|
|
32
|
+
|
|
33
|
+
## Требования
|
|
34
|
+
|
|
35
|
+
Поддерживаемые версии и зависимости перечислены в [английском README](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/README.md#requirements).
|
|
36
|
+
|
|
37
|
+
## Установка
|
|
38
|
+
|
|
39
|
+
```bash
|
|
40
|
+
npm install @tungoai/sdk
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
## Быстрый старт
|
|
44
|
+
|
|
45
|
+
```ts
|
|
46
|
+
import { Tungo } from '@tungoai/sdk';
|
|
47
|
+
|
|
48
|
+
const client = new Tungo(); // reads TUNGO_API_KEY
|
|
49
|
+
|
|
50
|
+
const { data: companies } = await client.companies.list();
|
|
51
|
+
for (const company of companies) {
|
|
52
|
+
console.log(company.id, company.name);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const reply = await client.ask('co_01h455vb4pex5vsknk084sn02q', 'What VAT applies to the last sale?');
|
|
56
|
+
console.log(reply.answer);
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Аутентификация и настройка
|
|
60
|
+
|
|
61
|
+
Создайте один клиент и используйте его везде: он неизменяем и безопасен для работы из нескольких потоков или задач. Любой параметр можно передать явно; три из них берутся из переменных окружения, если не заданы.
|
|
62
|
+
|
|
63
|
+
| Параметр | Переменная окружения | По умолчанию |
|
|
64
|
+
| --- | --- | --- |
|
|
65
|
+
| Ключ API | `TUNGO_API_KEY` | нет |
|
|
66
|
+
| Базовый адрес | `TUNGO_BASE_URL` | `https://api.tungo.kz` |
|
|
67
|
+
| Секрет вебхуков | `TUNGO_WEBHOOK_SECRET` | нет |
|
|
68
|
+
| Тайм-аут | | 60 с (600 с для обычных, не потоковых, ответов чата) |
|
|
69
|
+
| Максимум повторов | | 2 |
|
|
70
|
+
| Заголовки по умолчанию, HTTP-клиент | | нет, встроенный |
|
|
71
|
+
|
|
72
|
+
Ключ API отправляется только тем операциям, которым он нужен: открытые адреса и входящие хуки его не получают, и он никогда не попадает в тексты ошибок и отладочный вывод. Вызов операции, требующей ключ, без ключа завершается ошибкой на месте, до отправки запроса.
|
|
73
|
+
|
|
74
|
+
Каждый метод принимает и параметры отдельного запроса: тайм-аут, число повторов, дополнительные заголовки, ключ идемпотентности и отмену.
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
import { Tungo } from '@tungoai/sdk';
|
|
78
|
+
|
|
79
|
+
const client = new Tungo({
|
|
80
|
+
apiKey: 'tg_...', // default: TUNGO_API_KEY
|
|
81
|
+
baseUrl: 'https://api.tungo.kz', // default: TUNGO_BASE_URL
|
|
82
|
+
webhookSecret: 'whsec_...', // default: TUNGO_WEBHOOK_SECRET
|
|
83
|
+
timeout: 30_000, // milliseconds, covers the whole request
|
|
84
|
+
longRunningTimeout: 300_000, // non-streaming chat turns
|
|
85
|
+
maxRetries: 3,
|
|
86
|
+
defaultHeaders: { 'X-App': 'billing' },
|
|
87
|
+
fetch: (url, init) => fetch(url, init), // any fetch-compatible function: proxy, tracing, mock
|
|
88
|
+
});
|
|
89
|
+
|
|
90
|
+
// Per-request options are the last argument of every method.
|
|
91
|
+
const controller = new AbortController();
|
|
92
|
+
const company = await client.companies.get('co_01h455vb4pex5vsknk084sn02q', {
|
|
93
|
+
timeout: 5_000,
|
|
94
|
+
maxRetries: 0,
|
|
95
|
+
headers: { 'X-Trace-Id': 'trace-123' },
|
|
96
|
+
signal: controller.signal,
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Status, headers, request id and rate limit of any call.
|
|
100
|
+
const { data, response } = await client.companies.get(company.id).withResponse();
|
|
101
|
+
console.log(data.name, response.status, response.requestId, response.rateLimit?.remaining);
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Ошибки
|
|
105
|
+
|
|
106
|
+
Любой сбой — подтип базовой ошибки SDK. Ответ с HTTP-ошибкой превращается в ошибку API, тип которой выбирается по полю `error.type` тела ответа, а если тело не является стандартной ошибкой API — по HTTP-статусу:
|
|
107
|
+
|
|
108
|
+
| `error.type` | Статус |
|
|
109
|
+
| --- | --- |
|
|
110
|
+
| `invalid_request_error` | 400 |
|
|
111
|
+
| `authentication_error` | 401 |
|
|
112
|
+
| `payment_required_error` | 402 |
|
|
113
|
+
| `permission_error` | 403 |
|
|
114
|
+
| `not_found_error` | 404 |
|
|
115
|
+
| `conflict_error` | 409 |
|
|
116
|
+
| `gone_error` | 410 |
|
|
117
|
+
| `limit_error` | 429 |
|
|
118
|
+
| `api_error` | 500 |
|
|
119
|
+
| `unavailable_error` | 503 |
|
|
120
|
+
|
|
121
|
+
Ошибка API содержит статус, тип, код, сообщение, идентификатор запроса, ошибки полей, разобранную задержку перед повтором, заголовки ответа и исходное тело. У сбоев без ответа свои типы: ошибка соединения, тайм-аут, ошибка разбора (успешный ответ с некорректным телом), ошибка настройки или проверки аргументов (возникает до запроса).
|
|
122
|
+
|
|
123
|
+
```ts
|
|
124
|
+
import { APIError, ConnectionError, LimitError, NotFoundError, TimeoutError, Tungo } from '@tungoai/sdk';
|
|
125
|
+
|
|
126
|
+
const client = new Tungo();
|
|
127
|
+
|
|
128
|
+
try {
|
|
129
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042');
|
|
130
|
+
} catch (err) {
|
|
131
|
+
if (err instanceof NotFoundError) {
|
|
132
|
+
console.log('No such proposal');
|
|
133
|
+
} else if (err instanceof LimitError) {
|
|
134
|
+
console.log('Retry in', err.retryAfter, 'seconds; the limit resets at', err.extra['resets_at']);
|
|
135
|
+
} else if (err instanceof APIError) {
|
|
136
|
+
// status, error.type, error.code, the API's message, the id to quote to support, field errors
|
|
137
|
+
console.log(err.status, err.type, err.code, err.detail, err.requestId, err.fields);
|
|
138
|
+
} else if (err instanceof TimeoutError || err instanceof ConnectionError) {
|
|
139
|
+
console.log('Network problem:', err.message);
|
|
140
|
+
} else {
|
|
141
|
+
throw err;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
## Повторы и тайм-ауты
|
|
147
|
+
|
|
148
|
+
Запрос повторяется до 2 раз (всего 3 попытки) при ошибках соединения, тайм-аутах и статусах 408, 429, 500, 502, 503 и 504, но только когда повтор безопасен: запросы `GET`, `HEAD`, `PUT` и `DELETE`, а также `POST` и `PATCH` тех операций, у которых контракт объявляет заголовок `Idempotency-Key`. Для них SDK сам создаёт случайный ключ и использует его во всех попытках; можно передать свой. Другие операции ключ не отправляют, даже переданный: API его там не учитывает.
|
|
149
|
+
|
|
150
|
+
Пауза между попытками — `min(0,5 с × 2^попытка, 8 с)` со случайным разбросом. Положительное значение заголовка ответа `retry-after-ms` или `Retry-After` заменяет её; если сервер просит ждать дольше 60 с, SDK не ждёт и возвращает ошибку с указанной задержкой.
|
|
151
|
+
|
|
152
|
+
Тайм-аут охватывает весь запрос, включая чтение тела. У потоковых вызовов общего тайм-аута нет — только тайм-аут соединения и тайм-аут простоя 120 с. Отмена со стороны вызывающего кода действует вместе с тайм-аутом.
|
|
153
|
+
|
|
154
|
+
```ts
|
|
155
|
+
import { Tungo } from '@tungoai/sdk';
|
|
156
|
+
|
|
157
|
+
const client = new Tungo({ maxRetries: 5, timeout: 20_000 });
|
|
158
|
+
|
|
159
|
+
// Override per request.
|
|
160
|
+
await client.companies.list({ maxRetries: 0, timeout: 2_000 });
|
|
161
|
+
|
|
162
|
+
// A POST is retried only when it carries an Idempotency-Key. The SDK generates one for the
|
|
163
|
+
// operations that declare the header; pass your own to make a retry of your own code safe too.
|
|
164
|
+
await client.proposals.approve('co_01h455vb4pex5vsknk084sn02q', 'P-000042', {}, { idempotencyKey: 'approve-P-000042' });
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
## Постраничная выдача
|
|
168
|
+
|
|
169
|
+
Списки выдаются по курсору (`{ data, next_cursor }`). Обычный метод возвращает одну типизированную страницу, которая знает, есть ли следующая, и умеет её запросить. Вариант с автоматическим перелистыванием — ленивый итератор: он запрашивает следующую страницу только когда она нужна, сохраняет ваши фильтры и прекращает запросы, как только вы прекращаете обход.
|
|
170
|
+
|
|
171
|
+
```ts
|
|
172
|
+
import { Tungo } from '@tungoai/sdk';
|
|
173
|
+
|
|
174
|
+
const client = new Tungo();
|
|
175
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
176
|
+
|
|
177
|
+
// One page.
|
|
178
|
+
const page = await client.proposals.list(company, { status: 'awaiting_approval', limit: 50 });
|
|
179
|
+
console.log(page.data.length, 'of', page.body.total, 'next cursor:', page.nextCursor);
|
|
180
|
+
if (page.hasNextPage()) {
|
|
181
|
+
const next = await page.getNextPage();
|
|
182
|
+
console.log(next.data.length);
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
// Every item of every page, fetched lazily.
|
|
186
|
+
for await (const proposal of client.proposals.listAll(company, { status: 'awaiting_approval' })) {
|
|
187
|
+
console.log(proposal.id);
|
|
188
|
+
if (proposal.id === 'P-000100') break; // no further pages are requested
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Потоковая передача
|
|
193
|
+
|
|
194
|
+
Потоковые операции используют server-sent events и отдают типизированные события по мере поступления. Досрочный выход из цикла или закрытие потока закрывает соединение. Потоковый запрос повторяется только до получения первого байта; ответ с ошибкой становится той же типизированной ошибкой API, что и у обычных вызовов. Поток чата, оборвавшийся до завершающего события, считается ошибкой и никогда не выдаётся за готовый ответ.
|
|
195
|
+
|
|
196
|
+
```ts
|
|
197
|
+
import { Tungo } from '@tungoai/sdk';
|
|
198
|
+
|
|
199
|
+
const client = new Tungo();
|
|
200
|
+
const company = 'co_01h455vb4pex5vsknk084sn02q';
|
|
201
|
+
|
|
202
|
+
const stream = await client.chat.stream(company, { message: 'Check the November bank statement' });
|
|
203
|
+
console.log('dialog', stream.dialogId, 'turn', stream.turnNo);
|
|
204
|
+
for await (const event of stream) {
|
|
205
|
+
switch (event.type) {
|
|
206
|
+
case 'text':
|
|
207
|
+
console.log(event.delta);
|
|
208
|
+
break;
|
|
209
|
+
case 'tool':
|
|
210
|
+
console.log(event.name, event.status);
|
|
211
|
+
break;
|
|
212
|
+
case 'error':
|
|
213
|
+
console.error(event.error.code, event.error.message);
|
|
214
|
+
break;
|
|
215
|
+
case 'done':
|
|
216
|
+
console.log('finished:', event.stop_reason);
|
|
217
|
+
break;
|
|
218
|
+
default:
|
|
219
|
+
break; // a newer API version may send event types this SDK does not know
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Or let the SDK assemble the turn. A mid-stream error event is thrown as a typed APIError.
|
|
224
|
+
const turn = await client.streamChatWithResult(company, 'And for October?', {
|
|
225
|
+
onTextDelta: (delta) => console.log(delta),
|
|
226
|
+
});
|
|
227
|
+
console.log(turn.text, turn.stopReason, turn.costTiyn);
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Вебхуки
|
|
231
|
+
|
|
232
|
+
Исходящие вебхуки подписываются по спецификации Standard Webhooks (Svix). Функция проверки принимает исходное тело запроса и заголовки (`webhook-*` или `svix-*`), проверяет подпись HMAC-SHA256 за постоянное время и метку времени в пределах 300 с от системных часов и возвращает типизированное событие. Любая проблема сообщается как ошибка проверки вебхука. Если секрет не передан, используется секрет вебхуков клиента.
|
|
233
|
+
|
|
234
|
+
Функция отправки хука отправляет событие во входящий хук (`/hooks/{token}`) и, если передан секрет, подписывает ровно те байты, которые отправляет, в заголовке `X-Signature: sha256=<hex>`. Ключ API в хуки не отправляется никогда.
|
|
235
|
+
|
|
236
|
+
```ts
|
|
237
|
+
import { Tungo, WebhookVerificationError } from '@tungoai/sdk';
|
|
238
|
+
|
|
239
|
+
const client = new Tungo(); // webhook secret from TUNGO_WEBHOOK_SECRET
|
|
240
|
+
|
|
241
|
+
// A fetch-style handler (Workers, Deno, Bun, Next.js route handlers, Hono, ...).
|
|
242
|
+
export async function handleWebhook(request: Request): Promise<Response> {
|
|
243
|
+
const rawBody = await request.text(); // the exact body: do not parse and re-serialise it
|
|
244
|
+
try {
|
|
245
|
+
const event = await client.verifyWebhook(rawBody, request.headers);
|
|
246
|
+
if (event.type === 'proposal.written') {
|
|
247
|
+
console.log('written to 1C:', event.data.proposal_id);
|
|
248
|
+
}
|
|
249
|
+
return new Response(null, { status: 204 });
|
|
250
|
+
} catch (err) {
|
|
251
|
+
if (err instanceof WebhookVerificationError) {
|
|
252
|
+
return new Response('invalid signature', { status: 400 });
|
|
253
|
+
}
|
|
254
|
+
throw err;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// Send an event to an incoming hook; the body is signed with the hook's secret.
|
|
259
|
+
const accepted = await client.sendHook(
|
|
260
|
+
'th_your_hook_token',
|
|
261
|
+
{ id: 'order_1532', amount_tiyn: 4500000 },
|
|
262
|
+
{ secret: 'your hook secret', eventId: 'order_1532' },
|
|
263
|
+
);
|
|
264
|
+
console.log(accepted.event_id, accepted.duplicate);
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Деньги
|
|
268
|
+
|
|
269
|
+
API передаёт суммы в тиынах (1/100 тенге) 64-битными целыми числами. Денежные функции переводят десятичные строки и точные десятичные значения в тиыны без погрешности дробных чисел, округляя половину от нуля (`"1.005"` → `101`), и форматируют тиыны для показа (`4500000` → `45 000,00 ₸`). Некорректный ввод вызывает типизированную ошибку.
|
|
270
|
+
|
|
271
|
+
```ts
|
|
272
|
+
import { TungoMoney, isValidBinIin } from '@tungoai/sdk';
|
|
273
|
+
|
|
274
|
+
console.log(TungoMoney.toTiyn('1.005')); // 101
|
|
275
|
+
console.log(TungoMoney.toTiyn(45000.5)); // 4500050
|
|
276
|
+
console.log(TungoMoney.formatTiyn(4500000)); // 45 000,00 ₸
|
|
277
|
+
console.log(TungoMoney.formatTiyn(-50)); // -0,50 ₸
|
|
278
|
+
console.log(TungoMoney.toTiynBigInt('92233720368547758.07')); // 9223372036854775807n
|
|
279
|
+
console.log(isValidBinIin('990140000017')); // true
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
## Справочник API
|
|
283
|
+
|
|
284
|
+
Создано из контракта API платформы Tungo: **ресурсов — 13, методов — 90, типов событий вебхуков — 22**.
|
|
285
|
+
|
|
286
|
+
| Ресурс | Описание | Методы |
|
|
287
|
+
| --- | --- | --- |
|
|
288
|
+
| `workspaces` | Организации (workspace), доступные ключу API | `list` |
|
|
289
|
+
| `companies` | Компании организации и их карточки | `list` · `get` |
|
|
290
|
+
| `platform` | Баланс платформы, книга движений, отчёты о расходе, лимиты, аудит и тарифы моделей | `listUsageRates` · `getAccount` · `getAudit` · `getAuditAll` · `getLedger` · `getLedgerAll` · `listLimits` · `listRequests` · `listRequestsAll` · `getUsage` |
|
|
291
|
+
| `apiKeys` | Сведения о текущем ключе API и статистика его расхода | `getCurrent` · `getCurrentUsage` · `getUsage` |
|
|
292
|
+
| `webhooks` | Исходящие вебхуки организации (Svix): адреса, каталог событий, доставки и проверка подписи | `listEndpoints` · `listEndpointsAll` · `createEndpoint` · `getEndpoint` · `updateEndpoint` · `deleteEndpoint` · `listEndpointAttempts` · `listEndpointAttemptsAll` · `rotateEndpointSecret` · `testEndpoint` · `listEventTypes` · `listMessages` · `listMessagesAll` · `listMessageAttempts` · `listMessageAttemptsAll` · `resendMessage` · `getUsage` |
|
|
293
|
+
| `chat` | Диалоги с ИИ-бухгалтером: вопросы, потоковый чат (SSE), подсчёт токенов и история | `list` · `listAll` · `create` · `stream` · `countTokens` · `listMentions` · `getRatingOptions` · `listSuggestions` · `get` · `update` · `delete` · `answer` · `answerStream` · `listEvents` · `rateMessage` · `deleteMessageRating` · `rate` · `dismissRating` · `stop` |
|
|
294
|
+
| `proposals` | Предложения документов ИИ-бухгалтера: просмотр, одобрение записи в 1С и отклонение | `list` · `listAll` · `approveBatch` · `get` · `approve` · `reject` · `requestApproval` |
|
|
295
|
+
| `feed` | Лента событий и предложений компании (страницы и живой поток SSE) | `get` · `getAll` · `listEvents` |
|
|
296
|
+
| `batches` | Пачки обработки банковских выписок, входящих ЭСФ и DirectBank | `list` · `listAll` · `createBankStatement` · `createEsfPurchases` · `get` · `listEvents` · `stop` · `getSummary` · `listStatements` · `listStatementsAll` · `pollDirectbank` |
|
|
297
|
+
| `esf` | Входящие и исходящие электронные счета-фактуры (ИС ЭСФ) | `getIncoming` · `getIncomingAll` · `getOutgoing` · `getOutgoingAll` |
|
|
298
|
+
| `forms` | Налоговые формы (ФНО 100.00 и др.): сборка, проверка ИСНА и разрывы данных | `list` · `build` · `listDataGaps` · `getIsna` · `listNotes` |
|
|
299
|
+
| `onec` | Состояние подключения компании к базе 1С | `getStatus` |
|
|
300
|
+
| `automations` | Автоматизации компании: входящие хуки, сценарии, цепочки шагов, запуски и уровень автономности ИИ | `postHook` · `listHooks` · `createHook` · `getHook` · `updateHook` · `deleteHook` · `rotateHook` · `testHook` · `listRuns` · `listRunsAll` · `getRun` · `cancelRun` · `retryRun` · `listScenarios` · `createScenario` · `getScenario` · `putScenario` · `updateScenario` · `deleteScenario` · `runScenario` · `getState` · `putState` · `getAutonomy` · `putAutonomy` |
|
|
301
|
+
|
|
302
|
+
## Другие SDK
|
|
303
|
+
|
|
304
|
+
Тот же API доступен на десяти языках. Все SDK создаются из одного контракта и ведут себя одинаково.
|
|
305
|
+
|
|
306
|
+
| Язык | Репозиторий | Пакет |
|
|
307
|
+
| --- | --- | --- |
|
|
308
|
+
| **TypeScript** | [tungo-sdk-typescript](https://github.com/TungoAI/tungo-sdk-typescript) | `@tungoai/sdk` |
|
|
309
|
+
| Python | [tungo-sdk-python](https://github.com/TungoAI/tungo-sdk-python) | `tungoai` |
|
|
310
|
+
| Go | [tungo-sdk-go](https://github.com/TungoAI/tungo-sdk-go) | `github.com/TungoAI/tungo-sdk-go` |
|
|
311
|
+
| Rust | [tungo-sdk-rust](https://github.com/TungoAI/tungo-sdk-rust) | `tungo-sdk` |
|
|
312
|
+
| PHP | [tungo-sdk-php](https://github.com/TungoAI/tungo-sdk-php) | `tungo/sdk` |
|
|
313
|
+
| Java | [tungo-sdk-java](https://github.com/TungoAI/tungo-sdk-java) | `kz.tungo:tungo-sdk` |
|
|
314
|
+
| Kotlin | [tungo-sdk-kotlin](https://github.com/TungoAI/tungo-sdk-kotlin) | `kz.tungo:tungo-sdk-kotlin` |
|
|
315
|
+
| Swift | [tungo-sdk-swift](https://github.com/TungoAI/tungo-sdk-swift) | `TungoSDK` |
|
|
316
|
+
| Ruby | [tungo-sdk-ruby](https://github.com/TungoAI/tungo-sdk-ruby) | `tungo-sdk` |
|
|
317
|
+
| .NET | [tungo-sdk-dotnet](https://github.com/TungoAI/tungo-sdk-dotnet) | `Tungo.Sdk` |
|
|
318
|
+
|
|
319
|
+
## Версии и поддержка
|
|
320
|
+
|
|
321
|
+
Библиотека следует [семантическому версионированию](https://semver.org/lang/ru/). Пока старшая версия равна 0, промежуточный выпуск может содержать несовместимые изменения; они всегда перечислены в [истории изменений](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/CHANGELOG.md). Этот README описывает версию 0.3.0.
|
|
322
|
+
|
|
323
|
+
Код создаётся генератором: пишите о проблемах и идеях в [обращения](https://github.com/TungoAI/tungo-sdk-typescript/issues), а не присылайте правки к созданным файлам. Об уязвимости сообщайте по [политике безопасности](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/SECURITY.md).
|
|
324
|
+
|
|
325
|
+
## Лицензия
|
|
326
|
+
|
|
327
|
+
[MIT](https://github.com/TungoAI/tungo-sdk-typescript/blob/main/LICENSE)
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { StreamPromise } from './core.js';
|
|
2
|
+
import { type APIError } from './errors.js';
|
|
3
|
+
import { Stream, type ResponseInfo, type StreamInit } from './streaming.js';
|
|
4
|
+
import type * as T from './generated/types.js';
|
|
5
|
+
/** Callbacks invoked while a chat stream is being accumulated. */
|
|
6
|
+
export interface ChatStreamCallbacks {
|
|
7
|
+
/** Every event, in order. */
|
|
8
|
+
onEvent?: ((event: T.ChatEvent) => void) | undefined;
|
|
9
|
+
/** A piece of the answer text. */
|
|
10
|
+
onTextDelta?: ((delta: string, event: T.ChatEventText) => void) | undefined;
|
|
11
|
+
/** A piece of the model's reasoning. */
|
|
12
|
+
onThinkingDelta?: ((delta: string, event: T.ChatEventThinking) => void) | undefined;
|
|
13
|
+
/** A tool call started, finished or failed. */
|
|
14
|
+
onTool?: ((event: T.ChatEventTool) => void) | undefined;
|
|
15
|
+
/** The text of a step turned out to be an intermediate remark, not part of the answer. */
|
|
16
|
+
onProgress?: ((event: T.ChatEventProgress) => void) | undefined;
|
|
17
|
+
}
|
|
18
|
+
/** A chat turn assembled from its stream. */
|
|
19
|
+
export interface ChatStreamResult {
|
|
20
|
+
/**
|
|
21
|
+
* The final answer: `done.answer` when the server sent it, otherwise the text deltas joined,
|
|
22
|
+
* without the deltas of steps that a later `progress` event marked as intermediate.
|
|
23
|
+
*/
|
|
24
|
+
text: string;
|
|
25
|
+
/** Dialog id from the `X-Dialog-Id` response header. */
|
|
26
|
+
dialogId: string | null;
|
|
27
|
+
/** Turn number from the `X-Turn-No` response header. */
|
|
28
|
+
turnNo: number | null;
|
|
29
|
+
/** `done.stop_reason`; null when absent (and in the partial result of a stream that ended without `done`). */
|
|
30
|
+
stopReason: string | null;
|
|
31
|
+
/** `done.cost_tiyn`; null when absent. A `bigint` beyond 2^53, like every 64-bit integer of the API. */
|
|
32
|
+
costTiyn: number | bigint | null;
|
|
33
|
+
/** `done.usage`; null when absent. */
|
|
34
|
+
usage: T.ChatUsage | null;
|
|
35
|
+
/** `done.choice_id`: the question to answer with `chat.answer`; null when absent. */
|
|
36
|
+
choiceId: string | null;
|
|
37
|
+
/** Every event received, heart-beats excluded. */
|
|
38
|
+
events: T.ChatEvent[];
|
|
39
|
+
/** The first `error` event of the turn, or null. */
|
|
40
|
+
error: T.ChatEventError | null;
|
|
41
|
+
}
|
|
42
|
+
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
43
|
+
export declare class ChatAccumulator {
|
|
44
|
+
#private;
|
|
45
|
+
/** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
|
|
46
|
+
push(event: T.ChatEvent, callbacks?: ChatStreamCallbacks): void;
|
|
47
|
+
/** True once the `done` event has arrived: the server finished the turn. */
|
|
48
|
+
get completed(): boolean;
|
|
49
|
+
/** The turn as accumulated so far. */
|
|
50
|
+
result(meta?: {
|
|
51
|
+
dialogId?: string | null;
|
|
52
|
+
turnNo?: number | null;
|
|
53
|
+
}): ChatStreamResult;
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
|
|
57
|
+
* `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
|
|
58
|
+
* `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
|
|
59
|
+
* successful, so there is no error status to report. `response` supplies the headers, the request
|
|
60
|
+
* id and the rate limit.
|
|
61
|
+
*/
|
|
62
|
+
export declare function chatTurnError(error: unknown, requestId: string | null, response?: ResponseInfo): APIError;
|
|
63
|
+
/**
|
|
64
|
+
* Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
|
|
65
|
+
* event makes it throw the matching typed {@link APIError}, and a stream that ends without its
|
|
66
|
+
* `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
|
|
67
|
+
* is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
|
|
68
|
+
* When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
|
|
69
|
+
*/
|
|
70
|
+
export declare function accumulateChatStream(events: AsyncIterable<T.ChatEvent> | Iterable<T.ChatEvent>, callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
71
|
+
/** The event stream of one chat turn (or of a batch job, which reports with the same events). */
|
|
72
|
+
export declare class ChatStream extends Stream<T.ChatEvent> {
|
|
73
|
+
/** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
|
|
74
|
+
readonly dialogId: string | null;
|
|
75
|
+
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
76
|
+
readonly turnNo: number | null;
|
|
77
|
+
constructor(init: StreamInit);
|
|
78
|
+
/** Reads the stream to its end and returns the assembled turn; throws on a mid-stream `error` event and when the stream ends without `done`. */
|
|
79
|
+
finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
80
|
+
}
|
|
81
|
+
/** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
|
|
82
|
+
export declare class ChatStreamPromise extends StreamPromise<T.ChatEvent, ChatStream> {
|
|
83
|
+
/** Opens the stream, reads it to its end and returns the assembled turn. */
|
|
84
|
+
finalResult(callbacks?: ChatStreamCallbacks): Promise<ChatStreamResult>;
|
|
85
|
+
}
|
package/dist/cjs/chat.js
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ChatStreamPromise = exports.ChatStream = exports.ChatAccumulator = void 0;
|
|
4
|
+
exports.chatTurnError = chatTurnError;
|
|
5
|
+
exports.accumulateChatStream = accumulateChatStream;
|
|
6
|
+
// Code generated by tungo-sdkgen. DO NOT EDIT.
|
|
7
|
+
const core_js_1 = require("./core.js");
|
|
8
|
+
const json_js_1 = require("./json.js");
|
|
9
|
+
const errors_js_1 = require("./errors.js");
|
|
10
|
+
const streaming_js_1 = require("./streaming.js");
|
|
11
|
+
/** Folds the events of one chat turn into a {@link ChatStreamResult}. */
|
|
12
|
+
class ChatAccumulator {
|
|
13
|
+
#segments = [];
|
|
14
|
+
#events = [];
|
|
15
|
+
#done = null;
|
|
16
|
+
#error = null;
|
|
17
|
+
/** Adds one event. Unknown event types are kept in `events` and otherwise ignored. */
|
|
18
|
+
push(event, callbacks = {}) {
|
|
19
|
+
this.#events.push(event);
|
|
20
|
+
callbacks.onEvent?.(event);
|
|
21
|
+
switch (event.type) {
|
|
22
|
+
case 'text':
|
|
23
|
+
this.#segments.push({ step: event.step, delta: event.delta });
|
|
24
|
+
callbacks.onTextDelta?.(event.delta, event);
|
|
25
|
+
break;
|
|
26
|
+
case 'progress':
|
|
27
|
+
this.#segments = this.#segments.filter((s) => s.step === undefined || event.step === undefined || s.step !== event.step);
|
|
28
|
+
callbacks.onProgress?.(event);
|
|
29
|
+
break;
|
|
30
|
+
case 'thinking':
|
|
31
|
+
callbacks.onThinkingDelta?.(event.delta, event);
|
|
32
|
+
break;
|
|
33
|
+
case 'tool':
|
|
34
|
+
callbacks.onTool?.(event);
|
|
35
|
+
break;
|
|
36
|
+
case 'error':
|
|
37
|
+
if (this.#error === null)
|
|
38
|
+
this.#error = event;
|
|
39
|
+
break;
|
|
40
|
+
case 'done':
|
|
41
|
+
this.#done = event;
|
|
42
|
+
break;
|
|
43
|
+
default:
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** True once the `done` event has arrived: the server finished the turn. */
|
|
48
|
+
get completed() {
|
|
49
|
+
return this.#done !== null;
|
|
50
|
+
}
|
|
51
|
+
/** The turn as accumulated so far. */
|
|
52
|
+
result(meta = {}) {
|
|
53
|
+
const done = this.#done;
|
|
54
|
+
let text = '';
|
|
55
|
+
for (const s of this.#segments)
|
|
56
|
+
text += s.delta;
|
|
57
|
+
if (done !== null && typeof done.answer === 'string')
|
|
58
|
+
text = done.answer;
|
|
59
|
+
return {
|
|
60
|
+
text,
|
|
61
|
+
dialogId: meta.dialogId ?? null,
|
|
62
|
+
turnNo: meta.turnNo ?? null,
|
|
63
|
+
stopReason: done !== null && typeof done.stop_reason === 'string' ? done.stop_reason : null,
|
|
64
|
+
costTiyn: done !== null && done.cost_tiyn !== undefined && done.cost_tiyn !== null ? done.cost_tiyn : null,
|
|
65
|
+
usage: done !== null && done.usage !== undefined && done.usage !== null ? done.usage : null,
|
|
66
|
+
choiceId: done !== null && typeof done.choice_id === 'string' ? done.choice_id : null,
|
|
67
|
+
events: this.#events.slice(),
|
|
68
|
+
error: this.#error,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
exports.ChatAccumulator = ChatAccumulator;
|
|
73
|
+
/**
|
|
74
|
+
* Converts a chat `error` object (`{ type, code, message, ... }`, from a stream event or from
|
|
75
|
+
* `ChatTurnResult.errors`) into the typed error of the class an HTTP error response with the same
|
|
76
|
+
* `error.type` produces. Its `status` is undefined: the HTTP response that carried the turn was
|
|
77
|
+
* successful, so there is no error status to report. `response` supplies the headers, the request
|
|
78
|
+
* id and the rate limit.
|
|
79
|
+
*/
|
|
80
|
+
function chatTurnError(error, requestId, response) {
|
|
81
|
+
const detail = (0, errors_js_1.parseErrorDetail)(error);
|
|
82
|
+
return (0, errors_js_1.makeAPIError)({
|
|
83
|
+
status: undefined,
|
|
84
|
+
type: detail?.type ?? 'api_error',
|
|
85
|
+
code: detail?.code ?? null,
|
|
86
|
+
detail: detail?.detail ?? 'The chat turn failed',
|
|
87
|
+
requestId: requestId ?? response?.requestId ?? null,
|
|
88
|
+
fields: detail?.fields ?? [],
|
|
89
|
+
retryAfter: null,
|
|
90
|
+
rateLimit: response?.rateLimit ?? null,
|
|
91
|
+
headers: response?.headers ?? new Headers(),
|
|
92
|
+
body: (0, json_js_1.debugJSON)(error),
|
|
93
|
+
extra: detail?.extra ?? {},
|
|
94
|
+
envelope: detail !== null,
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Consumes a chat event stream to its end and returns the assembled turn. A mid-stream `error`
|
|
99
|
+
* event makes it throw the matching typed {@link APIError}, and a stream that ends without its
|
|
100
|
+
* `done` event (a dropped connection, a proxy that cut it) a {@link DecodeError}: a partial text
|
|
101
|
+
* is never returned as a finished turn. Both errors carry what was accumulated in `partialResult`.
|
|
102
|
+
* When `events` is a {@link ChatStream}, `dialogId` and `turnNo` are filled from the response headers.
|
|
103
|
+
*/
|
|
104
|
+
async function accumulateChatStream(events, callbacks = {}) {
|
|
105
|
+
const accumulator = new ChatAccumulator();
|
|
106
|
+
for await (const event of events)
|
|
107
|
+
accumulator.push(event, callbacks);
|
|
108
|
+
const source = events instanceof ChatStream ? events : undefined;
|
|
109
|
+
const result = accumulator.result(source === undefined ? {} : { dialogId: source.dialogId, turnNo: source.turnNo });
|
|
110
|
+
if (result.error !== null) {
|
|
111
|
+
const failure = chatTurnError(result.error.error, result.error.request_id ?? null, source?.response);
|
|
112
|
+
failure.partialResult = result;
|
|
113
|
+
throw failure;
|
|
114
|
+
}
|
|
115
|
+
if (!accumulator.completed) {
|
|
116
|
+
const failure = new errors_js_1.DecodeError('The chat stream ended before completion: no "done" event was received', {
|
|
117
|
+
status: source?.response.status,
|
|
118
|
+
requestId: source?.response.requestId ?? null,
|
|
119
|
+
body: '',
|
|
120
|
+
});
|
|
121
|
+
failure.partialResult = result;
|
|
122
|
+
throw failure;
|
|
123
|
+
}
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
/** The event stream of one chat turn (or of a batch job, which reports with the same events). */
|
|
127
|
+
class ChatStream extends streaming_js_1.Stream {
|
|
128
|
+
/** Dialog id from the `X-Dialog-Id` response header; null when the operation does not send it. */
|
|
129
|
+
dialogId;
|
|
130
|
+
/** Turn number from the `X-Turn-No` response header; null when absent. */
|
|
131
|
+
turnNo;
|
|
132
|
+
constructor(init) {
|
|
133
|
+
super(init, (event, response) => (0, streaming_js_1.decodeJSONEvent)(event, response, true));
|
|
134
|
+
const dialogId = init.response.headers.get('x-dialog-id');
|
|
135
|
+
this.dialogId = dialogId === null || dialogId === '' ? null : dialogId;
|
|
136
|
+
const turnNo = init.response.headers.get('x-turn-no');
|
|
137
|
+
this.turnNo = turnNo !== null && /^[0-9]+$/.test(turnNo) ? Number(turnNo) : null;
|
|
138
|
+
}
|
|
139
|
+
/** Reads the stream to its end and returns the assembled turn; throws on a mid-stream `error` event and when the stream ends without `done`. */
|
|
140
|
+
finalResult(callbacks = {}) {
|
|
141
|
+
return accumulateChatStream(this, callbacks);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
exports.ChatStream = ChatStream;
|
|
145
|
+
/** A promise of a {@link ChatStream} that can be iterated directly or reduced with `finalResult()`. */
|
|
146
|
+
class ChatStreamPromise extends core_js_1.StreamPromise {
|
|
147
|
+
/** Opens the stream, reads it to its end and returns the assembled turn. */
|
|
148
|
+
finalResult(callbacks = {}) {
|
|
149
|
+
return this.then((stream) => stream.finalResult(callbacks));
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
exports.ChatStreamPromise = ChatStreamPromise;
|