-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.py
More file actions
64 lines (48 loc) · 2.28 KB
/
main.py
File metadata and controls
64 lines (48 loc) · 2.28 KB
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
from pydantic import BaseModel, Field
from typing import Iterator, Protocol, Callable
from haverscript import *
from haverscript.types import Reply, Prompt, Contexture
from copy import deepcopy
class Translate(BaseModel):
english: str = Field(
..., description="the original English text, and only the original text."
)
french: str = Field(
..., description="the translated French text, and only the translated text."
)
class FrenchAgent(Agent):
system: str = "You are a translator, translating from English to French. "
previous: list[Translate] = Field(default_factory=list)
def chat_to_bot(self, prompt: str) -> Reply:
return Reply(self._stream(prompt))
def _stream(self, prompt) -> Iterator:
max_traslations = 3
if len(self.previous) >= max_traslations:
yield f"Sorry. French lesson over.\nYour {max_traslations} translations:\n"
for resp in self.previous:
assert isinstance(resp, Translate)
yield f"* {resp.english} => {resp.french}\n"
else:
down_prompt = Markdown()
down_prompt += f"You are a translator, translating from English to French. "
down_prompt += f"English Text: {prompt}"
down_prompt += reply_in_json(Translate)
translated: Translate = self.ask(down_prompt, format=Translate)
self.previous.append(translated)
remaining = max_traslations - len(self.previous)
yield f"{translated.english} in French is {translated.french}\n"
yield "\n"
yield f"{remaining} translation(s) left."
# In a real example, validate and retry would be added to provide robustness.
session = connect_chatbot(FrenchAgent(model=connect("mistral"))) | echo()
print("--[ User-facing conversation ]------")
session = session.chat("Three blind mice")
session = session.chat("Such is life")
session = session.chat("All roads lead to Rome")
session = session.chat("The quick brown fox")
session = connect_chatbot(FrenchAgent(model=connect("mistral") | echo()))
print("--[ LLM-facing conversation ]------")
session = session.chat("Three blind mice")
session = session.chat("Such is life")
session = session.chat("All roads lead to Rome")
session = session.chat("The quick brown fox")