|
| 1 | +import {readFile} from 'node:fs/promises' |
| 2 | + |
| 3 | +import {type LanguageModelV2} from '@ai-sdk/provider' |
| 4 | +// eslint-disable-next-line import/no-unresolved |
| 5 | +import {parseYAML} from 'confbox/yaml' |
| 6 | +import templite from 'templite' |
| 7 | +import {z} from 'zod/v4' |
| 8 | + |
| 9 | +import {createGitHubModels, type GitHubModelsProviderSettings} from './provider' |
| 10 | + |
| 11 | +const message = z.discriminatedUnion('role', [ |
| 12 | + z.object({role: z.literal('user'), content: z.string()}), |
| 13 | + z.object({role: z.literal('system'), content: z.string()}), |
| 14 | +]) |
| 15 | + |
| 16 | +type Message = z.infer<typeof message> |
| 17 | + |
| 18 | +const schema = z.object({ |
| 19 | + name: z.string().optional(), |
| 20 | + description: z.string().optional(), |
| 21 | + model: z.string(), |
| 22 | + modelParameters: z |
| 23 | + .object({ |
| 24 | + maxTokens: z.number().positive().optional(), |
| 25 | + temperature: z.number().min(0).max(1).optional(), |
| 26 | + topP: z.number().min(0).max(1).optional(), |
| 27 | + }) |
| 28 | + .optional(), |
| 29 | + messages: z.array(message), |
| 30 | + responseFormat: z.enum(['text']).optional(), |
| 31 | +}) |
| 32 | + |
| 33 | +type PromptConfig = z.infer<typeof schema> |
| 34 | +type Variables = Record<string, string | number | boolean> |
| 35 | + |
| 36 | +export async function getPrompt(filename: string | URL, variables: Variables = {}): Promise<PromptConfig> { |
| 37 | + const file = await readFile(filename, 'utf8') |
| 38 | + const yml = parseYAML(file, { |
| 39 | + filename: filename.toString(), |
| 40 | + }) |
| 41 | + const p = schema.parse(yml) |
| 42 | + for (const msg of p.messages) msg.content = templite(msg.content, variables) |
| 43 | + return p |
| 44 | +} |
| 45 | + |
| 46 | +export async function prompt( |
| 47 | + filename: string | URL, |
| 48 | + variables: Variables = {}, |
| 49 | + options: GitHubModelsProviderSettings = {}, |
| 50 | +): Promise<{ |
| 51 | + model: LanguageModelV2 |
| 52 | + messages: Message[] |
| 53 | + temperature?: number |
| 54 | + maxOutputTokens?: number |
| 55 | + topP?: number |
| 56 | +}> { |
| 57 | + const p = await getPrompt(filename, variables) |
| 58 | + const provider = createGitHubModels(options) |
| 59 | + |
| 60 | + return { |
| 61 | + model: provider(p.model), |
| 62 | + messages: p.messages, |
| 63 | + temperature: p.modelParameters?.temperature, |
| 64 | + maxOutputTokens: p.modelParameters?.maxTokens, |
| 65 | + topP: p.modelParameters?.topP, |
| 66 | + } |
| 67 | +} |
0 commit comments