-
-
Notifications
You must be signed in to change notification settings - Fork 8
feat: Integrate Vercel Queues for asynchronous resolution search #702
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -12,7 +12,8 @@ import type { FeatureCollection } from 'geojson' | |
| import { Spinner } from '@/components/ui/spinner' | ||
| import { Section } from '@/components/section' | ||
| import { FollowupPanel } from '@/components/followup-panel' | ||
| import { inquire, researcher, taskManager, querySuggestor, resolutionSearch, type DrawnFeature } from '@/lib/agents' | ||
| import { inquire, researcher, taskManager, querySuggestor, type DrawnFeature } from '@/lib/agents' | ||
| import { send } from '@vercel/queue'; | ||
| import { writer } from '@/lib/agents/writer' | ||
| import { saveChat, getSystemPrompt } from '@/lib/actions/chat' | ||
| import { Chat, AIMessage } from '@/lib/types' | ||
|
|
@@ -101,96 +102,12 @@ async function submit(formData?: FormData, skip?: boolean) { | |
|
|
||
| async function processResolutionSearch() { | ||
| try { | ||
| const streamResult = await resolutionSearch(messages, timezone, drawnFeatures, location); | ||
|
|
||
| let fullSummary = ''; | ||
| for await (const partialObject of streamResult.partialObjectStream) { | ||
| if (partialObject.summary) { | ||
| fullSummary = partialObject.summary; | ||
| summaryStream.update(fullSummary); | ||
| } | ||
| } | ||
|
|
||
| const analysisResult = await streamResult.object; | ||
| summaryStream.done(analysisResult.summary || 'Analysis complete.'); | ||
|
|
||
| if (analysisResult.geoJson) { | ||
| uiStream.append( | ||
| <GeoJsonLayer | ||
| id={groupeId} | ||
| data={analysisResult.geoJson as FeatureCollection} | ||
| /> | ||
| ); | ||
| } | ||
|
|
||
| messages.push({ role: 'assistant', content: analysisResult.summary || 'Analysis complete.' }); | ||
|
|
||
| const sanitizedMessages: CoreMessage[] = messages.map((m: any) => { | ||
| if (Array.isArray(m.content)) { | ||
| return { | ||
| ...m, | ||
| content: m.content.filter((part: any) => part.type !== 'image') | ||
| } as CoreMessage | ||
| } | ||
| return m | ||
| }) | ||
|
|
||
| const currentMessages = aiState.get().messages; | ||
| const sanitizedHistory = currentMessages.map((m: any) => { | ||
| if (m.role === "user" && Array.isArray(m.content)) { | ||
| return { | ||
| ...m, | ||
| content: m.content.map((part: any) => | ||
| part.type === "image" ? { ...part, image: "IMAGE_PROCESSED" } : part | ||
| ) | ||
| } | ||
| } | ||
| return m | ||
| }); | ||
| const relatedQueries = await querySuggestor(uiStream, sanitizedMessages); | ||
| uiStream.append( | ||
| <Section title="Follow-up"> | ||
| <FollowupPanel /> | ||
| </Section> | ||
| ); | ||
|
|
||
| await new Promise(resolve => setTimeout(resolve, 500)); | ||
|
|
||
| aiState.done({ | ||
| ...aiState.get(), | ||
| messages: [ | ||
| ...aiState.get().messages, | ||
| { | ||
| id: groupeId, | ||
| role: 'assistant', | ||
| content: analysisResult.summary || 'Analysis complete.', | ||
| type: 'response' | ||
| }, | ||
| { | ||
| id: groupeId, | ||
| role: 'assistant', | ||
| content: JSON.stringify({ | ||
| ...analysisResult, | ||
| image: dataUrl, | ||
| mapboxImage: mapboxDataUrl, | ||
| googleImage: googleDataUrl | ||
| }), | ||
| type: 'resolution_search_result' | ||
| }, | ||
| { | ||
| id: groupeId, | ||
| role: 'assistant', | ||
| content: JSON.stringify(relatedQueries), | ||
| type: 'related' | ||
| }, | ||
| { | ||
| id: groupeId, | ||
| role: 'assistant', | ||
| content: 'followup', | ||
| type: 'followup' | ||
| } | ||
| ] | ||
| }); | ||
| await send('resolution-search', { messages, timezone, drawnFeatures, location }); | ||
| summaryStream.update('Resolution search task enqueued. Please check back later for results.'); | ||
| summaryStream.done(); | ||
| isGenerating.done(false); | ||
| uiStream.done(); | ||
| return; // Exit early as the actual processing will happen in the queue | ||
|
Comment on lines
+105
to
+110
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 2. Queued results never surfaced The resolution_search server action now only enqueues a job and closes UI streams without writing any assistant response/resolution_search_result messages to aiState, so chats won’t be saved and there is no in-repo mechanism to later render the background result. Users will see “enqueued” once, but the actual analysis output can’t appear in history/reload/share flows. Agent Prompt
|
||
| } catch (error) { | ||
| console.error('Error in resolution search:', error); | ||
| summaryStream.error(error); | ||
|
|
||
| Original file line number | Diff line number | Diff line change | ||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| @@ -0,0 +1,18 @@ | ||||||||||||||||
| import { handleCallback } from '@vercel/queue'; | ||||||||||||||||
| import { resolutionSearch } from '@/lib/agents/resolution-search'; | ||||||||||||||||
| import { CoreMessage } from 'ai'; | ||||||||||||||||
|
|
||||||||||||||||
| export const POST = handleCallback(async (message: { messages: CoreMessage[], timezone: string, drawnFeatures?: any[], location?: { lat: number, lng: number } }, metadata) => { | ||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win Type the message payload with
♻️ Proposed fix import { handleCallback } from '`@vercel/queue`';
import { resolutionSearch } from '`@/lib/agents/resolution-search`';
import { CoreMessage } from 'ai';
+import type { DrawnFeature } from '`@/lib/agents/resolution-search`';
-export const POST = handleCallback(async (message: { messages: CoreMessage[], timezone: string, drawnFeatures?: any[], location?: { lat: number, lng: number } }, metadata) => {
+export const POST = handleCallback(async (message: { messages: CoreMessage[], timezone: string, drawnFeatures?: DrawnFeature[], location?: { lat: number, lng: number } }, metadata) => {📝 Committable suggestion
Suggested change
🤖 Prompt for AI Agents |
||||||||||||||||
| console.log(`Processing resolution search message ${metadata.messageId} for topic ${metadata.topicName}`); | ||||||||||||||||
| try { | ||||||||||||||||
| // Execute the resolutionSearch logic asynchronously | ||||||||||||||||
| const result = await resolutionSearch(message.messages, message.timezone, message.drawnFeatures, message.location); | ||||||||||||||||
| console.log(`Resolution search message ${metadata.messageId} processed successfully.`); | ||||||||||||||||
| // In a real application, you would likely store this result in a database | ||||||||||||||||
| // or notify the original requestor through a webhook or websocket. | ||||||||||||||||
| return { status: 'success', result }; | ||||||||||||||||
|
Comment on lines
+5
to
+13
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 1. Non-serializable queue result The queue callback returns the streamObject result wrapper from resolutionSearch instead of materializing the final structured object, so the returned value is not a plain JSON payload and the analysis result is never concretely produced/consumed. This can break the callback contract and prevents any usable result from being stored or forwarded. Agent Prompt
Comment on lines
+5
to
+13
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🗄️ Data Integrity & Integration | 🔵 Trivial | 🏗️ Heavy lift Implement the TODO: persist or forward the result. The comment on lines 11-12 correctly flags that Want me to sketch a persistence + notification path (e.g., write to a datastore keyed by a job id returned from 🤖 Prompt for AI Agents |
||||||||||||||||
| } catch (error) { | ||||||||||||||||
| console.error(`Error processing resolution search message ${metadata.messageId}:`, error); | ||||||||||||||||
| throw error; // Re-throw to trigger retry mechanism | ||||||||||||||||
| } | ||||||||||||||||
|
Comment on lines
+14
to
+17
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 3. Invalid timezone retry storm The queue worker rethrows all errors to trigger retries, but resolutionSearch uses a user-provided timezone in toLocaleString, which throws on invalid timezones; a permanently bad payload will be retried repeatedly. This can cause avoidable queue backlogs and repeated failures from a single malformed request. Agent Prompt
|
||||||||||||||||
| }); | ||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| { | ||
| "functions": { | ||
| "app/api/queues/resolution-search/route.ts": { | ||
| "experimentalTriggers": [ | ||
| { "type": "queue/v2beta", "topic": "resolution-search" } | ||
| ] | ||
| } | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win
Consider an idempotency key for the enqueue call.
send()supports deduplication: idempotencyKey provides deduplication for the full retention window. SinceprocessResolutionSearchis fire-and-forget and not obviously guarded against duplicate invocation (e.g., double form submits, client retries), passing a stableidempotencyKey(derived from the request/groupeId) would prevent duplicate resolution-search jobs from being enqueued and processed.🤖 Prompt for AI Agents