Skip to content

Commit

Permalink
feat(tool): add optional input preprocessor (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
Tomas2D authored Nov 4, 2024
1 parent b434e32 commit cec2cb9
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/internals/helpers/object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ export function getPropStrict(target: NonNullable<unknown>, path: string): any {

export function getProp(
target: unknown,
paths: readonly (string | symbol)[],
paths: readonly (keyof any)[],
defaultValue: any = undefined,
) {
let value: any = target;
Expand Down
6 changes: 6 additions & 0 deletions src/tools/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,8 @@ export abstract class Tool<
}

run(input: ToolInputRaw<this>, options?: TRunOptions): Promise<TOutput> {
input = shallowCopy(input);

return RunContext.enter(
this,
{ signal: options?.signal, params: [input, options] as const },
Expand All @@ -211,6 +213,7 @@ export abstract class Tool<
let errorPropagated = false;

try {
this.preprocessInput(input);
await this.assertInput(input);

const output = await new Retryable({
Expand Down Expand Up @@ -340,6 +343,9 @@ export abstract class Tool<
this.validateInput(schema, input);
}

// eslint-disable-next-line unused-imports/no-unused-vars
protected preprocessInput(rawInput: unknown): void {}

protected validateInput(
schema: AnyToolSchemaLike,
rawInput: unknown,
Expand Down
15 changes: 15 additions & 0 deletions src/tools/weather/openMeteo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { createURLParams } from "@/internals/fetcher.js";
import { isNullish, pick, pickBy } from "remeda";
import { Cache } from "@/cache/decoratorCache.js";
import { RunContext } from "@/context.js";
import { getProp, setProp } from "@/internals/helpers/object.js";

type ToolOptions = { apiKey?: string } & BaseToolOptions;
type ToolRunOptions = BaseToolRunOptions;
Expand Down Expand Up @@ -102,6 +103,20 @@ export class OpenMeteoTool extends Tool<
this.register();
}

protected preprocessInput(rawInput: unknown) {
super.preprocessInput(rawInput);

const fixDate = (key: keyof ToolInput<this>) => {
const value = getProp(rawInput, [key]);
if (value) {
setProp(rawInput, [key], value.substring(0, 10));
}
};

fixDate("start_date");
fixDate("end_date");
}

protected async _run(
{ location, start_date: startDate, end_date: endDate, ...input }: ToolInput<this>,
_options: BaseToolRunOptions | undefined,
Expand Down

0 comments on commit cec2cb9

Please sign in to comment.