({
assertion,
renderedValue,
test,
prompt,
output,
inverse,
}: AssertionParams)
| 5 | import type { AssertionParams, GradingResult } from '../types/index'; |
| 6 | |
| 7 | export async function handleWebhook({ |
| 8 | assertion, |
| 9 | renderedValue, |
| 10 | test, |
| 11 | prompt, |
| 12 | output, |
| 13 | inverse, |
| 14 | }: AssertionParams): Promise<GradingResult> { |
| 15 | invariant(renderedValue, '"webhook" assertion type must have a URL value'); |
| 16 | invariant(typeof renderedValue === 'string', '"webhook" assertion type must have a URL value'); |
| 17 | try { |
| 18 | const context = { |
| 19 | prompt, |
| 20 | vars: test.vars || {}, |
| 21 | }; |
| 22 | const response = await fetchWithRetries( |
| 23 | renderedValue, |
| 24 | { |
| 25 | method: 'POST', |
| 26 | headers: { |
| 27 | 'Content-Type': 'application/json', |
| 28 | }, |
| 29 | body: JSON.stringify({ output, context }), |
| 30 | }, |
| 31 | getEnvInt('WEBHOOK_TIMEOUT', 5000), |
| 32 | ); |
| 33 | |
| 34 | if (!response.ok) { |
| 35 | throw new Error(`Webhook response status: ${response.status}`); |
| 36 | } |
| 37 | |
| 38 | const jsonResponse = await response.json(); |
| 39 | const pass = jsonResponse.pass !== inverse; |
| 40 | const score = |
| 41 | typeof jsonResponse.score === 'undefined' |
| 42 | ? pass |
| 43 | ? 1 |
| 44 | : 0 |
| 45 | : inverse |
| 46 | ? 1 - jsonResponse.score |
| 47 | : jsonResponse.score; |
| 48 | |
| 49 | const reason = |
| 50 | jsonResponse.reason || |
| 51 | (pass ? 'Assertion passed' : `Webhook returned ${inverse ? 'true' : 'false'}`); |
| 52 | |
| 53 | return { |
| 54 | pass, |
| 55 | score, |
| 56 | reason, |
| 57 | assertion, |
| 58 | }; |
| 59 | } catch (err) { |
| 60 | return { |
| 61 | pass: false, |
| 62 | score: 0, |
| 63 | reason: `Webhook error: ${(err as Error).message}`, |
| 64 | assertion, |
nothing calls this directly
no test coverage detected
searching dependent graphs…