MCPcopy Create free account
hub / github.com/microsoft/TypeChat / TranslatorWithHistory

Class TranslatorWithHistory

python/examples/healthData/translator.py:16–67  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14
15
16class 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"""
44user: 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
49user:
50Use precise date and times RELATIVE TO CURRENT DATE: {now.strftime('%A, %m %d, %Y')} CURRENT TIME: {now.strftime("%H:%M:%S")}
51Also turn ranges like next week and next month into precise dates
52
53user:
54{self._additional_agent_instructions}
55
56system:
57IMPORTANT CONTEXT for the user request:
58{history_str}
59
60user:
61The 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

Callers 1

mainFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…