File size: 1,842 Bytes
6dec997
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
export type ContractEvent =
  | {
      type: "attempt";
      attempt: number;
      prompt: string;
    }
  | {
      type: "parse_error";
      attempt: number;
      rawText: string;
      error: string;
    }
  | {
      type: "validation_error";
      attempt: number;
      rawText: string;
      parsed: unknown;
      issues: ContractIssue[];
    }
  | {
      type: "success";
      attempt: number;
      rawText: string;
      data: unknown;
    }
  | {
      type: "failure";
      attempts: number;
      replay: ContractReplay;
    };

export type ContractIssue = {
  path: string;
  message: string;
  code?: string;
};

export type ContractReplay = {
  prompt: string;
  attempts: ContractReplayAttempt[];
  createdAt: string;
};

export type ContractReplayAttempt = {
  attempt: number;
  prompt: string;
  rawText?: string;
  parsed?: unknown;
  error?: string;
  issues?: ContractIssue[];
};

export type ContractSchema<T> = {
  parse(value: unknown): T;
};

export type ContractModel = {
  generate(prompt: string, context: ContractModelContext): Promise<ContractModelResponse>;
};

export type ContractModelContext = {
  attempt: number;
  signal?: AbortSignal;
  previous?: ContractReplayAttempt;
};

export type ContractModelResponse =
  | string
  | {
      text: string;
      metadata?: Record<string, unknown>;
    };

export type ContractOptions<T> = {
  model: ContractModel;
  schema: ContractSchema<T>;
  prompt: string;
  retries?: number;
  signal?: AbortSignal;
  onEvent?: (event: ContractEvent) => void;
  repairPrompt?: (input: RepairPromptInput) => string;
};

export type RepairPromptInput = {
  originalPrompt: string;
  lastAttempt: ContractReplayAttempt;
  issues: ContractIssue[];
};

export type ContractResult<T> = {
  data: T;
  attempts: number;
  rawText: string;
  replay: ContractReplay;
};