@chaoslabs/ai-sdk 0.0.1
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/LICENSE +41 -0
- package/README.md +241 -0
- package/dist/client.d.ts +77 -0
- package/dist/client.js +167 -0
- package/dist/converter.d.ts +5 -0
- package/dist/converter.js +159 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +6 -0
- package/dist/request.d.ts +48 -0
- package/dist/request.js +93 -0
- package/dist/response.d.ts +24 -0
- package/dist/response.js +111 -0
- package/dist/schemas.d.ts +547 -0
- package/dist/schemas.js +143 -0
- package/dist/types.d.ts +310 -0
- package/dist/types.js +126 -0
- package/package.json +52 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
Copyright (c) 2025 Chaos Labs. All rights reserved.
|
|
2
|
+
|
|
3
|
+
This software and associated documentation files (the "Software") are
|
|
4
|
+
proprietary and confidential. Unauthorized copying, distribution, or use
|
|
5
|
+
of this Software is strictly prohibited.
|
|
6
|
+
|
|
7
|
+
The Software is provided under license to authorized customers only.
|
|
8
|
+
Contact support@chaoslabs.xyz for licensing information.
|
|
9
|
+
|
|
10
|
+
TERMS OF USE
|
|
11
|
+
|
|
12
|
+
1. LICENSE GRANT
|
|
13
|
+
Subject to the terms of this license, Chaos Labs grants you a limited,
|
|
14
|
+
non-exclusive, non-transferable license to use the Software solely in
|
|
15
|
+
connection with Chaos Labs services.
|
|
16
|
+
|
|
17
|
+
2. RESTRICTIONS
|
|
18
|
+
You may not:
|
|
19
|
+
- Copy, modify, or distribute the Software
|
|
20
|
+
- Reverse engineer, decompile, or disassemble the Software
|
|
21
|
+
- Sublicense, rent, or lease the Software
|
|
22
|
+
- Use the Software for any purpose other than interfacing with Chaos Labs services
|
|
23
|
+
|
|
24
|
+
3. OWNERSHIP
|
|
25
|
+
Chaos Labs retains all right, title, and interest in the Software,
|
|
26
|
+
including all intellectual property rights.
|
|
27
|
+
|
|
28
|
+
4. TERMINATION
|
|
29
|
+
This license terminates automatically if you fail to comply with its terms
|
|
30
|
+
or upon termination of your agreement with Chaos Labs.
|
|
31
|
+
|
|
32
|
+
5. DISCLAIMER
|
|
33
|
+
THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. CHAOS LABS
|
|
34
|
+
DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WARRANTIES OF
|
|
35
|
+
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
|
|
36
|
+
|
|
37
|
+
6. LIMITATION OF LIABILITY
|
|
38
|
+
IN NO EVENT SHALL CHAOS LABS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
|
|
39
|
+
SPECIAL, OR CONSEQUENTIAL DAMAGES ARISING FROM USE OF THE SOFTWARE.
|
|
40
|
+
|
|
41
|
+
For questions about licensing, contact: support@chaoslabs.xyz
|
package/README.md
ADDED
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
# Chaos AI SDK
|
|
2
|
+
|
|
3
|
+
Official TypeScript SDK for the Chaos AI API. Build DeFi-aware applications with portfolio analysis, swap operations, lending, and more.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
`TBD`
|
|
7
|
+
|
|
8
|
+
## Quick Start
|
|
9
|
+
|
|
10
|
+
### 1. Get Your API Key
|
|
11
|
+
|
|
12
|
+
Contact [support@chaoslabs.xyz](mailto:support@chaoslabs.xyz) to obtain an API key.
|
|
13
|
+
|
|
14
|
+
### 2. Set Environment Variables
|
|
15
|
+
|
|
16
|
+
```bash
|
|
17
|
+
export CHAOS_API_KEY="ck-your-api-key"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
### 3. Basic Usage
|
|
21
|
+
|
|
22
|
+
```typescript
|
|
23
|
+
import { Chaos, WALLET_MODEL, extractText, extractBlocks } from '@chaoslabs/ai-sdk';
|
|
24
|
+
|
|
25
|
+
const chaos = new Chaos({
|
|
26
|
+
apiKey: process.env.CHAOS_API_KEY,
|
|
27
|
+
baseUrl: 'https://ai-staging.chaoslabs.co', // Optional, this is the default
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const response = await chaos.chat.responses.create({
|
|
31
|
+
model: WALLET_MODEL,
|
|
32
|
+
input: [
|
|
33
|
+
{ type: 'message', role: 'user', content: 'What is in my portfolio?' }
|
|
34
|
+
],
|
|
35
|
+
metadata: {
|
|
36
|
+
user_id: 'user-123',
|
|
37
|
+
session_id: 'session-abc',
|
|
38
|
+
wallet_id: '0x...', // Your wallet address
|
|
39
|
+
},
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
// Extract text content
|
|
43
|
+
const text = extractText(response);
|
|
44
|
+
console.log(text);
|
|
45
|
+
|
|
46
|
+
// Extract structured blocks (tables, charts, actions)
|
|
47
|
+
const blocks = extractBlocks(response);
|
|
48
|
+
for (const block of blocks) {
|
|
49
|
+
console.log(block.type, block);
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## API Reference
|
|
54
|
+
|
|
55
|
+
### Chaos Client
|
|
56
|
+
|
|
57
|
+
```typescript
|
|
58
|
+
new Chaos(config: ChaosConfig)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
**Configuration Options:**
|
|
62
|
+
|
|
63
|
+
| Option | Type | Default | Description |
|
|
64
|
+
|--------|------|---------|-------------|
|
|
65
|
+
| `apiKey` | `string` | Required | Your Chaos API key |
|
|
66
|
+
| `baseUrl` | `string` | `https://ai-staging.chaoslabs.co` | API base URL |
|
|
67
|
+
| `timeout` | `number` | `120000` | Request timeout in milliseconds |
|
|
68
|
+
|
|
69
|
+
> **Important:** API keys are environment-specific. A staging API key will not work with the production API, and vice versa. Make sure your `apiKey` and `baseUrl` are from the same environment.
|
|
70
|
+
|
|
71
|
+
**Available Environments:**
|
|
72
|
+
|
|
73
|
+
| Environment | Base URL |
|
|
74
|
+
|-------------|----------|
|
|
75
|
+
| Staging | `https://ai-staging.chaoslabs.co` |
|
|
76
|
+
| Production | Coming soon |
|
|
77
|
+
|
|
78
|
+
### Models
|
|
79
|
+
|
|
80
|
+
| Model | Description |
|
|
81
|
+
|-------|-------------|
|
|
82
|
+
| `WALLET_MODEL` | Portfolio operations, swaps, lending, staking |
|
|
83
|
+
|
|
84
|
+
### Request Metadata
|
|
85
|
+
|
|
86
|
+
```typescript
|
|
87
|
+
interface RequestMetadata {
|
|
88
|
+
user_id: string; // Unique user identifier
|
|
89
|
+
session_id: string; // Client-generated session ID for conversation continuity
|
|
90
|
+
wallet_id?: string; // Wallet address (required for WALLET_MODEL)
|
|
91
|
+
}
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
> **⚠️ Upcoming Change:** The `wallet_id` field currently accepts a wallet address string. In a future release, this will be replaced with a `wallet` object that includes additional wallet information (chain, connection status, etc.). We will provide migration guidance when this change is released.
|
|
95
|
+
|
|
96
|
+
### Rendering Responses
|
|
97
|
+
|
|
98
|
+
Responses may contain text, blocks, or both. When rendering responses, text should be displayed before blocks.
|
|
99
|
+
|
|
100
|
+
Use the `extractText` and `extractBlocks` helper functions to extract content from a response:
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
import { extractText, extractBlocks } from '@chaoslabs/ai-sdk';
|
|
104
|
+
|
|
105
|
+
const response = await chaos.chat.responses.create({ ... });
|
|
106
|
+
|
|
107
|
+
// Extract text content (render this first)
|
|
108
|
+
const text = extractText(response);
|
|
109
|
+
if (text) {
|
|
110
|
+
renderText(text);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Extract blocks (render after text)
|
|
114
|
+
const blocks = extractBlocks(response);
|
|
115
|
+
for (const block of blocks) {
|
|
116
|
+
renderBlock(block);
|
|
117
|
+
}
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
#### Response Structure
|
|
121
|
+
|
|
122
|
+
```typescript
|
|
123
|
+
interface Response {
|
|
124
|
+
id: string;
|
|
125
|
+
object: 'response';
|
|
126
|
+
model: string;
|
|
127
|
+
status: 'completed' | 'failed';
|
|
128
|
+
output: OutputItem[];
|
|
129
|
+
error?: ResponseError;
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
### Block Types
|
|
135
|
+
|
|
136
|
+
The SDK returns structured blocks for rich content:
|
|
137
|
+
|
|
138
|
+
| Block Type | Description |
|
|
139
|
+
|------------|-------------|
|
|
140
|
+
| `table` | Tabular data (portfolio holdings, positions) |
|
|
141
|
+
| `pie_chart` | Distribution charts (allocation breakdown) |
|
|
142
|
+
| `timeseries` | Historical data charts |
|
|
143
|
+
| `transaction_action` | DeFi operations with primitives and risks |
|
|
144
|
+
| `interactive_card` | User prompts and confirmations |
|
|
145
|
+
| `markdown` | Rich text content |
|
|
146
|
+
|
|
147
|
+
### Helper Functions
|
|
148
|
+
|
|
149
|
+
```typescript
|
|
150
|
+
// Extract all text from response
|
|
151
|
+
extractText(response: Response): string
|
|
152
|
+
|
|
153
|
+
// Extract all blocks from response
|
|
154
|
+
extractBlocks(response: Response): Block[]
|
|
155
|
+
|
|
156
|
+
// Check for transaction risks
|
|
157
|
+
hasRisks(response: Response): boolean
|
|
158
|
+
hasBlockers(response: Response): boolean
|
|
159
|
+
|
|
160
|
+
// Type guards
|
|
161
|
+
isTableBlock(block: Block): block is TableBlock
|
|
162
|
+
isPieChartBlock(block: Block): block is PieChartBlock
|
|
163
|
+
isTimeseriesBlock(block: Block): block is TimeseriesBlock
|
|
164
|
+
isTransactionActionBlock(block: Block): block is TransactionActionBlock
|
|
165
|
+
isInteractiveCardBlock(block: Block): block is InteractiveCardBlock
|
|
166
|
+
isMarkdownBlock(block: Block): block is MarkdownBlock
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
### Error Handling
|
|
170
|
+
|
|
171
|
+
```typescript
|
|
172
|
+
import { ChaosError, ChaosTimeoutError } from '@chaoslabs/ai-sdk';
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
const response = await chaos.chat.responses.create({ ... });
|
|
176
|
+
|
|
177
|
+
if (response.status === 'failed') {
|
|
178
|
+
console.error('Request failed:', response.error);
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Process successful response
|
|
183
|
+
} catch (error) {
|
|
184
|
+
if (error instanceof ChaosTimeoutError) {
|
|
185
|
+
console.error('Request timed out');
|
|
186
|
+
} else if (error instanceof ChaosError) {
|
|
187
|
+
console.error('API error:', error.message, error.status);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
## Examples
|
|
193
|
+
|
|
194
|
+
See the `examples/` directory for complete examples:
|
|
195
|
+
|
|
196
|
+
```bash
|
|
197
|
+
# Install example dependencies
|
|
198
|
+
cd examples
|
|
199
|
+
bun install
|
|
200
|
+
|
|
201
|
+
# Run examples
|
|
202
|
+
bun run example:01 # Basic query
|
|
203
|
+
bun run example:02 # Swap action
|
|
204
|
+
bun run example:03 # Multi-turn conversation
|
|
205
|
+
bun run example:04 # Block parsing
|
|
206
|
+
bun run example:05 # Error handling
|
|
207
|
+
bun run example:06 # Lending operations
|
|
208
|
+
```
|
|
209
|
+
|
|
210
|
+
## TypeScript Support
|
|
211
|
+
|
|
212
|
+
The SDK is written in TypeScript and exports all types:
|
|
213
|
+
|
|
214
|
+
```typescript
|
|
215
|
+
import type {
|
|
216
|
+
ChaosConfig,
|
|
217
|
+
CreateResponseParams,
|
|
218
|
+
RequestMetadata,
|
|
219
|
+
Response,
|
|
220
|
+
Block,
|
|
221
|
+
TableBlock,
|
|
222
|
+
TransactionActionBlock,
|
|
223
|
+
// ... and more
|
|
224
|
+
} from '@chaoslabs/ai-sdk';
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
## Requirements
|
|
228
|
+
|
|
229
|
+
- Node.js 18+ or Bun
|
|
230
|
+
- TypeScript 5.0+ (for TypeScript projects)
|
|
231
|
+
|
|
232
|
+
## License
|
|
233
|
+
|
|
234
|
+
This software is proprietary. See [LICENSE](./LICENSE) for terms.
|
|
235
|
+
|
|
236
|
+
## Support
|
|
237
|
+
|
|
238
|
+
For questions, issues, or API key requests:
|
|
239
|
+
|
|
240
|
+
- Email: [support@chaoslabs.xyz](mailto:support@chaoslabs.xyz)
|
|
241
|
+
- Documentation: [https://docs.chaoslabs.xyz](https://docs.chaoslabs.xyz)
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { ChaosConfig, CreateResponseParams, Response } from './types.js';
|
|
2
|
+
import { WALLET_MODEL, ASK_MODEL } from './request.js';
|
|
3
|
+
export { WALLET_MODEL, ASK_MODEL };
|
|
4
|
+
/**
|
|
5
|
+
* The v1 responses API namespace.
|
|
6
|
+
*/
|
|
7
|
+
declare class V1Responses {
|
|
8
|
+
private config;
|
|
9
|
+
private sessionId;
|
|
10
|
+
private abortController;
|
|
11
|
+
constructor(config: Required<ChaosConfig>);
|
|
12
|
+
private generateId;
|
|
13
|
+
/**
|
|
14
|
+
* Create a response using v1 API.
|
|
15
|
+
*/
|
|
16
|
+
create(params: CreateResponseParams): Promise<Response>;
|
|
17
|
+
/**
|
|
18
|
+
* Create a non-streaming response.
|
|
19
|
+
*/
|
|
20
|
+
private createNonStreaming;
|
|
21
|
+
/**
|
|
22
|
+
* Cancel the current request.
|
|
23
|
+
*/
|
|
24
|
+
cancel(): void;
|
|
25
|
+
/**
|
|
26
|
+
* Reset the session for a new conversation.
|
|
27
|
+
*/
|
|
28
|
+
reset(): void;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The v1 chat API namespace.
|
|
32
|
+
*/
|
|
33
|
+
declare class V1Chat {
|
|
34
|
+
readonly responses: V1Responses;
|
|
35
|
+
constructor(config: Required<ChaosConfig>);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Chaos AI SDK Client - V1 API.
|
|
39
|
+
*
|
|
40
|
+
* This client talks to the /v1/chat/stream endpoint.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```typescript
|
|
44
|
+
* import { Chaos, WALLET_MODEL } from '@chaoslabs/ai-sdk-v1';
|
|
45
|
+
*
|
|
46
|
+
* const chaos = new Chaos({
|
|
47
|
+
* apiKey: 'ck-...',
|
|
48
|
+
* baseUrl: 'https://ai-staging.chaoslabs.co'
|
|
49
|
+
* });
|
|
50
|
+
*
|
|
51
|
+
* const response = await chaos.chat.responses.create({
|
|
52
|
+
* model: WALLET_MODEL,
|
|
53
|
+
* input: [
|
|
54
|
+
* { type: 'message', role: 'user', content: 'What is in my portfolio?' }
|
|
55
|
+
* ],
|
|
56
|
+
* metadata: {
|
|
57
|
+
* user_id: 'user-123',
|
|
58
|
+
* session_id: 'session-abc',
|
|
59
|
+
* wallet_id: '0x...',
|
|
60
|
+
* },
|
|
61
|
+
* });
|
|
62
|
+
* ```
|
|
63
|
+
*/
|
|
64
|
+
export declare class Chaos {
|
|
65
|
+
readonly chat: V1Chat;
|
|
66
|
+
private config;
|
|
67
|
+
constructor(config: ChaosConfig);
|
|
68
|
+
/**
|
|
69
|
+
* Get the API key.
|
|
70
|
+
*/
|
|
71
|
+
get apiKey(): string;
|
|
72
|
+
/**
|
|
73
|
+
* Get the base URL.
|
|
74
|
+
*/
|
|
75
|
+
get baseUrl(): string;
|
|
76
|
+
}
|
|
77
|
+
export default Chaos;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
// V1 API Client for /v1/chat/stream
|
|
2
|
+
//
|
|
3
|
+
// This client talks to the new v1 API endpoint with Bearer auth.
|
|
4
|
+
import { ChaosError, ChaosTimeoutError } from './types.js';
|
|
5
|
+
import { toV1WalletRequest, toV1AskRequest, buildV1Headers, buildV1Endpoint, WALLET_MODEL, ASK_MODEL, } from './request.js';
|
|
6
|
+
import { parseV1Stream, toV1Response } from './response.js';
|
|
7
|
+
// Export model constants
|
|
8
|
+
export { WALLET_MODEL, ASK_MODEL };
|
|
9
|
+
// ============================================================================
|
|
10
|
+
// Constants
|
|
11
|
+
// ============================================================================
|
|
12
|
+
const DEFAULT_TIMEOUT = 120000; // 2 minutes
|
|
13
|
+
// ============================================================================
|
|
14
|
+
// V1 Responses Class
|
|
15
|
+
// ============================================================================
|
|
16
|
+
/**
|
|
17
|
+
* The v1 responses API namespace.
|
|
18
|
+
*/
|
|
19
|
+
class V1Responses {
|
|
20
|
+
config;
|
|
21
|
+
sessionId;
|
|
22
|
+
abortController = null;
|
|
23
|
+
constructor(config) {
|
|
24
|
+
this.config = config;
|
|
25
|
+
this.sessionId = this.generateId();
|
|
26
|
+
}
|
|
27
|
+
generateId() {
|
|
28
|
+
return `sdk-${crypto.randomUUID().slice(0, 12)}`;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Create a response using v1 API.
|
|
32
|
+
*/
|
|
33
|
+
async create(params) {
|
|
34
|
+
return this.createNonStreaming(params);
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Create a non-streaming response.
|
|
38
|
+
*/
|
|
39
|
+
async createNonStreaming(params) {
|
|
40
|
+
const responseId = this.generateId();
|
|
41
|
+
const sessionId = params.metadata.session_id || this.sessionId;
|
|
42
|
+
// Create abort controller for timeout
|
|
43
|
+
this.abortController = new AbortController();
|
|
44
|
+
const timeoutSignal = AbortSignal.timeout(this.config.timeout);
|
|
45
|
+
const signal = AbortSignal.any([this.abortController.signal, timeoutSignal]);
|
|
46
|
+
// Build request
|
|
47
|
+
const endpoint = buildV1Endpoint(this.config.baseUrl);
|
|
48
|
+
const headers = buildV1Headers(this.config.apiKey);
|
|
49
|
+
// Check if wallet or ask mode
|
|
50
|
+
const isWallet = params.model === WALLET_MODEL || params.model.includes('WALLET');
|
|
51
|
+
const requestBody = isWallet
|
|
52
|
+
? toV1WalletRequest(params, sessionId)
|
|
53
|
+
: toV1AskRequest(params, sessionId);
|
|
54
|
+
try {
|
|
55
|
+
// Make request
|
|
56
|
+
const response = await fetch(endpoint, {
|
|
57
|
+
method: 'POST',
|
|
58
|
+
headers,
|
|
59
|
+
body: JSON.stringify(requestBody),
|
|
60
|
+
signal,
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok) {
|
|
63
|
+
throw new ChaosError(`HTTP error: ${response.status} ${response.statusText}`, response.status);
|
|
64
|
+
}
|
|
65
|
+
if (!response.body) {
|
|
66
|
+
throw new ChaosError('Response body is null');
|
|
67
|
+
}
|
|
68
|
+
// Parse NDJSON stream
|
|
69
|
+
const finalState = await parseV1Stream(response.body);
|
|
70
|
+
// Convert to Response
|
|
71
|
+
return toV1Response(responseId, params.model, finalState);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error instanceof Error && error.name === 'TimeoutError') {
|
|
75
|
+
throw new ChaosTimeoutError(this.config.timeout);
|
|
76
|
+
}
|
|
77
|
+
if (error instanceof ChaosError) {
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
throw new ChaosError(error instanceof Error ? error.message : String(error));
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
this.abortController = null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Cancel the current request.
|
|
88
|
+
*/
|
|
89
|
+
cancel() {
|
|
90
|
+
this.abortController?.abort();
|
|
91
|
+
this.abortController = null;
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Reset the session for a new conversation.
|
|
95
|
+
*/
|
|
96
|
+
reset() {
|
|
97
|
+
this.cancel();
|
|
98
|
+
this.sessionId = this.generateId();
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
// ============================================================================
|
|
102
|
+
// V1 Chat Class
|
|
103
|
+
// ============================================================================
|
|
104
|
+
/**
|
|
105
|
+
* The v1 chat API namespace.
|
|
106
|
+
*/
|
|
107
|
+
class V1Chat {
|
|
108
|
+
responses;
|
|
109
|
+
constructor(config) {
|
|
110
|
+
this.responses = new V1Responses(config);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
// ============================================================================
|
|
114
|
+
// V1 Chaos Class
|
|
115
|
+
// ============================================================================
|
|
116
|
+
/**
|
|
117
|
+
* Chaos AI SDK Client - V1 API.
|
|
118
|
+
*
|
|
119
|
+
* This client talks to the /v1/chat/stream endpoint.
|
|
120
|
+
*
|
|
121
|
+
* @example
|
|
122
|
+
* ```typescript
|
|
123
|
+
* import { Chaos, WALLET_MODEL } from '@chaoslabs/ai-sdk-v1';
|
|
124
|
+
*
|
|
125
|
+
* const chaos = new Chaos({
|
|
126
|
+
* apiKey: 'ck-...',
|
|
127
|
+
* baseUrl: 'https://ai-staging.chaoslabs.co'
|
|
128
|
+
* });
|
|
129
|
+
*
|
|
130
|
+
* const response = await chaos.chat.responses.create({
|
|
131
|
+
* model: WALLET_MODEL,
|
|
132
|
+
* input: [
|
|
133
|
+
* { type: 'message', role: 'user', content: 'What is in my portfolio?' }
|
|
134
|
+
* ],
|
|
135
|
+
* metadata: {
|
|
136
|
+
* user_id: 'user-123',
|
|
137
|
+
* session_id: 'session-abc',
|
|
138
|
+
* wallet_id: '0x...',
|
|
139
|
+
* },
|
|
140
|
+
* });
|
|
141
|
+
* ```
|
|
142
|
+
*/
|
|
143
|
+
export class Chaos {
|
|
144
|
+
chat;
|
|
145
|
+
config;
|
|
146
|
+
constructor(config) {
|
|
147
|
+
this.config = {
|
|
148
|
+
apiKey: config.apiKey,
|
|
149
|
+
baseUrl: config.baseUrl || 'https://ai-staging.chaoslabs.co',
|
|
150
|
+
timeout: config.timeout || DEFAULT_TIMEOUT,
|
|
151
|
+
};
|
|
152
|
+
this.chat = new V1Chat(this.config);
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* Get the API key.
|
|
156
|
+
*/
|
|
157
|
+
get apiKey() {
|
|
158
|
+
return this.config.apiKey;
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Get the base URL.
|
|
162
|
+
*/
|
|
163
|
+
get baseUrl() {
|
|
164
|
+
return this.config.baseUrl;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
export default Chaos;
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
// Block converter from backend format to SDK format
|
|
2
|
+
/**
|
|
3
|
+
* Convert a backend block to SDK block format.
|
|
4
|
+
*/
|
|
5
|
+
export function convertBlock(raw) {
|
|
6
|
+
const blockType = raw.blockType;
|
|
7
|
+
const type = raw.type;
|
|
8
|
+
// Ask mode content block -> markdown
|
|
9
|
+
if (type === 'content' && typeof raw.value === 'string') {
|
|
10
|
+
return {
|
|
11
|
+
type: 'markdown',
|
|
12
|
+
content: raw.value,
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
// Table block
|
|
16
|
+
if (blockType === 'table') {
|
|
17
|
+
return {
|
|
18
|
+
type: 'table',
|
|
19
|
+
title: raw.title || '',
|
|
20
|
+
tableHeaders: raw.tableHeaders || [],
|
|
21
|
+
rows: raw.tableRows || [],
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
// Pie chart block
|
|
25
|
+
if (blockType === 'chart' && raw.chartType === 'pie') {
|
|
26
|
+
return {
|
|
27
|
+
type: 'pie_chart',
|
|
28
|
+
title: raw.title || '',
|
|
29
|
+
data: raw.data || [],
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
// Timeseries block
|
|
33
|
+
if (blockType === 'chart' && raw.chartType === 'timeseries') {
|
|
34
|
+
return {
|
|
35
|
+
type: 'timeseries',
|
|
36
|
+
title: raw.title || '',
|
|
37
|
+
data: raw.series || raw.data,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
// Interactive card block
|
|
41
|
+
if (blockType === 'interactive') {
|
|
42
|
+
return {
|
|
43
|
+
type: 'interactive_card',
|
|
44
|
+
title: raw.title || '',
|
|
45
|
+
body: raw.body,
|
|
46
|
+
style: raw.style || 'options',
|
|
47
|
+
options: raw.options,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
// Transaction action block
|
|
51
|
+
if (blockType === 'transaction_action' || type === 'action') {
|
|
52
|
+
return convertTransactionBlock(raw);
|
|
53
|
+
}
|
|
54
|
+
// Info block -> markdown
|
|
55
|
+
if (type === 'info' && typeof raw.content === 'string') {
|
|
56
|
+
return {
|
|
57
|
+
type: 'markdown',
|
|
58
|
+
content: raw.content,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
// One-of block -> transaction action (simplified)
|
|
62
|
+
if (type === 'one_of') {
|
|
63
|
+
const options = raw.options;
|
|
64
|
+
if (options && options.length > 0) {
|
|
65
|
+
// Take the first option as a simple representation
|
|
66
|
+
const firstOption = options[0];
|
|
67
|
+
return {
|
|
68
|
+
type: 'transaction_action',
|
|
69
|
+
title: raw.rationale || 'Choose an option',
|
|
70
|
+
primitives: convertPrimitives(firstOption.primitives),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// Sequence block -> transaction action
|
|
75
|
+
if (type === 'sequence') {
|
|
76
|
+
return {
|
|
77
|
+
type: 'transaction_action',
|
|
78
|
+
title: raw.notes || 'Sequence',
|
|
79
|
+
primitives: convertPrimitives(raw.actions),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
return null;
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* Convert a backend transaction/action block to SDK format.
|
|
86
|
+
*/
|
|
87
|
+
function convertTransactionBlock(raw) {
|
|
88
|
+
const primitives = raw.primitives;
|
|
89
|
+
if (!primitives || !Array.isArray(primitives)) {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
const risks = raw.risks;
|
|
93
|
+
return {
|
|
94
|
+
type: 'transaction_action',
|
|
95
|
+
title: raw.notes || 'Transaction',
|
|
96
|
+
primitives: primitives.map((p) => {
|
|
97
|
+
const params = p.params;
|
|
98
|
+
const display = p.display;
|
|
99
|
+
return {
|
|
100
|
+
kind: p.primitive || 'unknown',
|
|
101
|
+
amount: display?.amount || params?.amount || '0',
|
|
102
|
+
from: display?.from_asset || params?.from_token,
|
|
103
|
+
to: display?.to_asset || params?.to_token,
|
|
104
|
+
...params,
|
|
105
|
+
};
|
|
106
|
+
}),
|
|
107
|
+
risks: risks ? convertRisks(risks) : undefined,
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* Convert primitives array.
|
|
112
|
+
*/
|
|
113
|
+
function convertPrimitives(primitives) {
|
|
114
|
+
if (!Array.isArray(primitives)) {
|
|
115
|
+
return [];
|
|
116
|
+
}
|
|
117
|
+
return primitives.map((p) => {
|
|
118
|
+
const prim = p;
|
|
119
|
+
const params = prim.params;
|
|
120
|
+
return {
|
|
121
|
+
kind: prim.primitive || 'unknown',
|
|
122
|
+
amount: params?.amount || '0',
|
|
123
|
+
from: params?.from_token,
|
|
124
|
+
to: params?.to_token,
|
|
125
|
+
...params,
|
|
126
|
+
};
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Convert backend risks to SDK format.
|
|
131
|
+
*/
|
|
132
|
+
function convertRisks(raw) {
|
|
133
|
+
return {
|
|
134
|
+
level: raw.level || 'low',
|
|
135
|
+
warnings: extractRiskMessages(raw.warnings),
|
|
136
|
+
blockers: extractRiskMessages(raw.blockers),
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Extract risk messages from risk check array.
|
|
141
|
+
*/
|
|
142
|
+
function extractRiskMessages(checks) {
|
|
143
|
+
if (!Array.isArray(checks)) {
|
|
144
|
+
return [];
|
|
145
|
+
}
|
|
146
|
+
return checks
|
|
147
|
+
.map((check) => {
|
|
148
|
+
if (typeof check === 'string')
|
|
149
|
+
return check;
|
|
150
|
+
if (typeof check === 'object' && check && 'message' in check) {
|
|
151
|
+
return check.message;
|
|
152
|
+
}
|
|
153
|
+
if (typeof check === 'object' && check && 'title' in check) {
|
|
154
|
+
return check.title;
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
})
|
|
158
|
+
.filter((msg) => msg !== null);
|
|
159
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { Chaos as default, Chaos, WALLET_MODEL, ASK_MODEL } from './client.js';
|
|
2
|
+
export type { V1WalletRequest, V1AskRequest } from './request.js';
|
|
3
|
+
export type { V1StreamEvent, V1FinalState } from './response.js';
|
|
4
|
+
export type { ChaosConfig, CreateResponseParams, RequestMetadata, InputItem, Response, OutputItem, ContentPart, Block, OutputText, ChaosBlock, TableBlock, MarkdownBlock, TransactionActionBlock, Primitive, InteractiveCardBlock, InteractiveOption, TimeseriesBlock, PieChartBlock, Risks, ResponseError, } from './types.js';
|
|
5
|
+
export { ChaosError, ChaosTimeoutError } from './types.js';
|
|
6
|
+
export { extractText, extractBlocks, hasRisks, hasBlockers, isTableBlock, isPieChartBlock, isTimeseriesBlock, isTransactionActionBlock, isInteractiveCardBlock, isMarkdownBlock, isOutputText, isChaosBlock, } from './types.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Chaos AI SDK V1 - Public API
|
|
2
|
+
export { Chaos as default, Chaos, WALLET_MODEL, ASK_MODEL } from './client.js';
|
|
3
|
+
// Export error classes
|
|
4
|
+
export { ChaosError, ChaosTimeoutError } from './types.js';
|
|
5
|
+
// Export helper functions
|
|
6
|
+
export { extractText, extractBlocks, hasRisks, hasBlockers, isTableBlock, isPieChartBlock, isTimeseriesBlock, isTransactionActionBlock, isInteractiveCardBlock, isMarkdownBlock, isOutputText, isChaosBlock, } from './types.js';
|