Skip to content

Commit fee1ca5

Browse files
authored
feat(ai): support predicate criteria in decisions (anomalyco#62819)
1 parent f29228b commit fee1ca5

9 files changed

Lines changed: 144 additions & 4 deletions

File tree

‎packages/ai/README.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,8 @@ const [refund, department] = response.answers
322322
```
323323

324324
`input` is a JSON object or an ordered list of `text`, `json` and `media` parts. Answers come back in question order.
325+
A `predicate` can say what counts as true and as false with `criteria: { true, false }`; hosts without a criteria field
326+
read them appended to the instructions.
325327
A question the host declines is `{ name, type: "error", reason, message? }`, with `reason` such as `"refusal"`; the
326328
other answers still come back.
327329
`response.usage` has `inputTokens`, `outputTokens`, `totalTokens` and the host's reported `cost` when it sends one;

‎packages/ai/src/decision.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,10 @@ export const PredicateQuestion = Schema.Struct({
5151
name: Schema.String,
5252
type: Schema.Literal("predicate"),
5353
instructions: Schema.String,
54+
/** What counts as true and as false, for statements the instructions alone leave ambiguous. */
55+
criteria: Schema.optional(
56+
Schema.Struct({ true: Schema.optional(Schema.String), false: Schema.optional(Schema.String) }),
57+
),
5458
})
5559
export type PredicateQuestion = Schema.Schema.Type<typeof PredicateQuestion>
5660

‎packages/ai/src/protocols/openai-decisions.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,20 @@ const fromRequest = Effect.fn("OpenAIDecisions.fromRequest")(function* (request:
7272
),
7373
model: request.model.id,
7474
input: [{ role: "user", content: yield* Effect.forEach(request.input, (part) => inputPart(request, part)) }],
75-
questions: request.questions,
75+
questions: request.questions.map((question) => {
76+
if (question.type !== "predicate") return question
77+
// Predicates have no criteria field, so what true and false mean is appended to the instructions.
78+
const meanings = [
79+
question.criteria?.true === undefined ? [] : [`True means: ${question.criteria.true}`],
80+
question.criteria?.false === undefined ? [] : [`False means: ${question.criteria.false}`],
81+
].flat()
82+
return {
83+
name: question.name,
84+
type: question.type,
85+
instructions:
86+
meanings.length === 0 ? question.instructions : `${question.instructions}\n\n${meanings.join("\n")}`,
87+
}
88+
}),
7689
}
7790
})
7891

‎packages/ai/src/protocols/system-one.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,14 @@ export const encodeBody = Effect.fn("SystemOne.encodeBody")(function* (request:
7070
const encodeQuestions = (questions: ReadonlyArray<DecisionQuestion>) =>
7171
Effect.forEach(questions, (question): Effect.Effect<readonly [string, unknown], AIError> => {
7272
if (question.type === "predicate")
73-
return Effect.succeed([question.name, { type: "noul", instructions: question.instructions }] as const)
73+
return Effect.succeed([
74+
question.name,
75+
{
76+
type: "noul",
77+
instructions: question.instructions,
78+
...(question.criteria === undefined ? {} : { criteria: question.criteria }),
79+
},
80+
] as const)
7481
if (question.type === "score")
7582
return Effect.succeed([
7683
question.name,

‎packages/ai/test/decision.test.ts‎

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,16 @@ const questions = [
3535
{ name: "refund", type: "predicate", instructions: "Is the customer asking for a refund?" },
3636
] as const
3737

38+
const defect = {
39+
name: "defect",
40+
type: "predicate",
41+
instructions: "Is the customer reporting a product defect?",
42+
criteria: {
43+
true: "The product itself is broken or faulty.",
44+
false: "Preference, sizing, shipping, or pricing complaint.",
45+
},
46+
} as const
47+
3848
const systemOneAnswers = {
3949
department: { type: "choice", choice: "billing", probabilities: { technical: 0.1, billing: 0.9 }, confidence: 0.8 },
4050
urgency: {
@@ -516,6 +526,76 @@ describe("Decision", () => {
516526
),
517527
)
518528

529+
it.effect("sends predicate criteria as System One criteria", () =>
530+
ai.decision
531+
.generate({
532+
model: TypeSafeAI.configure({ apiKey: "test" }).decision("jev-latest"),
533+
input: [{ type: "text", text: "I returned the sweater because I prefer green." }],
534+
questions: [defect],
535+
})
536+
.pipe(
537+
Effect.tap((response) =>
538+
Effect.sync(() =>
539+
expect(response.answers).toEqual([{ name: "defect", type: "predicate", probability: 0.03 }]),
540+
),
541+
),
542+
Effect.provide(
543+
client((input) => {
544+
expect(JSON.parse(input.text).questions).toEqual({
545+
defect: {
546+
type: "noul",
547+
instructions: "Is the customer reporting a product defect?",
548+
criteria: {
549+
true: "The product itself is broken or faulty.",
550+
false: "Preference, sizing, shipping, or pricing complaint.",
551+
},
552+
},
553+
})
554+
return Effect.succeed(
555+
json(input, { model: "jev-latest", answers: { defect: { type: "noul", noul: 0.03 } } }),
556+
)
557+
}),
558+
),
559+
),
560+
)
561+
562+
it.effect("appends predicate criteria to OpenAI Decisions instructions", () =>
563+
ai.decision
564+
.generate({
565+
model: OpenAI.configure({ apiKey: "openai-key" }).decision("gpt-6-luna"),
566+
input: [{ type: "text", text: "I returned the sweater because I prefer green." }],
567+
questions: [defect, { ...defect, name: "only_true", criteria: { true: "The product is broken." } }],
568+
})
569+
.pipe(
570+
Effect.provide(
571+
client((input) => {
572+
expect(JSON.parse(input.text).questions).toEqual([
573+
{
574+
name: "defect",
575+
type: "predicate",
576+
instructions:
577+
"Is the customer reporting a product defect?\n\nTrue means: The product itself is broken or faulty.\nFalse means: Preference, sizing, shipping, or pricing complaint.",
578+
},
579+
{
580+
name: "only_true",
581+
type: "predicate",
582+
instructions: "Is the customer reporting a product defect?\n\nTrue means: The product is broken.",
583+
},
584+
])
585+
return Effect.succeed(
586+
json(input, {
587+
model: "gpt-6-luna",
588+
answers: [
589+
{ type: "predicate", name: "defect", probability: 0.03 },
590+
{ type: "predicate", name: "only_true", probability: 0.04 },
591+
],
592+
}),
593+
)
594+
}),
595+
),
596+
),
597+
)
598+
519599
it.effect("puts media in Clef's top-level lists on Cloudflare Run", () =>
520600
ai.decision
521601
.generate({

‎packages/client/src/promise/generated/types.ts‎

Lines changed: 6 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/core/test/generate.test.ts‎

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -502,12 +502,26 @@ describe("image and decision generation", () => {
502502
{ label: "Actively blocking revenue" },
503503
],
504504
},
505-
{ type: "predicate", name: "refund", instructions: "Is the customer asking for a refund?" },
505+
{
506+
type: "predicate",
507+
name: "refund",
508+
instructions: "Is the customer asking for a refund?",
509+
criteria: { true: "They want money back.", false: "Anything else." },
510+
},
506511
],
507512
})
508513
expect(requests[0]).toMatchObject({
509514
url: "https://openrouter.ai/api/v1/systemone",
510515
headers: { authorization: "Bearer openrouter-key" },
516+
body: {
517+
questions: {
518+
refund: {
519+
type: "noul",
520+
instructions: "Is the customer asking for a refund?",
521+
criteria: { true: "They want money back.", false: "Anything else." },
522+
},
523+
},
524+
},
511525
})
512526
expect(result.answers.map((answer) => [answer.name, answer.type])).toEqual([
513527
["department", "choice"],

‎packages/protocol/openapi.json‎

Lines changed: 12 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/schema/src/generate.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,9 @@ export const PredicateQuestion = Schema.Struct({
115115
type: Schema.Literal("predicate"),
116116
name: QuestionName,
117117
instructions: Schema.String,
118+
criteria: Schema.Struct({ true: Schema.String.pipe(optional), false: Schema.String.pipe(optional) })
119+
.pipe(optional)
120+
.annotate(description("What counts as true and as false, for statements the instructions alone leave ambiguous")),
118121
}).annotate({ identifier: "Generate.PredicateQuestion", description: "The probability that a statement is true" })
119122

120123
export interface ChoiceQuestion extends Schema.Schema.Type<typeof ChoiceQuestion> {}

0 commit comments

Comments
 (0)