Running Prompts
Execute prompts with the CobblAdminClient
The runPrompt method allows you to execute prompts stored in your Cobbl dashboard.
This method is only available on CobblAdminClient. It requires API key authentication and should only be used server-side.
Basic Usage
import { CobblAdminClient } from '@cobbl-ai/sdk'
const adminClient = new CobblAdminClient({
apiKey: process.env.COBBL_API_KEY,
})
const result = await adminClient.runPrompt('sales_summary', {
topic: 'Q4 Results',
tone: 'friendly',
audience: 'investors',
})
console.log(result.output) // AI-generated response
console.log(result.runId) // Unique run ID for feedbackMethod Signature
runPrompt(promptSlug: string, input: PromptInput): Promise<RunPromptResponse>Parameters
| Parameter | Type | Description |
|---|---|---|
promptSlug | string | The unique slug identifier for the prompt |
input | PromptInput | Object containing variables to fill the prompt |
PromptInput
The input object contains key-value pairs that map to variables defined in your prompt template:
// If your prompt template is:
// "Summarize {{topic}} in a {{tone}} tone for {{audience}}."
const input = {
topic: 'Q4 Results',
tone: 'friendly',
audience: 'investors',
}Response
The runPrompt method returns a RunPromptResponse object:
interface RunPromptResponse {
runId: string
output: string
tokenUsage: {
inputTokens: number
outputTokens: number
totalTokens: number
}
renderedPrompt: string
promptVersion: {
id: string
versionNumber: number
template: string
variables: Array<{
key: string
type: string
required: boolean
}>
provider: 'openai' | 'anthropic' | 'google'
model: string
}
}Response Fields
| Field | Type | Description |
|---|---|---|
runId | string | Unique ID for this run - save this for feedback |
output | string | The AI-generated response |
tokenUsage | TokenUsage | Token usage statistics |
renderedPrompt | string | The final prompt sent to the LLM |
promptVersion | PromptVersionClient | Metadata about the prompt version used |
Examples
Basic Example
const result = await adminClient.runPrompt('greeting', {
name: 'Alice',
})
console.log(result.output)
// => "Hello Alice! How can I help you today?"Storing the Run ID for Feedback
Always save the runId to link feedback later. See CobblPublicClient for how to collect feedback.
const result = await adminClient.runPrompt('recommendation', {
userId: '123',
category: 'electronics',
})
// Store in your database
await db.recommendations.create({
userId: '123',
content: result.output,
promptRunId: result.runId, // ← Save this!
})Accessing Token Usage
const result = await adminClient.runPrompt('article_summary', {
article: longArticleText,
})
console.log(`Input tokens: ${result.tokenUsage.inputTokens}`)
console.log(`Output tokens: ${result.tokenUsage.outputTokens}`)
console.log(`Total tokens: ${result.tokenUsage.totalTokens}`)Getting Prompt Metadata
const result = await adminClient.runPrompt('customer_email', {
customerName: 'John',
issue: 'billing',
})
console.log(`Prompt version: ${result.promptVersion.versionNumber}`)
console.log(`Model used: ${result.promptVersion.model}`)
console.log(`Provider: ${result.promptVersion.provider}`)Framework Examples
Express.js
import express from 'express'
import { CobblAdminClient } from '@cobbl-ai/sdk'
const app = express()
const adminClient = new CobblAdminClient({
apiKey: process.env.COBBL_API_KEY,
})
app.post('/api/generate', async (req, res) => {
try {
const result = await adminClient.runPrompt('content_generator', req.body)
res.json({
output: result.output,
runId: result.runId,
})
} catch (error) {
res.status(500).json({ error: 'Failed to generate content' })
}
})Next.js API Route
import { CobblAdminClient } from '@cobbl-ai/sdk'
import { NextResponse } from 'next/server'
const adminClient = new CobblAdminClient({
apiKey: process.env.COBBL_API_KEY!,
})
export const POST = async (request: Request) => {
const body = await request.json()
try {
const result = await adminClient.runPrompt('summarizer', {
text: body.text,
length: 'short',
})
return NextResponse.json(result)
} catch (error) {
return NextResponse.json(
{ error: 'Failed to generate summary' },
{ status: 500 }
)
}
}Next.js Server Action
'use server'
import { CobblAdminClient } from '@cobbl-ai/sdk'
const adminClient = new CobblAdminClient({
apiKey: process.env.COBBL_API_KEY!,
})
export const generateContent = async (topic: string) => {
const result = await adminClient.runPrompt('blog_post', {
topic,
style: 'informative',
})
return {
content: result.output,
runId: result.runId,
}
}Best Practices
1. Run Prompts Server-Side
Always execute prompts on the server, never in client-side code. This keeps your API key secure and ensures consistent, auditable prompt execution.
2. Always Store Run IDs with Responses
The runId is essential for Cobbl's feedback loop. When you store it alongside the AI response in your database, you enable:
- Feedback collection: Users can rate or comment on specific AI outputs
- Prompt improvement: Feedback links directly to the prompt version that generated it
- Analytics: Track performance across different prompt versions
const result = await adminClient.runPrompt('recommendation', { userId: '123' })
// Always store both the output AND the runId
await db.recommendations.create({
userId: '123',
content: result.output,
promptRunId: result.runId, // ← Essential for feedback
promptVersion: result.promptVersion.versionNumber, // Optional: useful for debugging
})When displaying the AI response to users, pass the runId to your frontend so the CobblPublicClient or Feedback Widget can submit feedback for that specific run.
3. Handle Errors Gracefully
Wrap calls in try-catch and provide fallback behavior. See Error Handling for comprehensive patterns.
try {
const result = await adminClient.runPrompt('greeting', { name: userName })
return result.output
} catch (error) {
console.error('Prompt failed:', error)
return `Hello, ${userName}!` // Fallback
}4. Use Environment-Specific Keys
Use different API keys for development, staging, and production:
const adminClient = new CobblAdminClient({
apiKey: process.env.COBBL_API_KEY,
})