Skip to content

Commit

Permalink
feat(openai/mod.ts): refactor parser creation into a function
Browse files Browse the repository at this point in the history
The parser creation logic was duplicated in two places. This commit
refactors it into a new function `createParser`. This function takes
a validate function and returns a parser that validates and parses
the input string into a JSON object. This change makes the code more
DRY (Don't Repeat Yourself) and easier to maintain.
  • Loading branch information
ryoppippi committed Aug 8, 2024
1 parent ab0b6b0 commit b760ca8
Showing 1 changed file with 16 additions and 21 deletions.
37 changes: 16 additions & 21 deletions openai/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@ import {
makeParseableTool,
} from "openai/lib/parser";
import type typia from "typia";

type Primitive<T> = typia.Primitive<T>;
import type { Primitive } from "typia";

/**
* Params for `typiaJsonToOpenAIJsonSchema` and `typiaJsonToOpenAIResponse`
Expand Down Expand Up @@ -129,6 +128,18 @@ export function typiaJsonToOpenAIResponse<T>(
};
}

function createParser<T>(validate: ReturnType<typeof typia.createValidate<T>>) {
return (input: string): Primitive<T> => {
const json = JSON.parse(input);

const result = validate(json);
if (!result.success) {
throw new Error(`${result.errors.toString()}`);
}
return json;
};
}

/**
* Creates an AutoParseableResponseFormat for OpenAI API from Typia JSON Schema.
* @see [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs).
Expand Down Expand Up @@ -170,17 +181,9 @@ export function typiaResponseFormat<T>(

const response = typiaJsonToOpenAIResponse(params);

const parse = (s: string) => {
const json = JSON.parse(s);
const parser = createParser(params.validate);

const result = params.validate(json);
if (!result.success) {
throw new Error(`${result.errors.toString()}`);
}
return json;
};

return makeParseableResponseFormat<ParsedT>(response, parse);
return makeParseableResponseFormat<ParsedT>(response, parser);
}

/**
Expand Down Expand Up @@ -233,15 +236,7 @@ export function typiaFunction<T>(
schema,
} = typiaJsonToOpenAIJsonSchema(params);

const parser = (s: string) => {
const json = JSON.parse(s);

const result = params.validate(json);
if (!result.success) {
throw new Error(`${result.errors.toString()}`);
}
return json;
};
const parser = createParser(params.validate);

// @ts-expect-error TODO
return makeParseableTool<unknown>(
Expand Down

0 comments on commit b760ca8

Please sign in to comment.