| 14 | |
| 15 | |
| 16 | class TranslatorWithHistory(TypeChatJsonTranslator[T]): |
| 17 | _chat_history: list[ChatMessage] |
| 18 | _max_prompt_length: int |
| 19 | _additional_agent_instructions: str |
| 20 | |
| 21 | def __init__( |
| 22 | self, model: TypeChatLanguageModel, validator: TypeChatValidator[T], target_type: type[T], additional_agent_instructions: str |
| 23 | ): |
| 24 | super().__init__(model=model, validator=validator, target_type=target_type) |
| 25 | self._chat_history = [] |
| 26 | self._max_prompt_length = 2048 |
| 27 | self._additional_agent_instructions = additional_agent_instructions |
| 28 | |
| 29 | @override |
| 30 | async def translate(self, input: str, *, prompt_preamble: str | list[PromptSection] | None = None) -> Result[T]: |
| 31 | result = await super().translate(input=input, prompt_preamble=prompt_preamble) |
| 32 | if not isinstance(result, Failure): |
| 33 | self._chat_history.append(ChatMessage(source="assistant", body=result.value)) |
| 34 | return result |
| 35 | |
| 36 | @override |
| 37 | def _create_request_prompt(self, intent: str) -> str: |
| 38 | # TODO: drop history entries if we exceed the max_prompt_length |
| 39 | history_str = json.dumps(self._chat_history, indent=2, default=lambda o: None, allow_nan=False) |
| 40 | |
| 41 | now = datetime.now() |
| 42 | |
| 43 | prompt = F""" |
| 44 | user: You are a service that translates user requests into JSON objects of type "{self.type_name}" according to the following TypeScript definitions: |
| 45 | ''' |
| 46 | {self.schema_str} |
| 47 | ''' |
| 48 | |
| 49 | user: |
| 50 | Use precise date and times RELATIVE TO CURRENT DATE: {now.strftime('%A, %m %d, %Y')} CURRENT TIME: {now.strftime("%H:%M:%S")} |
| 51 | Also turn ranges like next week and next month into precise dates |
| 52 | |
| 53 | user: |
| 54 | {self._additional_agent_instructions} |
| 55 | |
| 56 | system: |
| 57 | IMPORTANT CONTEXT for the user request: |
| 58 | {history_str} |
| 59 | |
| 60 | user: |
| 61 | The following is a user request: |
| 62 | ''' |
| 63 | {intent} |
| 64 | ''' |
| 65 | The following is the user request translated into a JSON object with 2 spaces of indentation and no properties with the value undefined: |
| 66 | """ |
| 67 | return prompt |
no outgoing calls
no test coverage detected
searching dependent graphs…