-
Notifications
You must be signed in to change notification settings - Fork 43
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
7
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.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
7374f3f
feat(chat): add image generation with toggle button and inline rendering
vibegui 629e009
feat(chat): improve image mode UX and add image-generation capability
vibegui cd63c24
fix(chat): harden image generation from PR review findings
vibegui 6e396de
fix(chat): ensure image mode state resets consistently on refresh/new…
vibegui c1d30ab
fix(chat): show friendly error message when image generation fails
vibegui c043237
refactor(chat): convert image generation from if-block to built-in tool
vibegui 4bb39de
feat(chat): persist generated images to object storage
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
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
203 changes: 203 additions & 0 deletions
203
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,203 @@ | ||
| /** | ||
| * generate_image Built-in Tool | ||
| * | ||
| * Server-side tool that generates images using the AI SDK's generateImage() | ||
| * function. When object storage is available, images are persisted there and | ||
| * served via /api/files; otherwise they are inlined as base64 data URLs. | ||
| */ | ||
|
|
||
| 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 MEDIA_TYPE_EXT: Record<string, string> = { | ||
| "image/png": "png", | ||
| "image/jpeg": "jpg", | ||
| "image/webp": "webp", | ||
| "image/gif": "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)) { | ||
| return `Image generation failed: unsupported image type "${rawMediaType}". Please try a different model.`; | ||
| } | ||
|
|
||
| // Try to persist to object storage; fall back to inline base64 | ||
| let imageUrl: string; | ||
| if (ctx.objectStorage) { | ||
| const ext = MEDIA_TYPE_EXT[rawMediaType] ?? "png"; | ||
| const key = `generated-images/${threadId}/${toolCallId}.${ext}`; | ||
| await ctx.objectStorage.put(key, Buffer.from(base64, "base64"), { | ||
| contentType: rawMediaType, | ||
| }); | ||
| imageUrl = `/api/files/${key}`; | ||
| } else { | ||
| imageUrl = `data:${rawMediaType};base64,${base64}`; | ||
| } | ||
|
|
||
| // Write the image as a file part directly to the stream | ||
| writer.write({ | ||
| type: "file", | ||
| url: imageUrl, | ||
| 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); | ||
| // Return error as tool result instead of throwing — throwing from a tool's | ||
| // execute crashes the entire stream, while returning lets the model see the | ||
| // error and respond with a friendly message to the user. | ||
| return `Image generation failed: ${errorMsg}. Please try again or use a different image model.`; | ||
| } | ||
| }, | ||
| }); | ||
| } |
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
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.