Validation & Errors

Automatic parameter validation and error handling strategies for tools.

Parameter Validation

The tool() function automatically uses the Zod Schema to validate model-generated parameters. If parameters don't conform to the schema, the validation error is caught and returned to the model as a failure result, rather than throwing an exception that interrupts the flow:

const searchTool = tool({
  name: 'search',
  description: 'Search records',
  schema: z.object({
    query: z.string().min(1).describe('Search keywords'),
    limit: z.number().int().min(1).max(100).describe('Number of results'),
  }),
  execute: async (input) => {
    return searchDatabase(input.query, input.limit)
  },
})

If the model generates limit: -1, Zod validation will fail, and the model will receive an error message like "Invalid arguments: limit: Number must be greater than or equal to 1", giving it the opportunity to correct the parameters and retry.

Error Handling

Errors during tool execution are automatically caught and returned to the model. You can handle errors yourself in the execute function, or let deepseek-kit's default mechanism take over:

const safeTool = tool({
  name: 'safeApi',
  description: 'Safe API call',
  schema: z.object({ url: z.string() }),
  execute: async (input) => {
    try {
      const response = await fetch(input.url)
      if (!response.ok) {
        return { error: `Request failed: ${response.status}` }
      }
      return await response.json()
    }
    catch (error) {
      return { error: `Network error: ${error instanceof Error ? error.message : String(error)}` }
    }
  },
})