91 lines
2.5 kB
1"""Pydantic models for what is read from disk and what is written back.
2
3Input models are forgiving, because the files are given to us and a single odd
4entry must not stop the run. The output model is strict, because its shape is
5what the program is graded on.
6"""
7
8from enum import Enum
9from typing import Any, Dict
10
11from pydantic import BaseModel, ConfigDict, Field, field_validator
12
13
14class JsonType(str, Enum):
15 """The parameter types this program knows how to generate."""
16
17 STRING = "string"
18 NUMBER = "number"
19 INTEGER = "integer"
20 BOOLEAN = "boolean"
21
22
23class ParameterDefinition(BaseModel):
24 """One parameter of a function, as declared in the definitions file.
25
26 Attributes:
27 type: The JSON type the argument must have.
28 """
29
30 model_config = ConfigDict(extra="ignore", frozen=True)
31
32 type: JsonType = JsonType.STRING
33
34 @field_validator("type", mode="before")
35 @classmethod
36 def _known_type(cls, value: Any) -> Any:
37 """Fall back to a string for any type this program cannot generate.
38
39 Args:
40 value: The type as written in the definitions file.
41
42 Returns:
43 The value itself when it is supported, "string" otherwise.
44 """
45 if isinstance(value, str) and value in tuple(item.value for item in JsonType):
46 return value
47 return JsonType.STRING.value
48
49
50class FunctionDefinition(BaseModel):
51 """One function the model may choose to call.
52
53 Attributes:
54 name: The function name, which is what the model has to produce.
55 description: What the function does, shown to the model.
56 parameters: The parameters, in declaration order.
57 """
58
59 model_config = ConfigDict(extra="ignore", frozen=True)
60
61 name: str = Field(min_length=1)
62 description: str = ""
63 parameters: Dict[str, ParameterDefinition] = Field(default_factory=dict)
64
65
66class PromptEntry(BaseModel):
67 """One entry of the prompts file.
68
69 Attributes:
70 prompt: The natural-language request to answer.
71 """
72
73 model_config = ConfigDict(extra="ignore", frozen=True)
74
75 prompt: str
76
77
78class FunctionCall(BaseModel):
79 """One answer, written to the results file.
80
81 Attributes:
82 prompt: The request this call answers.
83 name: The chosen function.
84 parameters: The arguments to call it with.
85 """
86
87 model_config = ConfigDict(extra="forbid", frozen=True)
88
89 prompt: str
90 name: str
91 parameters: Dict[str, Any]