-
Notifications
You must be signed in to change notification settings - Fork 40
Add image generation to chat UI #2708
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
vibegui
wants to merge
6
commits into
main
Choose a base branch
from
vibegui/image-gen-chat
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+575
−10
Open
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
02891a2
feat(chat): add image generation with toggle button and inline rendering
vibegui 0a215cd
feat(chat): improve image mode UX and add image-generation capability
vibegui 9eaab7c
fix(chat): harden image generation from PR review findings
vibegui 147f87a
fix(chat): ensure image mode state resets consistently on refresh/new…
vibegui 3c23705
fix(chat): show friendly error message when image generation fails
vibegui 1b0bcbb
refactor(chat): convert image generation from if-block to built-in tool
vibegui File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
182 changes: 182 additions & 0 deletions
182
apps/mesh/src/api/routes/decopilot/built-in-tools/generate-image.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,182 @@ | ||
| /** | ||
| * generate_image Built-in Tool | ||
| * | ||
| * Server-side tool that generates images using the AI SDK's generateImage() | ||
| * function. The image is written as a file part to the stream, and a short | ||
| * text result is returned to the model. | ||
| */ | ||
|
|
||
| import type { MeshContext } from "@/core/mesh-context"; | ||
| import type { MeshProvider } from "@/ai-providers/types"; | ||
| import { monitorLlmCall } from "@/monitoring/emit-llm-call"; | ||
| import { recordLlmCallMetrics } from "@/monitoring/record-llm-call-metrics"; | ||
| import type { UIMessageStreamWriter } from "ai"; | ||
| import { generateImage, tool, zodSchema } from "ai"; | ||
| import { z } from "zod"; | ||
| import type { ModelsConfig } from "../types"; | ||
|
|
||
| const ALLOWED_IMAGE_TYPES = new Set([ | ||
| "image/png", | ||
| "image/jpeg", | ||
| "image/webp", | ||
| "image/gif", | ||
| ]); | ||
|
|
||
| const GenerateImageInputSchema = z.object({ | ||
| prompt: z | ||
| .string() | ||
| .min(1) | ||
| .max(10_000) | ||
| .describe( | ||
| "Detailed description of the image to generate. Be specific about style, composition, colors, and subject.", | ||
| ), | ||
| aspect_ratio: z | ||
| .enum(["1:1", "16:9", "9:16", "4:3", "3:4"]) | ||
| .optional() | ||
| .describe("Aspect ratio for the generated image. Defaults to 1:1."), | ||
| }); | ||
|
|
||
| const GENERATE_IMAGE_DESCRIPTION = | ||
| "Generate an image from a text description. The generated image is displayed " + | ||
| "inline to the user. Use this when the user asks you to create, draw, or " + | ||
| "generate an image or picture."; | ||
|
|
||
| const GENERATE_IMAGE_ANNOTATIONS = { | ||
| readOnlyHint: true, | ||
| destructiveHint: false, | ||
| idempotentHint: false, | ||
| openWorldHint: true, | ||
| } as const; | ||
|
|
||
| export interface GenerateImageParams { | ||
| provider: MeshProvider; | ||
| imageModelId: string; | ||
| defaultAspectRatio?: string; | ||
| models: ModelsConfig; | ||
| organizationId: string; | ||
| agentId: string; | ||
| userId: string; | ||
| threadId: string; | ||
| } | ||
|
|
||
| export function createGenerateImageTool( | ||
| writer: UIMessageStreamWriter, | ||
| params: GenerateImageParams, | ||
| ctx: MeshContext, | ||
| ) { | ||
| const { | ||
| provider, | ||
| imageModelId, | ||
| defaultAspectRatio, | ||
| models, | ||
| organizationId, | ||
| agentId, | ||
| userId, | ||
| threadId, | ||
| } = params; | ||
|
|
||
| return tool({ | ||
| description: GENERATE_IMAGE_DESCRIPTION, | ||
| inputSchema: zodSchema(GenerateImageInputSchema), | ||
| execute: async ({ prompt, aspect_ratio }, { abortSignal, toolCallId }) => { | ||
| const aspectRatio = (aspect_ratio ?? defaultAspectRatio ?? "1:1") as | ||
| | `${number}:${number}` | ||
| | undefined; | ||
|
|
||
| const startTime = Date.now(); | ||
|
|
||
| try { | ||
| const result = await generateImage({ | ||
| model: provider.aiSdk.imageModel(imageModelId), | ||
| prompt, | ||
| aspectRatio, | ||
| abortSignal, | ||
| }); | ||
|
|
||
| const durationMs = Date.now() - startTime; | ||
| recordLlmCallMetrics({ | ||
| ctx, | ||
| organizationId, | ||
| modelId: imageModelId, | ||
| durationMs, | ||
| isError: false, | ||
| }); | ||
| monitorLlmCall({ | ||
| ctx, | ||
| organizationId, | ||
| agentId, | ||
| modelId: imageModelId, | ||
| modelTitle: imageModelId, | ||
| credentialId: models.credentialId, | ||
| threadId, | ||
| durationMs, | ||
| isError: false, | ||
| finishReason: "stop", | ||
| userId, | ||
| requestId: ctx.metadata.requestId, | ||
| userAgent: ctx.metadata.userAgent ?? null, | ||
| }); | ||
|
|
||
| const base64 = result.image.base64; | ||
| const rawMediaType = result.image.mediaType ?? "image/png"; | ||
| if (!ALLOWED_IMAGE_TYPES.has(rawMediaType)) { | ||
| throw new Error(`Unsupported generated image type: ${rawMediaType}`); | ||
| } | ||
|
|
||
| // Write the image as a file part directly to the stream | ||
| writer.write({ | ||
| type: "file", | ||
| url: `data:${rawMediaType};base64,${base64}`, | ||
| mediaType: rawMediaType, | ||
| }); | ||
|
|
||
| // Write tool metadata | ||
| writer.write({ | ||
| type: "data-tool-metadata", | ||
| id: toolCallId, | ||
| data: { | ||
| annotations: GENERATE_IMAGE_ANNOTATIONS, | ||
| latencyMs: durationMs, | ||
| }, | ||
| }); | ||
|
|
||
| return `Image generated successfully (${aspectRatio ?? "1:1"}).`; | ||
| } catch (error) { | ||
| // Don't record abort as an error | ||
| if (abortSignal?.aborted) { | ||
| throw error; | ||
| } | ||
|
|
||
| const durationMs = Date.now() - startTime; | ||
| recordLlmCallMetrics({ | ||
| ctx, | ||
| organizationId, | ||
| modelId: imageModelId, | ||
| durationMs, | ||
| isError: true, | ||
| errorType: error instanceof Error ? error.name : "Error", | ||
| }); | ||
| monitorLlmCall({ | ||
| ctx, | ||
| organizationId, | ||
| agentId, | ||
| modelId: imageModelId, | ||
| modelTitle: imageModelId, | ||
| credentialId: models.credentialId, | ||
| threadId, | ||
| durationMs, | ||
| isError: true, | ||
| errorMessage: error instanceof Error ? error.message : String(error), | ||
| userId, | ||
| requestId: ctx.metadata.requestId, | ||
| userAgent: ctx.metadata.userAgent ?? null, | ||
| }); | ||
|
|
||
| const errorMsg = error instanceof Error ? error.message : String(error); | ||
| throw new Error( | ||
| `Image generation failed: ${errorMsg}. Try describing what you'd like to see as an image.`, | ||
| ); | ||
| } | ||
| }, | ||
| }); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,30 @@ | ||
| # Image Generation — Follow-up Items | ||
|
|
||
| Tracked items deferred from the initial implementation PR. | ||
|
|
||
| ## 1. Base64 → Object Storage Migration | ||
|
|
||
| **Priority:** High | ||
| **Impact:** Database bloat, slow thread loading, large SSE payloads | ||
|
|
||
| Currently, generated images are stored as base64 data URLs directly in thread message `parts` JSON. A 1024x1024 PNG = 1-5MB per image in the database row. | ||
|
|
||
| **Fix:** Upload generated images to object storage (S3/R2) on the server, store only the HTTPS URL in the message parts. Add a size guard (reject images > 5MB decoded) as a stopgap until migration is complete. | ||
|
|
||
| ## 2. Conversation History Not Sent to Image Model | ||
|
|
||
| **Priority:** Medium | ||
| **Impact:** Multi-turn image refinement doesn't work | ||
|
|
||
| `generateImage()` is stateless — only the current message prompt is sent. Follow-up refinements like "make it darker" or "add a cat" won't have context from prior messages. Each generation is independent. | ||
|
|
||
| **Fix:** If multi-turn image generation is desired, switch to `streamText` with output modalities for models that support it (Gemini), or prepend conversation summary to the prompt. | ||
|
|
||
| ## 3. `toMetadataModelInfo` Doesn't Serialize `image-generation` Capability | ||
|
|
||
| **Priority:** Low | ||
| **Impact:** Server can't infer from metadata that a conversation used image generation | ||
|
|
||
| The `toMetadataModelInfo` helper in `chat-store.ts` maps capabilities to a boolean object but only includes `vision`, `text`, and `reasoning`. The `image-generation` capability is silently dropped. | ||
|
|
||
| **Fix:** Add `imageGeneration: caps.includes("image-generation") || undefined` to the capabilities mapping. |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.