Files
page-agent/packages/llms/src/index.ts
T

93 lines
2.7 KiB
TypeScript
Raw Normal View History

import { OpenAIClient } from './OpenAIClient'
import { DEFAULT_TEMPERATURE, LLM_MAX_RETRIES } from './constants'
import { InvokeError, InvokeErrorTypes } from './errors'
import type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool } from './types'
2025-10-17 18:43:41 +08:00
export { InvokeError, InvokeErrorTypes }
export type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool }
2025-12-22 16:29:19 +08:00
export function parseLLMConfig(config: LLMConfig): Required<LLMConfig> {
// Runtime validation as defensive programming (types already guarantee these)
2026-03-19 19:50:05 +08:00
if (!config.baseURL || !config.model) {
throw new Error(
2026-03-19 19:50:05 +08:00
'[PageAgent] LLM configuration required. Please provide: baseURL, model. ' +
2026-02-27 19:46:44 +08:00
'See: https://alibaba.github.io/page-agent/docs/features/models'
)
}
2025-12-22 16:29:19 +08:00
return {
baseURL: config.baseURL,
model: config.model,
2026-03-19 19:50:05 +08:00
apiKey: config.apiKey || '',
2025-12-22 16:29:19 +08:00
temperature: config.temperature ?? DEFAULT_TEMPERATURE,
maxRetries: config.maxRetries ?? LLM_MAX_RETRIES,
transformRequestBody: config.transformRequestBody ?? ((requestBody) => requestBody),
2026-03-20 17:40:16 +08:00
disableNamedToolChoice: config.disableNamedToolChoice ?? false,
2025-12-24 19:00:43 +08:00
customFetch: (config.customFetch ?? fetch).bind(globalThis), // fetch will be illegal unless bound
2025-12-22 16:29:19 +08:00
}
}
2025-09-29 16:33:15 +08:00
export class LLM extends EventTarget {
2025-09-29 16:33:15 +08:00
config: Required<LLMConfig>
2025-10-17 18:43:41 +08:00
client: LLMClient
2025-09-29 16:33:15 +08:00
constructor(config: LLMConfig) {
super()
2025-10-10 17:46:40 +08:00
this.config = parseLLMConfig(config)
2025-09-29 16:33:15 +08:00
2025-10-17 18:43:41 +08:00
// Default to OpenAI client
2025-12-24 16:42:31 +08:00
this.client = new OpenAIClient(this.config)
2025-09-29 16:33:15 +08:00
}
/**
* - call llm api *once*
* - invoke tool call *once*
* - return the result of the tool
*/
2025-10-17 18:43:41 +08:00
async invoke(
messages: Message[],
tools: Record<string, Tool>,
abortSignal: AbortSignal,
options?: InvokeOptions
2025-10-17 18:43:41 +08:00
): Promise<InvokeResult> {
return await withRetry(async () => this.client.invoke(messages, tools, abortSignal, options), {
maxRetries: this.config.maxRetries,
onRetry: (attempt, lastError) => {
this.dispatchEvent(
new CustomEvent('retry', {
detail: { attempt, maxAttempts: this.config.maxRetries, lastError },
})
)
2025-09-29 16:33:15 +08:00
},
})
2025-09-29 16:33:15 +08:00
}
}
/**
* Retry a function until it succeeds or reaches the maximum number of retries.
*/
2025-09-29 16:33:15 +08:00
async function withRetry<T>(
fn: () => Promise<T>,
settings: {
maxRetries: number
onRetry: (attempt: number, lastError: Error) => void
2025-09-29 16:33:15 +08:00
}
): Promise<T> {
let attempt = 0
while (true) {
2025-09-29 16:33:15 +08:00
try {
return await fn()
2025-10-17 18:43:41 +08:00
} catch (error: unknown) {
if ((error as any)?.name === 'AbortError') throw error
2025-10-17 18:43:41 +08:00
if (error instanceof InvokeError && !error.retryable) throw error
attempt++
if (attempt > settings.maxRetries) throw error
console.debug('[LLM] retryable failure, will retry:', error)
settings.onRetry(attempt, error as Error)
2025-09-29 16:33:15 +08:00
await new Promise((resolve) => setTimeout(resolve, 100))
}
}
}