Skip to content

capture failures in messages #101

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
126 changes: 126 additions & 0 deletions example/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,132 @@ export declare const components: {
>;
};
messages: {
addFailedMessage: FunctionReference<
"mutation",
"internal",
{
agentName?: string;
error?: string;
id?: string;
message?:
| {
content:
| string
| Array<
| {
providerOptions?: Record<string, Record<string, any>>;
text: string;
type: "text";
}
| {
image: string | ArrayBuffer;
mimeType?: string;
providerOptions?: Record<string, Record<string, any>>;
type: "image";
}
| {
data: string | ArrayBuffer;
filename?: string;
mimeType: string;
providerOptions?: Record<string, Record<string, any>>;
type: "file";
}
>;
providerOptions?: Record<string, Record<string, any>>;
role: "user";
}
| {
content:
| string
| Array<
| {
providerOptions?: Record<string, Record<string, any>>;
text: string;
type: "text";
}
| {
data: string | ArrayBuffer;
filename?: string;
mimeType: string;
providerOptions?: Record<string, Record<string, any>>;
type: "file";
}
| {
providerOptions?: Record<string, Record<string, any>>;
signature?: string;
text: string;
type: "reasoning";
}
| {
data: string;
providerOptions?: Record<string, Record<string, any>>;
type: "redacted-reasoning";
}
| {
args: any;
providerOptions?: Record<string, Record<string, any>>;
toolCallId: string;
toolName: string;
type: "tool-call";
}
>;
providerOptions?: Record<string, Record<string, any>>;
role: "assistant";
}
| {
content: Array<{
args?: any;
experimental_content?: Array<
| { text: string; type: "text" }
| { data: string; mimeType?: string; type: "image" }
>;
isError?: boolean;
providerOptions?: Record<string, Record<string, any>>;
result: any;
toolCallId: string;
toolName: string;
type: "tool-result";
}>;
providerOptions?: Record<string, Record<string, any>>;
role: "tool";
}
| {
content: string;
providerOptions?: Record<string, Record<string, any>>;
role: "system";
};
model?: string;
promptMessageId: string;
provider?: string;
providerMetadata?: Record<string, Record<string, any>>;
providerOptions?: Record<string, Record<string, any>>;
reasoning?: string;
reasoningDetails?: Array<
| { signature?: string; text: string; type: "text" }
| { data: string; type: "redacted" }
>;
sources?: Array<{
id: string;
providerOptions?: Record<string, Record<string, any>>;
sourceType: "url";
title?: string;
url: string;
}>;
threadId: string;
usage?: {
completionTokens: number;
promptTokens: number;
totalTokens: number;
};
userId?: string;
warnings?: Array<
| { details?: string; setting: string; type: "unsupported-setting" }
| { details?: string; tool: any; type: "unsupported-tool" }
| { message: string; type: "other" }
>;
},
string
>;
addMessages: FunctionReference<
"mutation",
"internal",
Expand Down
82 changes: 71 additions & 11 deletions src/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,15 +524,28 @@ export class Agent<
result.messageId = messageId;
result.order = order;
return result;
} catch (error) {
} catch (err) {
if (threadId && messageId) {
console.error("RollbackMessage", messageId);
const error = err instanceof Error ? err.message : String(err);
await ctx.runMutation(this.component.messages.rollbackMessage, {
messageId,
error: (error as Error).message,
error,
});
if (saveOutput) {
await ctx.runMutation(this.component.messages.addFailedMessage, {
promptMessageId: messageId,
threadId,
userId,
agentName: this.options.name,
model: aiArgs.model.modelId,
provider: aiArgs.model.provider,
error,
providerOptions: aiArgs.providerOptions,
});
}
}
throw error;
throw err;
}
}

