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

109 lines
2.9 KiB
TypeScript
Raw Normal View History

import { OpenAIClient } from './OpenAIClient'
import { DEFAULT_TEMPERATURE, LLM_MAX_RETRIES } from './constants'
2025-10-17 18:43:41 +08:00
import { InvokeError } from './errors'
import type { InvokeOptions, InvokeResult, LLMClient, LLMConfig, Message, Tool } from './types'
2025-10-17 18:43:41 +08:00
export type { InvokeError, 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)
if (!config.baseURL || !config.apiKey || !config.model) {
throw new Error(
'[PageAgent] LLM configuration required. Please provide: baseURL, apiKey, model. ' +
'See: https://alibaba.github.io/page-agent/#/docs/features/models'
)
}
2025-12-22 16:29:19 +08:00
return {
baseURL: config.baseURL,
apiKey: config.apiKey,
model: config.model,
2025-12-22 16:29:19 +08:00
temperature: config.temperature ?? DEFAULT_TEMPERATURE,
maxRetries: config.maxRetries ?? LLM_MAX_RETRIES,
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 () => {
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!
}