mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 11:07:16 +00:00
refactor(core): split generated providers into per-provider files
This commit is contained in:
@@ -57,82 +57,135 @@ export function sortProviders(entries: [string, unknown][]): [string, unknown][]
|
||||
})
|
||||
}
|
||||
|
||||
async function sync() {
|
||||
console.log('Fetching pi models from GitHub...')
|
||||
const res = await fetch(
|
||||
'https://raw.githubusercontent.com/earendil-works/pi/refs/heads/main/packages/ai/src/models.generated.ts',
|
||||
function toIdentifier(name: string): string {
|
||||
const camel = name.replace(/-([a-z0-9])/g, (_, g) => g.toUpperCase())
|
||||
return camel.replace(/[^a-zA-Z0-9_$]/g, '_')
|
||||
}
|
||||
|
||||
async function loadModelData(): Promise<Record<string, unknown>> {
|
||||
// Check local pi-mono data directory first
|
||||
const piMonoDataDir = path.resolve(
|
||||
process.cwd(),
|
||||
'..',
|
||||
'pi-mono',
|
||||
'packages',
|
||||
'ai',
|
||||
'src',
|
||||
'providers',
|
||||
'data',
|
||||
)
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch pi models: ${res.statusText}`)
|
||||
if (fs.existsSync(piMonoDataDir)) {
|
||||
console.log(`Loading model data from local pi-mono workspace: ${piMonoDataDir}`)
|
||||
const files = fs
|
||||
.readdirSync(piMonoDataDir)
|
||||
.filter((f) => f.endsWith('.json') && !f.startsWith('.'))
|
||||
const rawProviders: Record<string, unknown> = {}
|
||||
for (const file of files) {
|
||||
const providerName = path.basename(file, '.json')
|
||||
const filePath = path.join(piMonoDataDir, file)
|
||||
const content = JSON.parse(fs.readFileSync(filePath, 'utf8'))
|
||||
rawProviders[providerName] = content
|
||||
}
|
||||
return rawProviders
|
||||
}
|
||||
let text = await res.text()
|
||||
|
||||
console.log('Parsing models...')
|
||||
// Remove imports
|
||||
text = text.replace(/import\s+.*?from\s+['"].*?['"];?/g, '')
|
||||
throw new Error(
|
||||
`Model data directory not found at ${piMonoDataDir}. Please run 'npm run generate-models' in pi-mono.`,
|
||||
)
|
||||
}
|
||||
|
||||
// Remove 'satisfies Model<...>'
|
||||
text = text.replace(/satisfies\s+Model<[^>]+>/g, '')
|
||||
async function sync() {
|
||||
console.log('Loading pi model data...')
|
||||
const rawModels = await loadModelData()
|
||||
|
||||
// Write to a temporary file to import it
|
||||
const tmpPath = path.join(process.cwd(), 'scripts', 'tmp-models.ts')
|
||||
fs.writeFileSync(tmpPath, text)
|
||||
|
||||
try {
|
||||
const { MODELS } = await import(tmpPath)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const providers: Record<string, any> = {}
|
||||
const sortedEntries = sortProviders(Object.entries(rawModels))
|
||||
|
||||
for (const [providerName, models] of sortedEntries) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const providers: Record<string, any> = {}
|
||||
const modelList = Object.values(models as Record<string, any>)
|
||||
if (modelList.length === 0) continue
|
||||
|
||||
const sortedEntries = sortProviders(Object.entries(MODELS))
|
||||
|
||||
for (const [providerName, models] of sortedEntries) {
|
||||
const firstModel = modelList[0]
|
||||
providers[providerName] = {
|
||||
name: providerName,
|
||||
config: {
|
||||
api: firstModel.api,
|
||||
baseUrl: firstModel.baseUrl,
|
||||
apiKey: envMap[providerName] || '',
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const modelList = Object.values(models as Record<string, any>)
|
||||
if (modelList.length === 0) continue
|
||||
|
||||
const firstModel = modelList[0]
|
||||
providers[providerName] = {
|
||||
name: providerName,
|
||||
models: modelList.map((m: any) => ({
|
||||
modelId: m.id,
|
||||
name: m.name,
|
||||
config: {
|
||||
api: firstModel.api,
|
||||
baseUrl: firstModel.baseUrl,
|
||||
apiKey: envMap[providerName] || '',
|
||||
api: m.api,
|
||||
reasoning: m.reasoning,
|
||||
input: m.input,
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: m.cost,
|
||||
},
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
models: modelList.map((m: any) => ({
|
||||
modelId: m.id,
|
||||
name: m.name,
|
||||
config: {
|
||||
api: m.api,
|
||||
reasoning: m.reasoning,
|
||||
input: m.input,
|
||||
contextWindow: m.contextWindow,
|
||||
maxTokens: m.maxTokens,
|
||||
cost: m.cost,
|
||||
},
|
||||
})),
|
||||
}
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
const generatedDir = path.join(process.cwd(), 'packages', 'core', 'src', 'generated')
|
||||
if (!fs.existsSync(generatedDir)) {
|
||||
fs.mkdirSync(generatedDir, { recursive: true })
|
||||
const generatedDir = path.join(process.cwd(), 'packages', 'core', 'src', 'generated')
|
||||
const providersSubdir = path.join(generatedDir, 'providers')
|
||||
|
||||
if (!fs.existsSync(providersSubdir)) {
|
||||
fs.mkdirSync(providersSubdir, { recursive: true })
|
||||
}
|
||||
|
||||
// Clean existing files in providers directory
|
||||
const existingSubFiles = fs.readdirSync(providersSubdir)
|
||||
for (const file of existingSubFiles) {
|
||||
if (file.endsWith('.ts')) {
|
||||
fs.unlinkSync(path.join(providersSubdir, file))
|
||||
}
|
||||
}
|
||||
|
||||
const outPath = path.join(generatedDir, 'providers.generated.ts')
|
||||
const outContent = `// This file is auto-generated by scripts/generate-builtin-providers.ts
|
||||
// Write individual provider files
|
||||
const importStatements: string[] = []
|
||||
const providerEntries: string[] = []
|
||||
|
||||
for (const [providerName, providerData] of Object.entries(providers)) {
|
||||
const filePath = path.join(providersSubdir, `${providerName}.ts`)
|
||||
const fileContent = `// This file is auto-generated by scripts/generate-builtin-providers.ts
|
||||
// Do not edit manually - run 'bun run generate-providers' to update
|
||||
|
||||
export const builtinProviders: Record<string, any> = ${JSON.stringify(providers, null, 2)} as unknown as Record<string, any>
|
||||
export const providerName = ${JSON.stringify(providerName)}
|
||||
export const providerConfig = ${JSON.stringify(providerData, null, 2)} as const
|
||||
`
|
||||
fs.writeFileSync(outPath, outContent)
|
||||
console.log(`Successfully generated builtin providers: ${outPath}`)
|
||||
} finally {
|
||||
if (fs.existsSync(tmpPath)) {
|
||||
fs.unlinkSync(tmpPath)
|
||||
fs.writeFileSync(filePath, fileContent)
|
||||
|
||||
const identifier = toIdentifier(providerName)
|
||||
importStatements.push(
|
||||
`import { providerConfig as ${identifier} } from './providers/${providerName}'`,
|
||||
)
|
||||
if (identifier === providerName) {
|
||||
providerEntries.push(` ${identifier},`)
|
||||
} else {
|
||||
providerEntries.push(` ${JSON.stringify(providerName)}: ${identifier},`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Generated ${Object.keys(providers).length} provider files in ${providersSubdir}`)
|
||||
|
||||
// Write main aggregator providers.generated.ts
|
||||
const outPath = path.join(generatedDir, 'providers.generated.ts')
|
||||
const outContent = `// This file is auto-generated by scripts/generate-builtin-providers.ts
|
||||
// Do not edit manually - run 'bun run generate-providers' to update
|
||||
|
||||
${importStatements.join('\n')}
|
||||
|
||||
export const builtinProviders: Record<string, any> = {
|
||||
${providerEntries.join('\n')}
|
||||
} as unknown as Record<string, any>
|
||||
`
|
||||
fs.writeFileSync(outPath, outContent)
|
||||
console.log(`Successfully generated aggregator: ${outPath}`)
|
||||
}
|
||||
|
||||
sync().catch((err) => {
|
||||
|
||||
Reference in New Issue
Block a user