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

114 lines
3.1 KiB
TypeScript
Raw Normal View History

import { OpenAIClient } from './OpenAIClient'
import { DEFAULT_TEMPERATURE, LLM_MAX_RETRIES } from './constants'
import { InvokeError, InvokeErrorType } from './errors'
import type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool } from './types'
2025-10-17 18:43:41 +08:00
export { InvokeError, InvokeErrorType }
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,
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> {
2025-09-29 16:33:15 +08:00
return await withRetry(
async () => {
// in case user aborted before invoking
if (abortSignal.aborted) throw new Error('AbortError')
const result = await this.client.invoke(messages, tools, abortSignal, options)
2025-09-29 16:33:15 +08:00
2025-10-17 18:43:41 +08:00
return result
2025-09-29 16:33:15 +08:00
},
// retry settings
{
maxRetries: this.config.maxRetries,
onRetry: (attempt: number) => {
this.dispatchEvent(
new CustomEvent('retry', { detail: { attempt, maxAttempts: this.config.maxRetries } })
)
2025-09-29 16:33:15 +08:00
},
2025-12-08 17:20:03 +08:00
onError: (error: Error) => {
this.dispatchEvent(new CustomEvent('error', { detail: { error } }))
2025-09-29 16:33:15 +08:00
},
}
)
}
}
async function withRetry<T>(
fn: () => Promise<T>,
settings: {
maxRetries: number
onRetry: (attempt: number) => void
2025-12-08 17:20:03 +08:00
onError: (error: Error) => void
2025-09-29 16:33:15 +08:00
}
): Promise<T> {
let attempt = 0
2025-09-29 16:33:15 +08:00
let lastError: Error | null = null
while (attempt <= settings.maxRetries) {
if (attempt > 0) {
settings.onRetry(attempt)
2025-09-29 16:33:15 +08:00
await new Promise((resolve) => setTimeout(resolve, 100))
}
try {
return await fn()
2025-10-17 18:43:41 +08:00
} catch (error: unknown) {
// do not retry if aborted by user
if ((error as any)?.rawError?.name === 'AbortError') throw error
2025-09-29 16:33:15 +08:00
console.error(error)
2025-12-08 17:20:03 +08:00
settings.onError(error as Error)
2025-09-29 16:33:15 +08:00
2025-10-17 18:43:41 +08:00
// do not retry if error is not retryable (InvokeError)
if (error instanceof InvokeError && !error.retryable) throw error
2025-09-29 16:33:15 +08:00
lastError = error as Error
attempt++
2025-09-29 16:33:15 +08:00
await new Promise((resolve) => setTimeout(resolve, 100))
}
}
throw lastError!
}