Skip to content

Commit

Permalink
feat(tool): add optional input preprocessor
Browse files Browse the repository at this point in the history
Signed-off-by: Tomas Dvorak <[email protected]>
  • Loading branch information
Tomas2D committed Nov 4, 2024
1 parent b434e32 commit d218f8b
Show file tree
Hide file tree
Showing 3 changed files with 20 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
4 changes: 4 additions & 0 deletions src/tools/base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,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 +341,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 d218f8b

Please sign in to comment.