Files
upstream-mirror a774ac673a
Some checks failed
Deploy analytics worker / Deploy analytics worker to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
i18n upload strings / Upload latest strings (push) Failing after 1s
Deploy bemo / Deploy bemo to ${{ (github.ref == 'refs/heads/bemo-production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Failing after 1s
Deploy grafana resources / ${{ github.event_name == 'push' && 'Deploy grafana resources' || 'Validate grafana resources (dry run)' }} (push) Failing after 0s
End to end tests (dotcom) / Check for relevant changes (push) Failing after 0s
End to end tests (examples) / Check for relevant changes (push) Failing after 0s
End to end tests (mermaid readability) / Check for relevant changes (push) Failing after 1s
End to end tests (perf) / Check for relevant changes (push) Failing after 0s
Publish editor extensions / Publish editor extensions (push) Failing after 1s
Publish SDK packages / Remove the publish-packages label (push) Has been skipped
Checks / Tests & checks (push) Has been cancelled
Checks / Build all projects (push) Has been cancelled
Deploy templates / Deploy templates (push) Has been cancelled
End to end tests (dotcom) / End to end tests (dotcom) (push) Has been cancelled
End to end tests (mermaid readability) / End to end tests (mermaid readability) (push) Has been cancelled
End to end tests (perf) / End to end tests (perf) (push) Has been cancelled
Deploy .com / Deploy dotcom to ${{ (github.ref == 'refs/heads/production' && 'production') || (github.ref == 'refs/heads/main' && 'staging') || 'preview' }} (push) Has been cancelled
End to end tests (examples) / End to end tests (examples) (push) Has been cancelled
Publish SDK packages / Publish SDK packages (push) Has been cancelled
Publish SDK packages / Tell user released version (push) Has been cancelled
Publish SDK packages / Publishes code templates to separate repositories (push) Has been cancelled
Publish SDK packages / Deploys the template demos with the new SDK version (push) Has been cancelled
snapshot of https://github.com/tldraw/tldraw.git (main, 2026-09-23; blobs > 131072B omitted)
2026-09-23 16:12:52 +05:00

117 lines
3.4 KiB
TypeScript

import { IRequest } from 'itty-router'
import { resolveImage } from '../providers/types'
interface GenerateTextRequest {
input?: string
prompt: string
}
/**
* POST /api/generate-text
*
* Takes an optional input (image or text) and a prompt, then calls
* google/gemini-3.5-flash on Replicate to generate text.
* Falls back to a placeholder if no API token is configured.
*/
export async function handleGenerateText(request: IRequest, env: Env) {
const body = (await request.json()) as GenerateTextRequest
if (!body.prompt) {
return new Response(JSON.stringify({ error: 'prompt is required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
})
}
const apiToken = env.REPLICATE_API_TOKEN
if (!apiToken) {
return new Response(JSON.stringify(generateTextPlaceholder(body)), {
headers: { 'Content-Type': 'application/json' },
})
}
// Coerce input to string so downstream .startsWith() never crashes
const inputStr = body.input != null ? String(body.input) : null
// Detect whether the input is an image or text
const isImage =
inputStr != null &&
(inputStr.startsWith('data:image/') ||
inputStr.startsWith('/api/images/') ||
inputStr.startsWith('https://') ||
inputStr.startsWith('http://'))
try {
// Build the prompt — if input is text, prepend it to the prompt
let prompt = body.prompt
if (inputStr && !isImage) {
prompt = `Context:\n${inputStr}\n\n${body.prompt}`
}
// Build the images array if we have an image input
const images: string[] = []
if (inputStr && isImage) {
const { dataUrl } = await resolveImage(inputStr, env)
images.push(dataUrl)
}
const input: Record<string, unknown> = {
prompt,
max_output_tokens: 1024,
}
if (images.length > 0) {
input.images = images
}
const response = await fetch(
'https://api.replicate.com/v1/models/google/gemini-3.5-flash/predictions',
{
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${apiToken}`,
Prefer: 'wait',
},
body: JSON.stringify({ input }),
}
)
if (!response.ok) {
const err = await response.text()
throw new Error(`Replicate error: ${response.status} ${err}`)
}
const result = (await response.json()) as { output?: string | string[] }
const output = Array.isArray(result.output) ? result.output.join('') : result.output
if (!output) throw new Error('No output from text generation')
return new Response(JSON.stringify({ text: output }), {
headers: { 'Content-Type': 'application/json' },
})
} catch (e: any) {
console.error('Generate text error:', e)
return new Response(JSON.stringify({ error: e.message ?? 'Text generation failed' }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
})
}
}
function generateTextPlaceholder(body: GenerateTextRequest): { text: string } {
const inputStr = body.input != null ? String(body.input) : null
const isImage =
inputStr != null &&
(inputStr.startsWith('data:image/') ||
inputStr.startsWith('/api/images/') ||
inputStr.startsWith('https://') ||
inputStr.startsWith('http://'))
const inputDesc = inputStr
? isImage
? '[image provided]'
: `[text: "${inputStr.slice(0, 40)}${inputStr.length > 40 ? '...' : ''}"]`
: '[no input]'
return {
text: `[Placeholder] Prompt: "${body.prompt.slice(0, 60)}${body.prompt.length > 60 ? '...' : ''}" | Input: ${inputDesc} — Set REPLICATE_API_TOKEN for real text generation.`,
}
}