Skip to content
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
2 changes: 2 additions & 0 deletions example/convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ import type * as usage_tracking_tables from "../usage_tracking/tables.js";
import type * as usage_tracking_usageHandler from "../usage_tracking/usageHandler.js";
import type * as utils from "../utils.js";
import type * as workflows_chaining from "../workflows/chaining.js";
import type * as workflows_coordination from "../workflows/coordination.js";

import type {
ApiFromModules,
Expand Down Expand Up @@ -98,6 +99,7 @@ declare const fullApi: ApiFromModules<{
"usage_tracking/usageHandler": typeof usage_tracking_usageHandler;
utils: typeof utils;
"workflows/chaining": typeof workflows_chaining;
"workflows/coordination": typeof workflows_coordination;
}>;

/**
Expand Down
18 changes: 18 additions & 0 deletions example/convex/workflows/coordination.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/// <reference types="vite/client" />
import { expect, test } from "vitest";
import { api } from "../_generated/api.js";
import { initConvexTest } from "../setup.test.js";

test("orchestration preserves the planned agent handoff", async () => {
const result = await initConvexTest().action(
api.workflows.coordination.orchestrate,
{ prompt: "Plan a small release" },
);

expect(result.steps.map(({ agent }) => agent)).toEqual([
"coordinator",
"analyst",
"critic",
"coordinator",
]);
});
Comment on lines +6 to +18

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Determine which language model the example agents use under test.
fd -t f 'config.ts' example/convex | xargs -r cat -n
rg -n 'MockLanguageModel|mock|languageModel' example/convex --glob '!**/node_modules/**' -C2

Repository: get-convex/agent

Length of output: 6241


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- coordination test ---'
cat -n example/convex/workflows/coordination.test.ts
printf '%s\n' '--- coordination implementation ---'
fd -t f . example/convex/workflows | sort
rg -n 'orchestrate|generateText|Agent|defaultConfig|languageModel|initConvexTest' example/convex/workflows example/convex/agents example/convex --glob '*.ts' -C3
printf '%s\n' '--- model selection ---'
cat -n example/convex/modelsForDemo.ts
printf '%s\n' '--- test and package configuration ---'
fd -t f 'package.json|vitest.config.*|vite.config.*|test*.ts' . | sort | head -80
rg -n 'vitest|convexTest|environment|ANTHROPIC_API_KEY|OPENAI_API_KEY|GROQ_API_KEY' package.json example package.json .github --glob '*.json' --glob '*.ts' --glob '*.yml' --glob '*.yaml' -C2

Repository: get-convex/agent

Length of output: 50373


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- model selection source ---'
cat -n example/convex/modelsForDemo.ts
printf '%s\n' '--- test setup ---'
cat -n example/convex/setup.test.ts
printf '%s\n' '--- coordination orchestration ---'
sed -n '140,166p' example/convex/workflows/coordination.ts
printf '%s\n' '--- test commands and CI environment ---'
rg -n 'example|vitest|convex test|API_KEY|ANTHROPIC|OPENAI|GROQ' \
  package.json example/package.json .github --glob '*.json' --glob '*.yml' --glob '*.yaml' --glob '*.ts' -C2 || true
printf '%s\n' '--- environment-dependent model verifier ---'
python3 - <<'PY'
from pathlib import Path
import re

source = Path("example/convex/modelsForDemo.ts").read_text()
branches = re.findall(
    r'if \(process\.env\.([A-Z0-9_]+)\).*?languageModel = ([^;]+);',
    source,
    flags=re.S,
)
print("branches:", [(name, expr.strip()) for name, expr in branches])
for env in ({}, {"ANTHROPIC_API_KEY": "x"}, {"OPENAI_API_KEY": "x"}, {"GROQ_API_KEY": "x"}):
    selected = "mockModel({})"
    for name, expr in branches:
        if env.get(name):
            selected = expr.strip()
            break
    print("env =", sorted(env), "=>", selected)
print("orchestrate generateText calls:", len(re.findall(r'\.generateText\(', Path("example/convex/workflows/coordination.ts").read_text()[Path("example/convex/workflows/coordination.ts").read_text().find("export const orchestrate"):]))
PY

Repository: get-convex/agent

Length of output: 5728


🏁 Script executed:

#!/bin/bash
set -e
printf '%s\n' '--- repository test and CI configuration ---'
find .github -maxdepth 3 -type f -print 2>/dev/null | sort || true
rg -n 'vitest|npm test|API_KEY|ANTHROPIC|OPENAI|GROQ|environment|env:' \
  package.json .github example --glob '*.json' --glob '*.yml' --glob '*.yaml' --glob '*.ts' -C2 || true
printf '%s\n' '--- deterministic model-selection check ---'
python3 - <<'PY'
from pathlib import Path

source = Path("example/convex/modelsForDemo.ts").read_text()
checks = [
    ("ANTHROPIC_API_KEY", 'anthropic.chat("claude-opus-4-20250514")'),
    ("OPENAI_API_KEY", 'openai.chat("gpt-4o-mini")'),
    ("GROQ_API_KEY", 'groq.languageModel('),
]
for env_name, model in checks:
    print(f"{env_name}: live provider branch present -> {model}")
print("fallback: languageModel = mockModel({})")
orchestrate = Path("example/convex/workflows/coordination.ts").read_text()
start = orchestrate.index("export const orchestrate")
end = orchestrate.index("\n});", start)
body = orchestrate[start:end]
print("orchestrate generateText calls:", body.count(".generateText("))
print("test model override:", "languageModel:" in Path("example/convex/workflows/coordination.test.ts").read_text())
PY

Repository: get-convex/agent

Length of output: 5210


Use a test-only mock model for orchestrate. defaultConfig selects a live Anthropic, OpenAI, or Groq model when the corresponding API key exists. The test has no model override, so it can make four live network calls.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@example/convex/workflows/coordination.test.ts` around lines 6 - 18, Update
the orchestration test around orchestrate to supply a deterministic test-only
mock model through the action configuration or supported model override. Ensure
all agent handoffs use the mock instead of defaultConfig’s live Anthropic,
OpenAI, or Groq selection, while preserving the existing agent-order assertion.

311 changes: 311 additions & 0 deletions example/convex/workflows/coordination.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,311 @@
// See the docs at https://docs.convex.dev/agents/workflows
import { Agent, createTool, stepCountIs } from "@convex-dev/agent";
import {
defineEvent,
type WorkflowId,
WorkflowManager,
vWorkflowId,
} from "@convex-dev/workflow";
import { type Infer, v } from "convex/values";
import { z } from "zod/v3";
import { components, internal } from "../_generated/api.js";
import { action, mutation, query } from "../_generated/server.js";
import { defaultConfig } from "../agents/config.js";

const resultValidator = v.object({
steps: v.array(v.object({ agent: v.string(), output: v.string() })),
});

type ExampleResult = Infer<typeof resultValidator>;

const standaloneScope = { userId: "advanced-workflow-example" };

const analystAgent = new Agent(components.agent, {
name: "Analyst",
instructions:
"Analyze the request using concrete facts, constraints, and tradeoffs. Keep responses under 120 words.",
...defaultConfig,
});

const creativeAgent = new Agent(components.agent, {
name: "Creative",
instructions:
"Generate practical, original options for the request. Keep responses under 120 words.",
...defaultConfig,
});

const criticAgent = new Agent(components.agent, {
name: "Critic",
instructions:
"Find risks, weak assumptions, and useful improvements. Keep responses under 120 words.",
...defaultConfig,
});

const coordinatorAgent = new Agent(components.agent, {
name: "Coordinator",
instructions:
"Coordinate specialists and produce concise, actionable answers. Keep responses under 160 words.",
...defaultConfig,
});

const reactAgent = new Agent(components.agent, {
name: "ReAct Agent",
instructions:
"Reason about the request, call both available tools, then give a concise recommendation based on their results.",
tools: {
lookupProjectFacts: createTool({
description: "Look up fixed facts about the example software project",
inputSchema: z.object({
focus: z.string().describe("The project area to inspect"),
}),
execute: async (_ctx, { focus }) => ({
focus,
teamSize: 3,
releaseWindowDays: 10,
constraints: ["No new service", "Keep the first release small"],
}),
}),
estimateEffort: createTool({
description:
"Estimate implementation days from task count and complexity",
inputSchema: z.object({
tasks: z.number().int().positive(),
complexity: z.enum(["low", "medium", "high"]),
}),
execute: async (_ctx, { tasks, complexity }) => ({
days: Math.ceil(tasks * { low: 0.5, medium: 1, high: 2 }[complexity]),
}),
}),
},
stopWhen: stepCountIs(5),
...defaultConfig,
});

const specialists = {
analyst: analystAgent,
creative: creativeAgent,
critic: criticAgent,
};

/** Route a request with one LLM call, then invoke only the selected agent. */
export const dynamicRouting = action({
args: { prompt: v.string() },
returns: resultValidator,
handler: async (ctx, { prompt }): Promise<ExampleResult> => {
const {
object: { route },
} = await coordinatorAgent.generateObject(ctx, standaloneScope, {
prompt: `Choose the best specialist for this request: ${prompt}`,
schema: z.object({
route: z.enum(["analyst", "creative", "critic"]),
}),
});
const response = await specialists[route].generateText(
ctx,
standaloneScope,
{ prompt },
);
return {
steps: [
{ agent: "Router", output: `Selected ${route}` },
{ agent: route, output: response.text },
],
};
},
});

/** Run independent specialists in parallel, then synthesize their reports. */
export const fanOut = action({
args: { prompt: v.string() },
returns: resultValidator,
handler: async (ctx, { prompt }): Promise<ExampleResult> => {
const reports = await Promise.all(
Object.entries(specialists).map(async ([name, agent]) => ({
agent: name,
output: (await agent.generateText(ctx, standaloneScope, { prompt }))
.text,
})),
);
const combined = await coordinatorAgent.generateText(ctx, standaloneScope, {
prompt: `Combine these specialist reports into one answer to "${prompt}":\n\n${reports
.map(({ agent, output }) => `${agent}: ${output}`)
.join("\n\n")}`,
});
return {
steps: [...reports, { agent: "coordinator", output: combined.text }],
};
},
});

/** Give agents distinct sequential responsibilities in one controlled flow. */
export const orchestrate = action({
args: { prompt: v.string() },
returns: resultValidator,
handler: async (ctx, { prompt }): Promise<ExampleResult> => {
const plan = await coordinatorAgent.generateText(ctx, standaloneScope, {
prompt: `Create a short plan for answering: ${prompt}`,
});
const analysis = await analystAgent.generateText(ctx, standaloneScope, {
prompt: `Execute this plan for "${prompt}":\n${plan.text}`,
});
const critique = await criticAgent.generateText(ctx, standaloneScope, {
prompt: `Review this analysis and name the important corrections:\n${analysis.text}`,
});
const final = await coordinatorAgent.generateText(ctx, standaloneScope, {
prompt: `Answer "${prompt}" using this analysis and critique.\n\nAnalysis: ${analysis.text}\n\nCritique: ${critique.text}`,
});
return {
steps: [
{ agent: "coordinator", output: plan.text },
{ agent: "analyst", output: analysis.text },
{ agent: "critic", output: critique.text },
{ agent: "coordinator", output: final.text },
],
};
},
});

/** Let the model alternate between reasoning and deterministic tool actions. */
export const reasonAndAct = action({
args: { prompt: v.string() },
returns: resultValidator,
handler: async (ctx, { prompt }): Promise<ExampleResult> => {
const response = await reactAgent.generateText(ctx, standaloneScope, {
prompt,
});
return { steps: [{ agent: "ReAct agent", output: response.text }] };
},
});

/** Let several agents contribute to the same persistent conversation thread. */
export const agentNetwork = action({
args: { prompt: v.string() },
returns: resultValidator,
handler: async (ctx, { prompt }): Promise<ExampleResult> => {
const { threadId } = await coordinatorAgent.createThread(ctx, {
userId: standaloneScope.userId,
title: `Agent network: ${prompt}`,
});
const turns = [
["analyst", analystAgent, `Analyze this request: ${prompt}`],
[
"creative",
creativeAgent,
"Read the earlier analysis in this thread and propose better options.",
],
[
"critic",
criticAgent,
"Review the earlier messages and identify the strongest option and its main risk.",
],
[
"coordinator",
coordinatorAgent,
"Use the full discussion in this thread to give the final answer.",
],
] as const;
const steps: ExampleResult["steps"] = [];
for (const [agentName, agent, turnPrompt] of turns) {
const response = await agent.generateText(
ctx,
{ threadId },
{ prompt: turnPrompt },
);
steps.push({ agent: agentName, output: response.text });
}
return { steps };
},
});

const workflow = new WorkflowManager(components.workflow);
const revisionRequested = defineEvent({
name: "revisionRequested",
validator: v.string(),
});

export const writeForReview = coordinatorAgent.asTextAction({});

/** Pause durably until feedback arrives, then resume from the recorded step. */
export const reviewWorkflow = workflow.define({
args: { prompt: v.string() },
returns: v.string(),
handler: async (step, { prompt }): Promise<string> => {
const { text: draft } = await step.runAction(
internal.workflows.coordination.writeForReview,
{
userId: standaloneScope.userId,
prompt: `Write a short draft for: ${prompt}`,
},
{ name: "writeDraft", retry: true },
);
const feedback = await step.awaitEvent(revisionRequested);
const { text: revision } = await step.runAction(
internal.workflows.coordination.writeForReview,
{
userId: standaloneScope.userId,
prompt: `Revise this draft using the feedback.\n\nDraft: ${draft}\n\nFeedback: ${feedback}`,
},
{ name: "reviseDraft", retry: true },
);
return revision;
},
});

export const startReviewWorkflow = mutation({
args: { prompt: v.string() },
returns: vWorkflowId,
handler: (ctx, { prompt }): Promise<WorkflowId> =>
workflow.start(
ctx,
internal.workflows.coordination.reviewWorkflow,
{ prompt },
{ startAsync: true },
),
});

export const resumeReviewWorkflow = mutation({
args: { workflowId: vWorkflowId, feedback: v.string() },
returns: v.null(),
handler: async (ctx, { workflowId, feedback }) => {
await workflow.sendEvent(ctx, {
...revisionRequested,
workflowId,
value: feedback,
});
return null;
},
});

export const reviewWorkflowStatus = query({
args: { workflowId: vWorkflowId },
returns: v.union(
v.object({
state: v.union(v.literal("running"), v.literal("waiting")),
}),
v.object({ state: v.literal("completed"), result: v.string() }),
v.object({ state: v.literal("failed"), error: v.string() }),
v.object({ state: v.literal("canceled") }),
),
handler: async (ctx, { workflowId }) => {
const status = await workflow.status(ctx, workflowId);
switch (status.type) {
case "inProgress":
return {
state: status.running.some((step) => step.kind === "event")
? ("waiting" as const)
: ("running" as const),
};
case "completed":
if (typeof status.result !== "string") {
throw new Error("Review workflow returned a non-string result");
}
return { state: "completed" as const, result: status.result };
case "failed":
return { state: "failed" as const, error: status.error };
case "canceled":
return { state: "canceled" as const };
default:
return status satisfies never;
}
},
});
14 changes: 14 additions & 0 deletions example/ui/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import RagBasic from "./rag/RagBasic";
import { StrictMode } from "react";
import StreamArray from "./objects/StreamArray";
import ChatApproval from "./chat/ChatApproval";
import { AgentCoordination } from "./workflows/AgentCoordination";

const convex = new ConvexReactClient(import.meta.env.VITE_CONVEX_URL as string);

Expand Down Expand Up @@ -46,6 +47,7 @@ export function App() {
<Route path="/rag-basic" element={<RagBasic />} />
<Route path="/rate-limiting" element={<RateLimiting />} />
<Route path="/weather-fashion" element={<WeatherFashion />} />
<Route path="/advanced-workflows" element={<AgentCoordination />} />
<Route path="/stream-array" element={<StreamArray />} />
<Route path="/chat-approval" element={<ChatApproval />} />
</Routes>
Expand Down Expand Up @@ -152,6 +154,18 @@ function Index() {
with an optional reason.
</p>
</li>
<li className="border rounded p-4 hover:shadow transition">
<Link
to="/advanced-workflows"
className="text-xl font-semibold text-indigo-700 hover:underline"
>
Advanced Workflows
</Link>
<p className="mt-2 text-gray-700">
Demonstrates dynamic routing, parallel fan-out, multi-agent
orchestration, ReAct, agent networks, and durable pause/resume.
</p>
</li>
</ul>
<div className="mt-8 text-sm text-gray-500">
More examples coming soon!
Expand Down
Loading