chatgpt-api/src/ai-function-set.ts

93 wiersze
2.2 KiB
TypeScript
Czysty Zwykły widok Historia

2024-05-24 23:55:26 +00:00
import type * as types from './types.ts'
import { AIFunctionsProvider } from './fns.js'
2024-05-24 23:55:26 +00:00
2024-06-03 00:12:22 +00:00
/**
* A set of AI functions intended to make it easier to work with large sets of
* AI functions across different clients.
*
* This class mimics a built-in `Set<AIFunction>`, but with additional utility
* methods like `pick`, `omit`, and `map`.
*/
2024-05-24 23:55:26 +00:00
export class AIFunctionSet implements Iterable<types.AIFunction> {
protected readonly _map: Map<string, types.AIFunction>
constructor(aiFunctionLikeObjects?: types.AIFunctionLike[]) {
const fns = aiFunctionLikeObjects?.flatMap((fn) =>
fn instanceof AIFunctionsProvider
? [...fn.functions]
: fn instanceof AIFunctionSet
? [...fn]
: [fn]
2024-06-02 00:34:25 +00:00
)
this._map = new Map(fns ? fns.map((fn) => [fn.spec.name, fn]) : null)
2024-05-24 23:55:26 +00:00
}
get size(): number {
return this._map.size
}
add(fn: types.AIFunction): this {
2024-06-02 02:04:13 +00:00
this._map.set(fn.spec.name, fn)
2024-05-24 23:55:26 +00:00
return this
}
get(name: string): types.AIFunction | undefined {
return this._map.get(name)
}
set(name: string, fn: types.AIFunction): this {
this._map.set(name, fn)
return this
}
has(name: string): boolean {
return this._map.has(name)
}
clear(): void {
this._map.clear()
}
delete(name: string): boolean {
return this._map.delete(name)
}
pick(...keys: string[]): AIFunctionSet {
const keysToIncludeSet = new Set(keys)
return new AIFunctionSet(
Array.from(this).filter((fn) => keysToIncludeSet.has(fn.spec.name))
)
}
omit(...keys: string[]): AIFunctionSet {
const keysToExcludeSet = new Set(keys)
return new AIFunctionSet(
Array.from(this).filter((fn) => !keysToExcludeSet.has(fn.spec.name))
)
}
2024-06-02 02:04:13 +00:00
map<T>(fn: (fn: types.AIFunction) => T): T[] {
return [...this.entries].map(fn)
}
2024-06-02 22:30:39 +00:00
get specs(): types.AIFunctionSpec[] {
return this.map((fn) => fn.spec)
}
get toolSpecs(): types.AIToolSpec[] {
return this.map((fn) => ({
type: 'function' as const,
function: fn.spec
}))
}
2024-05-24 23:55:26 +00:00
get entries(): IterableIterator<types.AIFunction> {
return this._map.values()
}
[Symbol.iterator](): Iterator<types.AIFunction> {
return this.entries
}
}