Expand Down Expand Up @@ -613,6 +626,7 @@ export class Agent<
? new DeltaStreamer(this.component, ctx, opts.saveStreamDeltas, {
threadId,
userId,
promptMessageId: saveOutput ? messageId : undefined,
agentName: this.options.name,
model: aiArgs.model.modelId,
provider: aiArgs.model.provider,
Expand All @@ -638,16 +652,32 @@ export class Agent<
// console.log("onChunk", chunk);
return args.onChunk?.(event);
},
onError: async (error) => {
console.error("onError", error);
onError: async (err) => {
console.error("onError", err);
if (threadId && messageId && saveOutput) {
const error =
err.error instanceof Error ? err.error.message : String(err.error);
await ctx.runMutation(this.component.messages.rollbackMessage, {
messageId,
error: (error.error as Error).message,
error,
});
if (streamer) {
await streamer.fail(error);
} else {
// TODO: capture the parts that were generated so far for the failed message
await ctx.runMutation(this.component.messages.addFailedMessage, {
threadId,
userId,
promptMessageId: messageId,
agentName: this.options.name,
model: aiArgs.model.modelId,
provider: aiArgs.model.provider,
providerOptions: aiArgs.providerOptions,
error,
});
}
}
// TODO: update the streamer to error state
return args.onError?.(error);
return args.onError?.(err);
},
onStepFinish: async (step) => {
// console.log("onStepFinish", step);
Expand Down Expand Up @@ -775,6 +805,17 @@ export class Agent<
messageId,
error: (error as Error).message,
});

await ctx.runMutation(this.component.messages.addFailedMessage, {
threadId,
userId,
promptMessageId: messageId,
agentName: this.options.name,
model: aiArgs.model.modelId,
provider: aiArgs.model.provider,
providerOptions: aiArgs.providerOptions,
error: (error as Error).message,
});
}
throw error;
}
Expand Down Expand Up @@ -822,9 +863,28 @@ export class Agent<
const stream = streamObject<T>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
...(aiArgs as any),
onError: async (error) => {
console.error("onError", error);
return args.onError?.(error);
onError: async (err) => {
console.error("onError", err);
if (threadId && messageId && saveOutput) {
const error =
err.error instanceof Error ? err.error.message : String(err.error);
await ctx.runMutation(this.component.messages.rollbackMessage, {
messageId,
error,
});

await ctx.runMutation(this.component.messages.addFailedMessage, {
threadId,
userId,
promptMessageId: messageId,
agentName: this.options.name,
model: aiArgs.model.modelId,
provider: aiArgs.model.provider,
providerOptions: aiArgs.providerOptions,
error,
});
}
return args.onError?.(err);
},
onFinish: async (result) => {
if (threadId && messageId && saveOutput) {
Expand Down
42 changes: 35 additions & 7 deletions src/client/streaming.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import type {
SyncStreamsReturnValue,
} from "./types.js";
import { omit } from "convex-helpers";
import { convexToJson } from "convex/values";

/**
* A function that handles fetching stream deltas, used with the React hooks
Expand Down Expand Up @@ -164,6 +165,7 @@ export class DeltaStreamer {
#latestWrite: number = 0;
#ongoingWrite: Promise<void> | undefined;
#cursor: number = 0;
#draining: boolean = false;
public abortController: AbortController;

constructor(
Expand All @@ -172,6 +174,7 @@ export class DeltaStreamer {
options: true | StreamingOptions,
public readonly metadata: {
threadId: string;
promptMessageId: string | undefined;
agentName: string | undefined;
model: string | undefined;
provider: string | undefined;
Expand All @@ -196,12 +199,14 @@ export class DeltaStreamer {
if (metadata.abortSignal) {
metadata.abortSignal.addEventListener("abort", async () => {
if (this.streamId) {
await this.ctx.runMutation(this.component.streams.abort, {
streamId: this.streamId,
reason: "abortSignal",
});
const reason = metadata.abortSignal?.reason
? typeof metadata.abortSignal.reason === "string"
? metadata.abortSignal.reason
: JSON.stringify(convexToJson(metadata.abortSignal.reason))
: "abortSignal";
await this.fail(reason);
}
this.abortController.abort();
this.abortController.abort(metadata.abortSignal?.reason);
});
}
}
Expand All @@ -213,7 +218,7 @@ export class DeltaStreamer {
this.streamId = await this.ctx.runMutation(
this.component.streams.create,
{
...omit(this.metadata, ["abortSignal"]),
...omit(this.metadata, ["abortSignal", "promptMessageId"]),
order: this.#nextOrder,
stepOrder: this.#nextStepOrder,
},
Expand Down Expand Up @@ -249,7 +254,9 @@ export class DeltaStreamer {
// Now that we've sent the delta, check if we need to send another one.
if (
this.#nextParts.length > 0 &&
Date.now() - this.#latestWrite >= this.options.throttleMs
Date.now() - this.#latestWrite >= this.options.throttleMs &&
!this.abortController.signal.aborted &&
!this.#draining
) {
// We send again immediately with the accumulated deltas.
this.#ongoingWrite = this.#sendDelta();
Expand All @@ -275,6 +282,27 @@ export class DeltaStreamer {
};
}

public async fail(reason: string) {
if (this.streamId) {
this.#draining = true;
if (this.#ongoingWrite) {
await this.#ongoingWrite;
}
// TODO: const delta = this.#createDelta();
await this.ctx.runMutation(this.component.streams.abort, {
streamId: this.streamId,
reason,
// finalDelta: delta,
});
} else if (this.metadata.promptMessageId) {
await this.ctx.runMutation(this.component.messages.addFailedMessage, {
...omit(this.metadata, ["abortSignal", "order", "stepOrder"]),
promptMessageId: this.metadata.promptMessageId,
error: reason,
});
}
}

public async finish(messages: MessageDoc[]) {
if (this.#ongoingWrite) {
await this.#ongoingWrite;
Expand Down
Loading