Represents an object that can translate natural language requests in JSON objects of the given type.
| 10 | T = TypeVar("T", covariant=True) |
| 11 | |
| 12 | class TypeChatJsonTranslator(Generic[T]): |
| 13 | """ |
| 14 | Represents an object that can translate natural language requests in JSON objects of the given type. |
| 15 | """ |
| 16 | |
| 17 | model: TypeChatLanguageModel |
| 18 | validator: TypeChatValidator[T] |
| 19 | target_type: type[T] |
| 20 | type_name: str |
| 21 | schema_str: str |
| 22 | _max_repair_attempts = 1 |
| 23 | |
| 24 | def __init__( |
| 25 | self, |
| 26 | model: TypeChatLanguageModel, |
| 27 | validator: TypeChatValidator[T], |
| 28 | target_type: type[T], |
| 29 | *, # keyword-only parameters follow |
| 30 | _raise_on_schema_errors: bool = True, |
| 31 | ): |
| 32 | """ |
| 33 | Args: |
| 34 | model: The associated `TypeChatLanguageModel`. |
| 35 | validator: The associated `TypeChatValidator[T]`. |
| 36 | target_type: A runtime type object describing `T` - the expected shape of JSON data. |
| 37 | """ |
| 38 | super().__init__() |
| 39 | self.model = model |
| 40 | self.validator = validator |
| 41 | self.target_type = target_type |
| 42 | |
| 43 | conversion_result = python_type_to_typescript_schema(target_type) |
| 44 | |
| 45 | if _raise_on_schema_errors and conversion_result.errors: |
| 46 | error_text = "".join(f"\n- {error}" for error in conversion_result.errors) |
| 47 | raise ValueError(f"Could not convert Python type to TypeScript schema: \n{error_text}") |
| 48 | |
| 49 | self.type_name = conversion_result.typescript_type_reference |
| 50 | self.schema_str = conversion_result.typescript_schema_str |
| 51 | |
| 52 | async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: |
| 53 | """ |
| 54 | Translates a natural language request into an object of type `T`. If the JSON object returned by |
| 55 | the language model fails to validate, repair attempts will be made up until `_max_repair_attempts`. |
| 56 | The prompt for the subsequent attempts will include the diagnostics produced for the prior attempt. |
| 57 | This often helps produce a valid instance. |
| 58 | |
| 59 | Args: |
| 60 | input: A natural language request. |
| 61 | prompt_preamble: An optional string or list of prompt sections to prepend to the generated prompt.\ |
| 62 | If a string is given, it is converted to a single "user" role prompt section. |
| 63 | """ |
| 64 | |
| 65 | messages: list[PromptSection] = [] |
| 66 | |
| 67 | if prompt_preamble: |
| 68 | if isinstance(prompt_preamble, str): |
| 69 | prompt_preamble = [{"role": "user", "content": prompt_preamble}] |
no outgoing calls
no test coverage detected
searching dependent graphs…