binding.ts
This file
Path
packages/drafting/src/drafter/binding.ts
181 lines · 5.3 KiB · TypeScript
Last changed by
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
History of this fileTake it
Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 1–3why, one step back1// Workers AI can't promise the model keeps to the schema, so the reply is2// decoded whatever the model claims. Nothing here logs: a prompt carries the3// project's files.Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 4–6why, one step back4import { Effect, Hash, Layer, Predicate, Schema } from "effect";5import type { JsonSchema } from "effect";6Take one sentence where a draft's list is asked for, so kimi's drafts decodeoscabrielbefore adoptionecc2107
line 7why, one step back7import { DraftedAsk, DraftedReply, DraftFailed } from "../drafted.ts";Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 8–12why, one step back8import type { DraftInput } from "../drafted.ts";9import { Drafter } from "../drafter.ts";10import { systemPrompt, userPrompt } from "../prompt.ts";1112/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 13–14why, one step back13 * `run` with a model named by a var, so the generated type's fallback14 * overload. A type test holds the generated `Ai` to it, so tests pass a fake.Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 15–24why, one step back15 */16export interface AiLike {17 readonly run: (model: string, inputs: ChatInputs) => Promise<object>;18}1920export interface ChatMessage {21 readonly content: string;22 readonly role: "system" | "user";23}24Merge build/1007oscabrielbefore adoption77fa97a
lines 25–28why, one step back25export interface ReasoningInputs {26 readonly reasoning_effort: "low";27}28Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
line 29why, one step back29/** A type alias, not an interface, so it fits the binding's open `Record` of inputs. */Merge build/1007oscabrielbefore adoption77fa97a
line 30why, one step back30export type ChatInputs = Partial<ReasoningInputs> & {Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 31–40why, one step back31 readonly max_completion_tokens: number;32 readonly messages: readonly ChatMessage[];33 readonly response_format: {34 readonly json_schema: JsonSchema.JsonSchema;35 readonly type: "json_schema";36 };37 readonly seed: number;38 readonly temperature: number;39};40Merge build/1007oscabrielbefore adoption77fa97a
lines 41–48why, one step back41export interface ModelSettings {42 readonly max_completion_tokens: number;43 readonly reasoning?: ReasoningInputs;44}4546const DEFAULT_SETTINGS: ModelSettings = { max_completion_tokens: 12_000 };4748/**Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503
lines 49–50why, one step back49 * The fallback models spent 12,000 tokens reasoning on the drafting prompt50 * before the JSON was done, so each gets more room and a low effort.Merge build/1007oscabrielbefore adoption77fa97a
lines 51–65why, one step back51 */52const FALLBACK_SETTINGS: ModelSettings = {53 max_completion_tokens: 32_000,54 reasoning: { reasoning_effort: "low" },55};5657const MODEL_SETTINGS: ReadonlyMap<string, ModelSettings> = new Map([58 ["@cf/moonshotai/kimi-k2.7-code", DEFAULT_SETTINGS],59 ["@cf/zai-org/glm-5.3", FALLBACK_SETTINGS],60 ["@cf/openai/gpt-oss-120b", FALLBACK_SETTINGS],61]);6263export const modelSettings = (model: string): ModelSettings =>64 MODEL_SETTINGS.get(model) ?? DEFAULT_SETTINGS;65Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 66–91why, one step back66const responseSchema = (() => {67 const { definitions, schema } = Schema.toJsonSchemaDocument(DraftedAsk);6869 return Object.keys(definitions).length === 070 ? schema71 : { ...schema, $defs: definitions };72})();7374const Reply = Schema.Union([75 Schema.Struct({76 choices: Schema.NonEmptyArray(77 Schema.Struct({ message: Schema.Struct({ content: Schema.String }) })78 ),79 }),80 Schema.Struct({81 response: Schema.Union([82 Schema.String,83 Schema.Record(Schema.String, Schema.Unknown),84 ]),85 }),86]);8788const decodeReply = Schema.decodeUnknownEffect(Reply);8990const decodeJson = Schema.decodeEffect(Schema.fromJsonString(Schema.Unknown));91Take one sentence where a draft's list is asked for, so kimi's drafts decodeoscabrielbefore adoptionecc2107
line 92why, one step back92const decodeDrafted = Schema.decodeUnknownEffect(DraftedReply);Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 93–134why, one step back9394const unfenced = (text: string) =>95 /^\s*```[\w-]*[^\S\n]*\n(?<body>[\s\S]*?)\n?```\s*$/u.exec(text)?.groups96 ?.body ?? text;9798const failed = (reason: DraftFailed["reason"]) => new DraftFailed({ reason });99100const draftedOf = (101 reply: typeof Reply.Type102): Effect.Effect<DraftedAsk, DraftFailed> => {103 const content =104 "choices" in reply ? reply.choices[0].message.content : reply.response;105106 return Effect.flatMap(107 Predicate.isString(content)108 ? Effect.mapError(decodeJson(unfenced(content)), () =>109 failed("unparseable")110 )111 : Effect.succeed(content),112 (parsed) => Effect.mapError(decodeDrafted(parsed), () => failed("schema"))113 );114};115116const reasonOf = (thrown: string): DraftFailed["reason"] => {117 if (/\b(?:429|3040)\b|rate.?limit/iu.test(thrown)) {118 return "rate-limited";119 }120121 return /JSON Mode couldn't be met/iu.test(thrown) ? "schema" : "model-error";122};123124/** The same attempt asks with the same seed. */125const seedOf = (input: DraftInput) =>126 Math.abs(127 Hash.string(128 `${input.context.project}:${input.context.at}:${input.attempt}:${input.want}`129 )130 );131132export const DrafterWorkersAi = (133 ai: AiLike,134 model: stringMerge build/1007oscabrielbefore adoption77fa97a
lines 135–138why, one step back135): Layer.Layer<Drafter> => {136 const settings = modelSettings(model);137138 return Layer.succeed(Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 139–154why, one step back139 Drafter,140 Drafter.of({141 draft: (input) =>142 Effect.gen(function* () {143 const reply = yield* Effect.tryPromise({144 catch: (error) =>145 failed(146 reasonOf(147 Predicate.hasProperty(error, "message") &&148 Predicate.isString(error.message)149 ? error.message150 : String(error)151 )152 ),153 try: () =>154 ai.run(model, {Merge build/1007oscabrielbefore adoption77fa97a
lines 155–156why, one step back155 ...settings.reasoning,156 max_completion_tokens: settings.max_completion_tokens,Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 157–180why, one step back157 messages: [158 {159 content: systemPrompt(input.context.policy),160 role: "system",161 },162 { content: userPrompt(input), role: "user" },163 ],164 response_format: {165 json_schema: responseSchema,166 type: "json_schema",167 },168 seed: seedOf(input),169 temperature: 0.2,170 }),171 });172173 return yield* draftedOf(174 yield* Effect.mapError(decodeReply(reply), () =>175 failed("unparseable")176 )177 );178 }),179 })180 );Merge build/1007oscabrielbefore adoption77fa97a
line 181why, one step back181};