openpencil/server/api/ai/models.ts
Kayshen-X f81d6bde18 feat(ai): add model selection and fetching capabilities
Enhance AI chat and generation functionalities by introducing model selection. Update the chat and generation endpoints to accept an optional model parameter. Implement a new API endpoint to fetch available AI models from the server, and integrate model selection into the AI chat panel for improved user experience.
2026-02-18 22:35:16 +08:00

48 lines
1 KiB
TypeScript

import { defineEventHandler } from 'h3'
interface ModelInfo {
value: string
displayName: string
description: string
}
let cachedModels: ModelInfo[] | null = null
/**
* Returns the list of available AI models.
* Fetches from Claude Agent SDK and caches the result.
*/
export default defineEventHandler(async () => {
if (cachedModels) {
return { models: cachedModels }
}
try {
const { query } = await import('@anthropic-ai/claude-agent-sdk')
const env = { ...process.env } as Record<string, string | undefined>
delete env.CLAUDECODE
const q = query({
prompt: '',
options: {
model: 'claude-sonnet-4-6',
maxTurns: 1,
tools: [],
permissionMode: 'plan',
persistSession: false,
env,
},
})
const models = await q.supportedModels()
cachedModels = models
q.close()
return { models }
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error'
return { models: [], error: message }
}
})