mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-29 05:48:45 +08:00
Merge branch 'docs/ai-stream-stop' into docs/ai-app-functions
This commit is contained in:
commit
4e4591eae7
3 files changed
+753
-87
No files matched your search
@@ -28,6 +28,11 @@ const reply = await puter.ai.chat('Extract the quantity from: three pencils', {
|
||||
model, normalize: true,
|
||||
outputFormat: { type: 'json_schema', name: 'quantity', strict: true, schema },
|
||||
});
|
||||
if (reply.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${reply.finish_reason}`);
|
||||
}
|
||||
if (reply.message.refusal) throw new Error(`Extraction refused: ${reply.message.refusal}`);
|
||||
if (!reply.message.content) throw new Error('Extraction returned no content.');
|
||||
const value = JSON.parse(reply.message.content);
|
||||
if (!Number.isInteger(value.quantity) || value.quantity < 1 || value.quantity > 20) {
|
||||
throw new Error('quantity must be an integer between 1 and 20');
|
||||
@@ -35,14 +40,118 @@ if (!Number.isInteger(value.quantity) || value.quantity < 1 || value.quantity >
|
||||
```
|
||||
|
||||
The schema constrains the shape. Your code enforces the rule that an order can
|
||||
contain 1 to 20 of an item. Treat an incomplete or refused reply as a failure,
|
||||
including when its text happens to parse.
|
||||
contain 1 to 20 of an item.
|
||||
|
||||
The three checks before `JSON.parse()` treat an incomplete or refused reply as a
|
||||
failure, including when its text happens to parse. A
|
||||
[`finish_reason`](/Objects/chatresponse/) other than `stop` means the reply was
|
||||
cut off or filtered. A model that declines can also finish with `stop`, and then
|
||||
the reply has a `message.refusal` string or no content.
|
||||
|
||||
## Extract Several Items Together
|
||||
|
||||
Put several related inputs in one call. The full code uses an `items` array
|
||||
containing one result per input ID. Validate that each ID appears exactly once,
|
||||
that the fields have the right types, and that every quantity is allowed.
|
||||
Put several related inputs in one call. Change the schema to an `items` array
|
||||
containing one result per input ID, and put the instructions and the schema in a
|
||||
system prompt:
|
||||
|
||||
```js
|
||||
const schema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
items: { type: 'array', items: {
|
||||
type: 'object',
|
||||
properties: { id: { type: 'string' }, quantity: { type: 'integer' } },
|
||||
required: ['id', 'quantity'], additionalProperties: false,
|
||||
} },
|
||||
},
|
||||
required: ['items'], additionalProperties: false,
|
||||
};
|
||||
const system = 'Extract requested quantities. Return only JSON matching this schema.\n'
|
||||
+ JSON.stringify(schema);
|
||||
```
|
||||
|
||||
Validate that each ID appears exactly once, that the fields have the right
|
||||
types, and that every quantity is allowed. The `validate()` function returns
|
||||
every problem it finds as a string:
|
||||
|
||||
```js
|
||||
function validate(value, ids) {
|
||||
const errors = [];
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return ['result must be an object'];
|
||||
}
|
||||
if (Object.keys(value).some(key => key !== 'items')) errors.push('result has extra fields');
|
||||
if (!Array.isArray(value.items)) return [...errors, 'items must be an array'];
|
||||
if (value.items.length !== ids.length) errors.push(`items must have ${ids.length} entries`);
|
||||
const seen = new Set();
|
||||
value.items.forEach((item, index) => {
|
||||
const path = `items[${index}]`;
|
||||
if (!item || typeof item !== 'object' || Array.isArray(item)) {
|
||||
errors.push(`${path} must be an object`);
|
||||
return;
|
||||
}
|
||||
if (Object.keys(item).some(key => !['id', 'quantity'].includes(key))) {
|
||||
errors.push(`${path} has extra fields`);
|
||||
}
|
||||
if (typeof item.id !== 'string' || !ids.includes(item.id)) {
|
||||
errors.push(`${path}.id must be one of ${JSON.stringify(ids)}`);
|
||||
}
|
||||
if (seen.has(item.id)) errors.push(`${path}.id must be unique`);
|
||||
seen.add(item.id);
|
||||
if (!Number.isInteger(item.quantity)) errors.push(`${path}.quantity must be an integer`);
|
||||
else if (item.quantity < 1 || item.quantity > 20) {
|
||||
errors.push(`${path}.quantity must be between 1 and 20`);
|
||||
}
|
||||
});
|
||||
return errors;
|
||||
}
|
||||
```
|
||||
|
||||
The `extract()` function checks the requests, sends them in one call, and
|
||||
returns the result only when `validate()` finds no errors:
|
||||
|
||||
```js
|
||||
async function extract(requests) {
|
||||
if (!Array.isArray(requests) || requests.length < 1 || requests.length > 20
|
||||
|| requests.some(item => typeof item?.id !== 'string' || !item.id || item.id.length > 64
|
||||
|| typeof item.text !== 'string' || !item.text.trim() || item.text.length > 2000)
|
||||
|| new Set(requests.map(item => item.id)).size !== requests.length) {
|
||||
throw new Error('Supply 1 to 20 requests with unique IDs of 1 to 64 characters and text of 1 to 2000 characters.');
|
||||
}
|
||||
const messages = [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: JSON.stringify(requests) },
|
||||
];
|
||||
const result = await puter.ai.chat(messages, {
|
||||
model, normalize: true, max_tokens: 2048,
|
||||
outputFormat: { type: 'json_schema', name: 'quantities', strict: true, schema },
|
||||
});
|
||||
if (result.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
if (result.message.refusal) throw new Error(`Extraction refused: ${result.message.refusal}`);
|
||||
if (!result.message.content) throw new Error('Extraction returned no content.');
|
||||
const value = JSON.parse(result.message.content);
|
||||
const errors = validate(value, requests.map(item => item.id));
|
||||
if (errors.length > 0) throw new Error(`AI data failed validation:\n${errors.join('\n')}`);
|
||||
return value;
|
||||
}
|
||||
```
|
||||
|
||||
Call it with a list of requests, each with its own ID:
|
||||
|
||||
```js
|
||||
try {
|
||||
const result = await extract([
|
||||
{ id: 'pencils', text: 'Please send three pencils.' },
|
||||
{ id: 'notebooks', text: 'I need two notebooks.' },
|
||||
]);
|
||||
console.log(result);
|
||||
} catch (error) {
|
||||
console.error(error.code ?? 'extraction_failed', error.message);
|
||||
throw error;
|
||||
}
|
||||
```
|
||||
|
||||
This batches N items into one structured-output call. It avoids paying for the
|
||||
same instructions N times. Keep each batch small enough for your chosen model.
|
||||
@@ -52,13 +161,55 @@ The example uses an application batch size of 20.
|
||||
|
||||
After a validation failure, append the returned assistant message and a user
|
||||
message containing the exact error strings. Keep the original input in the
|
||||
conversation so the model can correct the data against it.
|
||||
conversation so the model can correct the data against it. This version of
|
||||
`extract()` repeats the call in a loop:
|
||||
|
||||
```js
|
||||
async function extract(requests) {
|
||||
if (!Array.isArray(requests) || requests.length < 1 || requests.length > 20
|
||||
|| requests.some(item => typeof item?.id !== 'string' || !item.id || item.id.length > 64
|
||||
|| typeof item.text !== 'string' || !item.text.trim() || item.text.length > 2000)
|
||||
|| new Set(requests.map(item => item.id)).size !== requests.length) {
|
||||
throw new Error('Supply 1 to 20 requests with unique IDs of 1 to 64 characters and text of 1 to 2000 characters.');
|
||||
}
|
||||
const messages = [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: JSON.stringify(requests) },
|
||||
];
|
||||
let errors = [];
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const result = await puter.ai.chat(messages, {
|
||||
model, normalize: true, max_tokens: 2048,
|
||||
outputFormat: { type: 'json_schema', name: 'quantities', strict: true, schema },
|
||||
});
|
||||
if (result.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
if (result.message.refusal) throw new Error(`Extraction refused: ${result.message.refusal}`);
|
||||
if (!result.message.content) throw new Error('Extraction returned no content.');
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(result.message.content);
|
||||
errors = validate(value, requests.map(item => item.id));
|
||||
} catch (error) {
|
||||
errors = [`Invalid JSON: ${error.message}`];
|
||||
}
|
||||
if (errors.length === 0) return value;
|
||||
messages.push(result.message);
|
||||
messages.push({ role: 'user', content: JSON.stringify({
|
||||
validationErrors: errors, instruction: 'Correct these errors and return the complete JSON result.',
|
||||
}) });
|
||||
}
|
||||
throw new Error(`AI data failed validation after three attempts:\n${errors.join('\n')}`);
|
||||
}
|
||||
```
|
||||
|
||||
Allow at most two correction calls after the initial attempt. If the third
|
||||
result still fails, throw an error containing those validation errors. The UI
|
||||
can display it and ask the user to correct the input. Network failures, sign-in
|
||||
failures, and billing failures propagate immediately instead of entering the
|
||||
validation retry loop. Each correction call is billed.
|
||||
validation retry loop. An incomplete, refused, or empty reply also throws before
|
||||
the correction step. Each correction call is billed.
|
||||
|
||||
Keep the system prompt and schema byte-identical. Changing content and error
|
||||
feedback go after the fixed prompt, so repeated calls can reuse a cached prefix.
|
||||
@@ -71,8 +222,52 @@ lists the OpenAI models that do. The model catalog doesn't say which models
|
||||
accept it. For a model without `outputFormat`, put the same schema in the system
|
||||
prompt, omit that option, and run exactly the same parser and validator.
|
||||
|
||||
The full code already puts the schema in the system prompt. To use a model
|
||||
without `outputFormat`, change the model ID at the top and call
|
||||
The `system` prompt already contains the schema. Give `extract()` a
|
||||
`nativeFormat` parameter and send `outputFormat` only when it's `true`:
|
||||
|
||||
```js
|
||||
async function extract(requests, nativeFormat = true) {
|
||||
if (!Array.isArray(requests) || requests.length < 1 || requests.length > 20
|
||||
|| requests.some(item => typeof item?.id !== 'string' || !item.id || item.id.length > 64
|
||||
|| typeof item.text !== 'string' || !item.text.trim() || item.text.length > 2000)
|
||||
|| new Set(requests.map(item => item.id)).size !== requests.length) {
|
||||
throw new Error('Supply 1 to 20 requests with unique IDs of 1 to 64 characters and text of 1 to 2000 characters.');
|
||||
}
|
||||
const messages = [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: JSON.stringify(requests) },
|
||||
];
|
||||
let errors = [];
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const result = await puter.ai.chat(messages, {
|
||||
model, normalize: true, max_tokens: 2048,
|
||||
...(nativeFormat ? { outputFormat: {
|
||||
type: 'json_schema', name: 'quantities', strict: true, schema,
|
||||
} } : {}),
|
||||
});
|
||||
if (result.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
if (result.message.refusal) throw new Error(`Extraction refused: ${result.message.refusal}`);
|
||||
if (!result.message.content) throw new Error('Extraction returned no content.');
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(result.message.content);
|
||||
errors = validate(value, requests.map(item => item.id));
|
||||
} catch (error) {
|
||||
errors = [`Invalid JSON: ${error.message}`];
|
||||
}
|
||||
if (errors.length === 0) return value;
|
||||
messages.push(result.message);
|
||||
messages.push({ role: 'user', content: JSON.stringify({
|
||||
validationErrors: errors, instruction: 'Correct these errors and return the complete JSON result.',
|
||||
}) });
|
||||
}
|
||||
throw new Error(`AI data failed validation after three attempts:\n${errors.join('\n')}`);
|
||||
}
|
||||
```
|
||||
|
||||
To use a model without `outputFormat`, change the model ID at the top and call
|
||||
`extract(requests, false)`. A model that returns invalid JSON gets the same
|
||||
bounded correction loop.
|
||||
|
||||
@@ -80,8 +275,62 @@ bounded correction loop.
|
||||
|
||||
Hash the model, instructions, schema, mode, and inputs to make a cache key.
|
||||
Check [`puter.kv.get()`](/KV/get/) before calling AI. Validate cached results
|
||||
with the same rules, then return them. The full code saves a successful result
|
||||
and sets its lifetime with [`puter.kv.expire()`](/KV/expire/).
|
||||
with the same rules, then return them. Save a successful result with
|
||||
[`puter.kv.set()`](/KV/set/) and pass the time it expires as the third argument,
|
||||
a Unix time in seconds:
|
||||
|
||||
```js
|
||||
async function extract(requests, nativeFormat = true) {
|
||||
if (!Array.isArray(requests) || requests.length < 1 || requests.length > 20
|
||||
|| requests.some(item => typeof item?.id !== 'string' || !item.id || item.id.length > 64
|
||||
|| typeof item.text !== 'string' || !item.text.trim() || item.text.length > 2000)
|
||||
|| new Set(requests.map(item => item.id)).size !== requests.length) {
|
||||
throw new Error('Supply 1 to 20 requests with unique IDs of 1 to 64 characters and text of 1 to 2000 characters.');
|
||||
}
|
||||
const input = JSON.stringify({ model, system, nativeFormat, requests });
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(input));
|
||||
const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
|
||||
const cacheKey = `ai:quantities:${hash}`;
|
||||
const ids = requests.map(item => item.id);
|
||||
const cached = await puter.kv.get(cacheKey);
|
||||
if (cached !== null && validate(cached, ids).length === 0) return cached;
|
||||
const messages = [
|
||||
{ role: 'system', content: system },
|
||||
{ role: 'user', content: JSON.stringify(requests) },
|
||||
];
|
||||
let errors = [];
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const result = await puter.ai.chat(messages, {
|
||||
model, normalize: true, max_tokens: 2048,
|
||||
...(nativeFormat ? { outputFormat: {
|
||||
type: 'json_schema', name: 'quantities', strict: true, schema,
|
||||
} } : {}),
|
||||
});
|
||||
if (result.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
if (result.message.refusal) throw new Error(`Extraction refused: ${result.message.refusal}`);
|
||||
if (!result.message.content) throw new Error('Extraction returned no content.');
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(result.message.content);
|
||||
errors = validate(value, requests.map(item => item.id));
|
||||
} catch (error) {
|
||||
errors = [`Invalid JSON: ${error.message}`];
|
||||
}
|
||||
if (errors.length === 0) {
|
||||
const expireAt = Math.floor(Date.now() / 1000) + 60 * 60;
|
||||
await puter.kv.set(cacheKey, value, expireAt);
|
||||
return value;
|
||||
}
|
||||
messages.push(result.message);
|
||||
messages.push({ role: 'user', content: JSON.stringify({
|
||||
validationErrors: errors, instruction: 'Correct these errors and return the complete JSON result.',
|
||||
}) });
|
||||
}
|
||||
throw new Error(`AI data failed validation after three attempts:\n${errors.join('\n')}`);
|
||||
}
|
||||
```
|
||||
|
||||
The cache belongs to this app and user. Its one-hour lifetime is an application
|
||||
choice. Changing the schema or model changes the key. Generated images and audio
|
||||
@@ -176,6 +425,8 @@ async function extract(requests, nativeFormat = true) {
|
||||
if (result.finish_reason !== 'stop') {
|
||||
throw new Error(`Extraction incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
if (result.message.refusal) throw new Error(`Extraction refused: ${result.message.refusal}`);
|
||||
if (!result.message.content) throw new Error('Extraction returned no content.');
|
||||
let value;
|
||||
try {
|
||||
value = JSON.parse(result.message.content);
|
||||
@@ -184,8 +435,8 @@ async function extract(requests, nativeFormat = true) {
|
||||
errors = [`Invalid JSON: ${error.message}`];
|
||||
}
|
||||
if (errors.length === 0) {
|
||||
await puter.kv.set(cacheKey, value);
|
||||
await puter.kv.expire(cacheKey, 60 * 60);
|
||||
const expireAt = Math.floor(Date.now() / 1000) + 60 * 60;
|
||||
await puter.kv.set(cacheKey, value, expireAt);
|
||||
return value;
|
||||
}
|
||||
messages.push(result.message);
|
||||
|
||||
@@ -36,29 +36,51 @@ summary below.
|
||||
## Carry the Artifact Forward
|
||||
|
||||
When the response includes an artifact, replace the compacted history with the
|
||||
assistant turn that produced it. Keep its other fields and put the artifact first:
|
||||
assistant turn that produced it. Keep its other fields and put the artifact
|
||||
first. Add the reply text after it when the reply has text. A turn that only
|
||||
calls tools has none:
|
||||
|
||||
```js
|
||||
if (result.compaction) {
|
||||
context = [{ ...result.message, content: [
|
||||
result.compaction,
|
||||
{ type: 'text', text: result.message.content ?? '' },
|
||||
...(result.message.content ? [{ type: 'text', text: result.message.content }] : []),
|
||||
] }];
|
||||
}
|
||||
context.push({ role: 'user', content: 'What is the project called?' });
|
||||
```
|
||||
|
||||
Send the artifact unchanged to the same model. Keep system instructions first
|
||||
and byte-identical on every call, followed by the changing conversation. This
|
||||
also gives prompt caching a reusable prefix. Compaction fires only after the
|
||||
model's threshold is reached. See [Compaction](/AI/chat/#compaction) for thresholds.
|
||||
and byte-identical on every call, followed by the changing conversation.
|
||||
Compaction fires only after the model's threshold is reached. See
|
||||
[Compaction](/AI/chat/#compaction) for thresholds.
|
||||
|
||||
## Keep the Full Transcript
|
||||
|
||||
Archive each user, assistant, and tool message separately from the compacted
|
||||
context. The full code splits each serialized message into small keys, following
|
||||
[Split a Large Value Across Keys](/recipes/split-a-large-value/). This keeps a
|
||||
large reply or reasoning artifact from filling a single KV entry.
|
||||
context. The `archive()` function below splits each serialized message into
|
||||
small keys, following [Split a Large Value Across Keys](/recipes/split-a-large-value/).
|
||||
This keeps a large reply or reasoning artifact from filling a single KV entry.
|
||||
It numbers the message with [`puter.kv.incr()`](/KV/incr/) and writes the parts
|
||||
in one [`puter.kv.set()`](/KV/set/) call:
|
||||
|
||||
```js
|
||||
const chatId = crypto.randomUUID();
|
||||
const prefix = `conversation:${chatId}:`;
|
||||
|
||||
async function archive(message) {
|
||||
const number = await puter.kv.incr(`${prefix}count`);
|
||||
const json = JSON.stringify(message);
|
||||
const parts = [];
|
||||
for (let start = 0; start < json.length; start += 8000) {
|
||||
parts.push(json.slice(start, start + 8000));
|
||||
}
|
||||
await puter.kv.set(parts.map((value, index) => ({
|
||||
key: `${prefix}transcript:${String(number).padStart(10, '0')}:${String(index).padStart(6, '0')}`,
|
||||
value,
|
||||
})));
|
||||
}
|
||||
```
|
||||
|
||||
The example has one active writer per chat. Queue sends in your app, and open a
|
||||
separate chat for an independent tab. A counter is not a distributed lock. Keep
|
||||
@@ -67,15 +89,136 @@ model context stays in memory in this building block.
|
||||
|
||||
## Recover an Earlier Detail
|
||||
|
||||
Give the model a `search_transcript` tool. It searches archived messages a page at
|
||||
a time with [`puter.kv.list()`](/KV/list/) and returns up to five excerpts. The
|
||||
model can ask for a fact that its compacted context omitted. A larger archive
|
||||
can use a search index with the same tool contract.
|
||||
Give the model a `search_transcript` tool. The model can ask for a fact that its
|
||||
compacted context omitted:
|
||||
|
||||
```js
|
||||
const tools = [{
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'search_transcript',
|
||||
description: 'Find earlier messages containing an exact phrase.',
|
||||
parameters: {
|
||||
type: 'object', properties: { query: { type: 'string' } },
|
||||
required: ['query'], additionalProperties: false,
|
||||
},
|
||||
},
|
||||
}];
|
||||
```
|
||||
|
||||
The tool runs the `searchTranscript()` function. It searches archived messages a
|
||||
page at a time with [`puter.kv.list()`](/KV/list/) and returns up to five
|
||||
excerpts. A larger archive can use a search index with the same tool contract:
|
||||
|
||||
```js
|
||||
async function searchTranscript(query) {
|
||||
if (typeof query !== 'string' || !query.trim() || query.length > 100) {
|
||||
throw new Error('query must contain 1 to 100 characters');
|
||||
}
|
||||
const matches = [];
|
||||
let current = '';
|
||||
let pieces = [];
|
||||
const collect = () => {
|
||||
const json = pieces.join('');
|
||||
const index = json.toLowerCase().indexOf(query.toLowerCase());
|
||||
if (index >= 0) {
|
||||
matches.push({ number: current, excerpt: json.slice(Math.max(0, index - 500), index + 1500) });
|
||||
}
|
||||
};
|
||||
for await (const page of puter.kv.list({
|
||||
pattern: `${prefix}transcript:`, returnValues: true, stream: true, limit: 100,
|
||||
})) {
|
||||
for (const { key, value } of page.items) {
|
||||
const number = key.split(':').at(-2);
|
||||
if (current && number !== current) {
|
||||
collect();
|
||||
if (matches.length === 5) return matches;
|
||||
pieces = [];
|
||||
}
|
||||
current = number;
|
||||
pieces.push(value);
|
||||
}
|
||||
}
|
||||
if (pieces.length) collect();
|
||||
return matches;
|
||||
}
|
||||
```
|
||||
|
||||
The `send()` function runs one user message through the model. It archives each
|
||||
message, carries the artifact as in the section above, and runs the tool calls
|
||||
the model asks for. It starts from an empty `context`, since it adds every
|
||||
message itself:
|
||||
|
||||
```js
|
||||
context = [];
|
||||
const system = 'Help with this conversation. Use search_transcript for older details.';
|
||||
let busy = false;
|
||||
|
||||
async function send(text) {
|
||||
if (busy) throw new Error('Wait for the current reply.');
|
||||
if (typeof text !== 'string' || !text.trim() || text.length > 8000) {
|
||||
throw new Error('Enter 1 to 8000 characters.');
|
||||
}
|
||||
busy = true;
|
||||
try {
|
||||
const userMessage = { role: 'user', content: text };
|
||||
await archive(userMessage);
|
||||
context.push(userMessage);
|
||||
for (let step = 0; step < 5; step++) {
|
||||
const result = await puter.ai.chat([
|
||||
{ role: 'system', content: system }, ...context,
|
||||
], { model, normalize: true, compaction: true, tools, max_tokens: 1024 });
|
||||
const message = result.message;
|
||||
const done = !message.tool_calls?.length;
|
||||
if (done && (result.finish_reason !== 'stop' || typeof message.content !== 'string')) {
|
||||
throw new Error(`Reply incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
await archive(message);
|
||||
if (result.compaction) {
|
||||
context = [{ ...message, content: [
|
||||
result.compaction,
|
||||
...(message.content ? [{ type: 'text', text: message.content }] : []),
|
||||
] }];
|
||||
} else {
|
||||
context.push(message);
|
||||
}
|
||||
if (done) return message.content;
|
||||
const toolMessages = [];
|
||||
for (const call of message.tool_calls) {
|
||||
let output;
|
||||
try {
|
||||
if (call.function.name !== 'search_transcript') throw new Error('Unknown tool');
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
output = await searchTranscript(args.query);
|
||||
} catch (error) {
|
||||
output = { error: error.message };
|
||||
}
|
||||
toolMessages.push({
|
||||
role: 'tool', tool_call_id: call.id, content: JSON.stringify(output),
|
||||
});
|
||||
}
|
||||
context.push(...toolMessages);
|
||||
for (const toolMessage of toolMessages) await archive(toolMessage);
|
||||
}
|
||||
throw new Error('The conversation reached its tool step limit.');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
console.log(await send('Remember that the project is called Blue Kite.'));
|
||||
console.log(await send('What is the project called?'));
|
||||
```
|
||||
|
||||
Keep the returned assistant message intact, including `reasoning_details` and
|
||||
any tool metadata. Tool failures become tool results. A five-step limit stops
|
||||
the loop with an explicit error.
|
||||
|
||||
A reply without tool calls is checked before it joins `context`, so an
|
||||
incomplete reply rejects `send()` and stays out of the conversation. The tool
|
||||
results join `context` before they're archived. A failed archive write then
|
||||
can't leave a tool call without its result, which the next call would reject.
|
||||
|
||||
## Summarize for Another Model
|
||||
|
||||
For a model without native compaction, use an explicit summary step between
|
||||
@@ -103,15 +246,85 @@ async function summarizeOlderTurns() {
|
||||
|
||||
In this mode, omit `compaction` from the main call and await
|
||||
`summarizeOlderTurns()` before adding the next user message. Run it only after
|
||||
all tool calls have results. Bound each turn as in the full code so the summary
|
||||
call itself fits in the chosen model's context window. This is an extra billed
|
||||
call, and summaries can omit details.
|
||||
all tool calls have results. Bound each turn, as `send()` does with its input
|
||||
length check and `max_tokens`, so the summary call itself fits in the chosen
|
||||
model's context window. This is an extra billed call, and summaries can omit
|
||||
details.
|
||||
|
||||
To support both modes, choose the model with a `nativeCompaction` flag in place
|
||||
of the fixed model ID from the first section. Set the flag before starting a new
|
||||
chat:
|
||||
|
||||
```js
|
||||
const nativeCompaction = true;
|
||||
const modelId = nativeCompaction ? 'claude-sonnet-4-6' : 'gemini-3.5-flash-lite';
|
||||
const model = models.find(item => item.id === modelId)?.puterId;
|
||||
if (!model) throw new Error('The conversation model is unavailable.');
|
||||
```
|
||||
|
||||
Then have `send()` follow the flag. This version summarizes before it adds the
|
||||
user message, and enables compaction only in native mode:
|
||||
|
||||
```js
|
||||
async function send(text) {
|
||||
if (busy) throw new Error('Wait for the current reply.');
|
||||
if (typeof text !== 'string' || !text.trim() || text.length > 8000) {
|
||||
throw new Error('Enter 1 to 8000 characters.');
|
||||
}
|
||||
busy = true;
|
||||
try {
|
||||
if (!nativeCompaction) await summarizeOlderTurns();
|
||||
const userMessage = { role: 'user', content: text };
|
||||
await archive(userMessage);
|
||||
context.push(userMessage);
|
||||
for (let step = 0; step < 5; step++) {
|
||||
const result = await puter.ai.chat([
|
||||
{ role: 'system', content: system }, ...context,
|
||||
], { model, normalize: true, ...(nativeCompaction ? { compaction: true } : {}), tools, max_tokens: 1024 });
|
||||
const message = result.message;
|
||||
const done = !message.tool_calls?.length;
|
||||
if (done && (result.finish_reason !== 'stop' || typeof message.content !== 'string')) {
|
||||
throw new Error(`Reply incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
await archive(message);
|
||||
if (result.compaction) {
|
||||
context = [{ ...message, content: [
|
||||
result.compaction,
|
||||
...(message.content ? [{ type: 'text', text: message.content }] : []),
|
||||
] }];
|
||||
} else {
|
||||
context.push(message);
|
||||
}
|
||||
if (done) return message.content;
|
||||
const toolMessages = [];
|
||||
for (const call of message.tool_calls) {
|
||||
let output;
|
||||
try {
|
||||
if (call.function.name !== 'search_transcript') throw new Error('Unknown tool');
|
||||
const args = JSON.parse(call.function.arguments);
|
||||
output = await searchTranscript(args.query);
|
||||
} catch (error) {
|
||||
output = { error: error.message };
|
||||
}
|
||||
toolMessages.push({
|
||||
role: 'tool', tool_call_id: call.id, content: JSON.stringify(output),
|
||||
});
|
||||
}
|
||||
context.push(...toolMessages);
|
||||
for (const toolMessage of toolMessages) await archive(toolMessage);
|
||||
}
|
||||
throw new Error('The conversation reached its tool step limit.');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Full Code
|
||||
|
||||
This version includes both modes. Set `nativeCompaction` before starting a new
|
||||
chat. API failures reject `send()` so your UI can show sign-in, funds, and
|
||||
subscription actions, or another failure with its code and message:
|
||||
This version includes both modes. API failures reject `send()` so your UI can
|
||||
show sign-in, funds, and subscription actions, or another failure with its code
|
||||
and message:
|
||||
|
||||
```js
|
||||
const models = await puter.ai.listModels();
|
||||
@@ -121,8 +334,8 @@ const model = models.find(item => item.id === modelId)?.puterId;
|
||||
if (!model) throw new Error('The conversation model is unavailable.');
|
||||
const chatId = crypto.randomUUID();
|
||||
const prefix = `conversation:${chatId}:`;
|
||||
const system = 'Help with this conversation. Use search_transcript for older details.';
|
||||
let context = [];
|
||||
const system = 'Help with this conversation. Use search_transcript for older details.';
|
||||
let busy = false;
|
||||
const tools = [{
|
||||
type: 'function',
|
||||
@@ -213,20 +426,21 @@ async function send(text) {
|
||||
{ role: 'system', content: system }, ...context,
|
||||
], { model, normalize: true, ...(nativeCompaction ? { compaction: true } : {}), tools, max_tokens: 1024 });
|
||||
const message = result.message;
|
||||
const done = !message.tool_calls?.length;
|
||||
if (done && (result.finish_reason !== 'stop' || typeof message.content !== 'string')) {
|
||||
throw new Error(`Reply incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
await archive(message);
|
||||
if (result.compaction) {
|
||||
context = [{ ...message, content: [
|
||||
result.compaction, { type: 'text', text: message.content ?? '' },
|
||||
result.compaction,
|
||||
...(message.content ? [{ type: 'text', text: message.content }] : []),
|
||||
] }];
|
||||
} else {
|
||||
context.push(message);
|
||||
}
|
||||
if (!message.tool_calls?.length) {
|
||||
if (result.finish_reason !== 'stop' || typeof message.content !== 'string') {
|
||||
throw new Error(`Reply incomplete: ${result.finish_reason}`);
|
||||
}
|
||||
return message.content;
|
||||
}
|
||||
if (done) return message.content;
|
||||
const toolMessages = [];
|
||||
for (const call of message.tool_calls) {
|
||||
let output;
|
||||
try {
|
||||
@@ -236,12 +450,12 @@ async function send(text) {
|
||||
} catch (error) {
|
||||
output = { error: error.message };
|
||||
}
|
||||
const toolMessage = {
|
||||
toolMessages.push({
|
||||
role: 'tool', tool_call_id: call.id, content: JSON.stringify(output),
|
||||
};
|
||||
await archive(toolMessage);
|
||||
context.push(toolMessage);
|
||||
});
|
||||
}
|
||||
context.push(...toolMessages);
|
||||
for (const toolMessage of toolMessages) await archive(toolMessage);
|
||||
}
|
||||
throw new Error('The conversation reached its tool step limit.');
|
||||
} finally {
|
||||
|
||||
@@ -34,50 +34,12 @@ Appending only text keeps usage and reasoning metadata out of the displayed repl
|
||||
The default model is the cheap chat model. To offer other models, populate a
|
||||
picker from [`puter.ai.listModels()`](/AI/listModels/).
|
||||
|
||||
The full version below wraps both the initial call and the iterator in one
|
||||
`try...catch` so failures remain visible alongside any partial reply.
|
||||
|
||||
## Stop While Waiting
|
||||
|
||||
Keep the controller outside the loop so your Stop button can call
|
||||
`controller.abort()` at any time. Catch the signal's own reason as a user stop.
|
||||
Keep `partialReply` intact in that branch.
|
||||
|
||||
Disable the Start button during a request so another click cannot replace its
|
||||
controller. Restore both buttons in `finally`, including after a failed call.
|
||||
The full code creates the buttons and output elements itself.
|
||||
|
||||
## Distinguish Provider and Transport Failures
|
||||
|
||||
A provider failure arrives as a chunk with `type: 'error'` and a `message`.
|
||||
Handle it inside the loop and mark the answer as partial. The chunk's documented
|
||||
contract has no stable error code for a billing or sign-in decision.
|
||||
|
||||
A thrown failure arrives from the initial call or the iterator. The documented
|
||||
transport codes include `network_error`, `invalid_stream_response`, and
|
||||
`request_timeout`. Display the code and message, retain the partial answer, and
|
||||
let the user decide whether to start a new request.
|
||||
|
||||
The full code also shows actionable messages when a thrown error carries a
|
||||
sign-in, funds, or subscription code. Other failures remain visible with their
|
||||
code and message. A provider error chunk and a thrown failure use separate
|
||||
branches so a provider failure never looks like a completed reply.
|
||||
|
||||
## Keep the Partial Reply
|
||||
|
||||
Render with `textContent`, since model text can contain HTML. The `partialReply`
|
||||
variable remains available after completion, cancellation, or failure, for
|
||||
example for a Copy button. Mark it incomplete in the UI when stopped or failed.
|
||||
|
||||
Each Start click makes one application call. The code uses `fallback: false`
|
||||
and has no automatic retry. A failed or stopped call may already be billed, so
|
||||
starting again is an explicit user action. See [stream billing](/AI/chat/#return-value)
|
||||
for what stopping changes.
|
||||
|
||||
## Full Code
|
||||
|
||||
Run this in a browser page that loads Puter.js. The first click starts the
|
||||
request, and Stop works both during output and while waiting for another chunk:
|
||||
`controller.abort()` at any time. This code creates the buttons and output
|
||||
elements itself, and keeps the controller and the reply in variables that
|
||||
outlive one request:
|
||||
|
||||
```js
|
||||
const startButton = document.createElement('button');
|
||||
@@ -90,21 +52,106 @@ const status = document.createElement('p');
|
||||
document.body.append(startButton, stopButton, status, output);
|
||||
let controller = null;
|
||||
let partialReply = '';
|
||||
```
|
||||
|
||||
Catch the signal's own reason as a user stop. Keep `partialReply` intact in
|
||||
that branch. Disable the Start button during a request so another click cannot
|
||||
replace its controller. Restore both buttons in `finally`, including after a
|
||||
failed call:
|
||||
|
||||
```js
|
||||
async function streamReply(prompt) {
|
||||
if (controller) throw new Error('A reply is already running.');
|
||||
const active = new AbortController();
|
||||
controller = active;
|
||||
partialReply = '';
|
||||
output.textContent = '';
|
||||
startButton.disabled = true;
|
||||
stopButton.disabled = false;
|
||||
status.textContent = 'Receiving reply…';
|
||||
try {
|
||||
const stream = await puter.ai.chat(prompt, {
|
||||
stream: true, signal: active.signal, fallback: false,
|
||||
});
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.type === 'error') throw new Error(chunk.message);
|
||||
if (chunk.type === 'text') {
|
||||
partialReply += chunk.text;
|
||||
output.textContent = partialReply;
|
||||
}
|
||||
}
|
||||
status.textContent = active.signal.aborted ? 'Stopped. Partial reply kept.' : 'Reply complete.';
|
||||
} catch (error) {
|
||||
if (active.signal.aborted && error === active.signal.reason) {
|
||||
status.textContent = 'Stopped. Partial reply kept.';
|
||||
} else {
|
||||
status.textContent = 'Request failed. Partial reply kept.';
|
||||
console.error(error);
|
||||
}
|
||||
} finally {
|
||||
controller = null;
|
||||
startButton.disabled = false;
|
||||
stopButton.disabled = true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Connect the buttons to it. Stop works both during output and while waiting for
|
||||
another chunk, and leaving the page stops the request too:
|
||||
|
||||
```js
|
||||
stopButton.addEventListener('click', () => controller?.abort());
|
||||
startButton.addEventListener('click', () => {
|
||||
streamReply('Explain how rain forms in three paragraphs.');
|
||||
});
|
||||
window.addEventListener('pagehide', () => controller?.abort());
|
||||
```
|
||||
|
||||
## Distinguish Provider and Transport Failures
|
||||
|
||||
A provider failure arrives as a chunk with `type: 'error'` and a `message`.
|
||||
Handle it inside the loop and mark the answer as partial. The chunk's documented
|
||||
contract has no stable error code for a billing or sign-in decision.
|
||||
|
||||
A thrown failure arrives from the initial call or the iterator, so one
|
||||
`try...catch` wraps both. The documented transport codes include
|
||||
`network_error`, `invalid_stream_response`, and `request_timeout`. Display the
|
||||
code and message, retain the partial answer, and let the user decide whether to
|
||||
start a new request.
|
||||
|
||||
The `showFailure()` function turns a thrown failure into a status message. It
|
||||
shows an actionable message for a sign-in, funds, or subscription failure. A
|
||||
sign-in the user cancelled rejects as
|
||||
`{ error: { code: 'auth_canceled', message } }`, so the function reads the
|
||||
nested `error` object first. A session that expired and wasn't renewed rejects
|
||||
with `status: 401` and no code. Other failures remain visible with their code
|
||||
and message. A connection that fails before the stream starts rejects with
|
||||
neither, and gets a fixed message:
|
||||
|
||||
```js
|
||||
function showFailure(error) {
|
||||
const code = error?.code;
|
||||
if (['auth_required', 'auth_canceled', 'auth_failed'].includes(code)) {
|
||||
const failure = error?.error && typeof error.error === 'object' ? error.error : error;
|
||||
const code = failure?.code;
|
||||
if (code === 'auth_canceled' || failure?.status === 401) {
|
||||
status.textContent = 'Sign in to Puter, then start a new request.';
|
||||
} else if (code === 'insufficient_funds') {
|
||||
status.textContent = 'Add funds to your Puter account before starting another request.';
|
||||
} else if (code === 'subscription_required') {
|
||||
status.textContent = 'Choose a paid Puter plan before starting another request.';
|
||||
} else if (code || typeof failure?.message === 'string') {
|
||||
status.textContent = `Request failed (${code ?? 'unknown'}): ${failure.message ?? 'no message'}`;
|
||||
} else {
|
||||
status.textContent = `Request failed (${code ?? 'unknown'}): ${error?.message ?? String(error)}`;
|
||||
status.textContent = 'Request failed before the reply started. Check your connection, then start a new request.';
|
||||
}
|
||||
console.error(error);
|
||||
}
|
||||
```
|
||||
|
||||
Call it from the `catch` block of `streamReply()`. A provider error chunk and a
|
||||
thrown failure use separate branches so a provider failure never looks like a
|
||||
completed reply:
|
||||
|
||||
```js
|
||||
async function streamReply(prompt) {
|
||||
if (controller) throw new Error('A reply is already running.');
|
||||
const active = new AbortController();
|
||||
@@ -142,6 +189,160 @@ async function streamReply(prompt) {
|
||||
stopButton.disabled = true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Pass a rejection from `streamReply()` itself to the same function:
|
||||
|
||||
```js
|
||||
startButton.addEventListener('click', () => {
|
||||
streamReply('Explain how rain forms in three paragraphs.').catch(showFailure);
|
||||
});
|
||||
```
|
||||
|
||||
## Keep the Partial Reply
|
||||
|
||||
Render with `textContent`, since model text can contain HTML. The `partialReply`
|
||||
variable remains available after completion, cancellation, or failure, for
|
||||
example for a Copy button. Mark it incomplete in the UI when stopped or failed.
|
||||
|
||||
A reply can also end early without an error, for example at the model's token
|
||||
limit. The last chunk of a stream has `type: 'usage'` and carries a
|
||||
[`finish_reason`](/Objects/chatresponsechunk/). A value other than `stop`, such
|
||||
as `length` at the token limit, means the reply was cut off. This version of
|
||||
`streamReply()` reads it and marks the reply incomplete:
|
||||
|
||||
```js
|
||||
async function streamReply(prompt) {
|
||||
if (controller) throw new Error('A reply is already running.');
|
||||
const active = new AbortController();
|
||||
controller = active;
|
||||
partialReply = '';
|
||||
output.textContent = '';
|
||||
startButton.disabled = true;
|
||||
stopButton.disabled = false;
|
||||
status.textContent = 'Receiving reply…';
|
||||
try {
|
||||
const stream = await puter.ai.chat(prompt, {
|
||||
stream: true, signal: active.signal, fallback: false,
|
||||
});
|
||||
let finishReason;
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.type === 'error') {
|
||||
status.textContent = `Provider failed: ${chunk.message}. Partial reply kept.`;
|
||||
console.error('AI provider error', chunk.message);
|
||||
return;
|
||||
}
|
||||
if (chunk.type === 'text') {
|
||||
partialReply += chunk.text;
|
||||
output.textContent = partialReply;
|
||||
}
|
||||
if (chunk.type === 'usage') finishReason = chunk.finish_reason;
|
||||
}
|
||||
if (active.signal.aborted) {
|
||||
status.textContent = 'Stopped. Partial reply kept.';
|
||||
} else if (finishReason && finishReason !== 'stop') {
|
||||
status.textContent = `Reply cut off (${finishReason}). Partial reply kept.`;
|
||||
} else {
|
||||
status.textContent = 'Reply complete.';
|
||||
}
|
||||
} catch (error) {
|
||||
if (active.signal.aborted && error === active.signal.reason) {
|
||||
status.textContent = 'Stopped. Partial reply kept.';
|
||||
} else {
|
||||
showFailure(error);
|
||||
}
|
||||
} finally {
|
||||
controller = null;
|
||||
startButton.disabled = false;
|
||||
stopButton.disabled = true;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Each Start click makes one application call. The code uses `fallback: false`
|
||||
and has no automatic retry. A failed or stopped call may already be billed, so
|
||||
starting again is an explicit user action. See [stream billing](/AI/chat/#return-value)
|
||||
for what stopping changes.
|
||||
|
||||
## Full Code
|
||||
|
||||
Run this in a browser page that loads Puter.js. The first click starts the
|
||||
request, and Stop works both during output and while waiting for another chunk:
|
||||
|
||||
```js
|
||||
const startButton = document.createElement('button');
|
||||
startButton.textContent = 'Ask AI';
|
||||
const stopButton = document.createElement('button');
|
||||
stopButton.textContent = 'Stop';
|
||||
stopButton.disabled = true;
|
||||
const output = document.createElement('pre');
|
||||
const status = document.createElement('p');
|
||||
document.body.append(startButton, stopButton, status, output);
|
||||
let controller = null;
|
||||
let partialReply = '';
|
||||
|
||||
function showFailure(error) {
|
||||
const failure = error?.error && typeof error.error === 'object' ? error.error : error;
|
||||
const code = failure?.code;
|
||||
if (code === 'auth_canceled' || failure?.status === 401) {
|
||||
status.textContent = 'Sign in to Puter, then start a new request.';
|
||||
} else if (code === 'insufficient_funds') {
|
||||
status.textContent = 'Add funds to your Puter account before starting another request.';
|
||||
} else if (code === 'subscription_required') {
|
||||
status.textContent = 'Choose a paid Puter plan before starting another request.';
|
||||
} else if (code || typeof failure?.message === 'string') {
|
||||
status.textContent = `Request failed (${code ?? 'unknown'}): ${failure.message ?? 'no message'}`;
|
||||
} else {
|
||||
status.textContent = 'Request failed before the reply started. Check your connection, then start a new request.';
|
||||
}
|
||||
console.error(error);
|
||||
}
|
||||
|
||||
async function streamReply(prompt) {
|
||||
if (controller) throw new Error('A reply is already running.');
|
||||
const active = new AbortController();
|
||||
controller = active;
|
||||
partialReply = '';
|
||||
output.textContent = '';
|
||||
startButton.disabled = true;
|
||||
stopButton.disabled = false;
|
||||
status.textContent = 'Receiving reply…';
|
||||
try {
|
||||
const stream = await puter.ai.chat(prompt, {
|
||||
stream: true, signal: active.signal, fallback: false,
|
||||
});
|
||||
let finishReason;
|
||||
for await (const chunk of stream) {
|
||||
if (chunk.type === 'error') {
|
||||
status.textContent = `Provider failed: ${chunk.message}. Partial reply kept.`;
|
||||
console.error('AI provider error', chunk.message);
|
||||
return;
|
||||
}
|
||||
if (chunk.type === 'text') {
|
||||
partialReply += chunk.text;
|
||||
output.textContent = partialReply;
|
||||
}
|
||||
if (chunk.type === 'usage') finishReason = chunk.finish_reason;
|
||||
}
|
||||
if (active.signal.aborted) {
|
||||
status.textContent = 'Stopped. Partial reply kept.';
|
||||
} else if (finishReason && finishReason !== 'stop') {
|
||||
status.textContent = `Reply cut off (${finishReason}). Partial reply kept.`;
|
||||
} else {
|
||||
status.textContent = 'Reply complete.';
|
||||
}
|
||||
} catch (error) {
|
||||
if (active.signal.aborted && error === active.signal.reason) {
|
||||
status.textContent = 'Stopped. Partial reply kept.';
|
||||
} else {
|
||||
showFailure(error);
|
||||
}
|
||||
} finally {
|
||||
controller = null;
|
||||
startButton.disabled = false;
|
||||
stopButton.disabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
stopButton.addEventListener('click', () => controller?.abort());
|
||||
startButton.addEventListener('click', () => {
|
||||
|
||||
Reference in new issue
Block a user