Skip to content

Commit

Permalink
add function to verify zod schema matches type
Browse files Browse the repository at this point in the history
  • Loading branch information
Parker-Stafford committed Oct 11, 2024
1 parent 02e1d82 commit ee38d2e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 6 deletions.
2 changes: 1 addition & 1 deletion app/src/pages/playground/playgroundUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
ChatMessageRole,
createPlaygroundInstance,
generateMessageId,
} from "@phoenix/store/playgroundStore";
} from "@phoenix/store";
import { safelyParseJSON } from "@phoenix/utils/jsonUtils";

import { ChatRoleMap, DEFAULT_CHAT_ROLE } from "./constants";
Expand Down
14 changes: 9 additions & 5 deletions app/src/pages/playground/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import {
SemanticAttributePrefixes,
} from "@arizeai/openinference-semantic-conventions";

import { ChatMessageRole } from "@phoenix/store";
import { ChatMessage, ChatMessageRole } from "@phoenix/store";
import { schemaForType } from "@phoenix/typeUtils";

/**
* The zod schema for llm tool calls in an input message
Expand Down Expand Up @@ -77,12 +78,15 @@ export const outputSchema = z.object({
*/
export const chatMessageRolesSchema = z.nativeEnum(ChatMessageRole);

/**
* The zod schema for ChatMessages
*/
export const chatMessagesSchema = z.array(
const chatMessageSchema = schemaForType<ChatMessage>()(
z.object({
id: z.number(),
role: chatMessageRolesSchema,
content: z.string(),
})
);

/**
* The zod schema for ChatMessages
*/
export const chatMessagesSchema = z.array(chatMessageSchema);
24 changes: 24 additions & 0 deletions app/src/typeUtils.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { z } from "zod";

/**
* Utility function that uses the type system to check if a switch statement is exhaustive.
* If the switch statement is not exhaustive, there will be a type error caught in typescript
Expand Down Expand Up @@ -45,3 +47,25 @@ export function isObject(value: unknown): value is object {
export type Mutable<T> = {
-readonly [P in keyof T]: T[P];
};

/**
* A zod type utility that ensures that the schema is written to correctly match (at least) what is included in the type.
* Note it does not guard against extra fields in the schema not present in the type.
* @example
* ```typescript
* const chatMessageSchema = schemaForType<ChatMessage>()(
* z.object({
* id: z.number(),
* role: chatMessageRolesSchema,
* content: z.string(),
* })
* );
* ```
* Taken from the zod maintainer here:
* @see https://github.com/colinhacks/zod/issues/372#issuecomment-826380330
*/
export const schemaForType =
<T>() =>
<S extends z.ZodType<T>>(arg: S) => {
return arg;
};

0 comments on commit ee38d2e

Please sign in to comment.