Skip to content

Commit

Permalink
replace tool response and error parser with zod schema
Browse files Browse the repository at this point in the history
  • Loading branch information
yinishi committed Aug 28, 2024
1 parent 6510d05 commit 76cdffd
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions packages/react/src/lib/useVoiceClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { type Hume, HumeClient } from 'hume';
import * as serializers from 'hume/serialization';
import { useCallback, useRef, useState } from 'react';
import z from 'zod';

import { type AuthStrategy } from './auth';

Expand Down Expand Up @@ -148,17 +148,39 @@ export const useVoiceClient = (props: {
})
.then((response) => {
// check that response is a correctly formatted response or error payload
const parsedResponse =
serializers.empathicVoice.ToolResponseMessage.parse(response);
const parsedError =
serializers.empathicVoice.ToolErrorMessage.parse(response);
const parsedResponse = z
.object({
type: z.literal('tool_response'),
customSessionId: z.string().optional(),
toolCallId: z.string(),
content: z.string(),
toolName: z.string().optional(),
toolType: z.enum(['builtin', 'function']).optional(),
})
.safeParse(response);

const parsedError = z
.object({
type: z.literal('tool_error'),
customSessionId: z.string().optional(),
toolType: z.enum(['builtin', 'function']).optional(),
toolCallId: z.string(),
content: z.string().optional(),
error: z.string(),
code: z.string().optional(),
level: z.enum(['warn']).optional(),
})
.safeParse(response);

// if valid send it to the socket
// otherwise, report error
if (response.type === 'tool_response' && parsedResponse.ok) {
client.current?.sendToolResponseMessage(response);
} else if (response.type === 'tool_error' && parsedError.ok) {
client.current?.sendToolErrorMessage(response);
if (response.type === 'tool_response' && parsedResponse.success) {
client.current?.sendToolResponseMessage(parsedResponse.data);
} else if (
response.type === 'tool_error' &&
parsedError.success
) {
client.current?.sendToolErrorMessage(parsedError.data);
} else {
onError.current?.('Invalid response from tool call');
}
Expand Down

0 comments on commit 76cdffd

Please sign in to comment.