-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtyped_message.py
More file actions
71 lines (56 loc) · 2.3 KB
/
Copy pathtyped_message.py
File metadata and controls
71 lines (56 loc) · 2.3 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
65
66
67
68
69
70
71
from pydantic import BaseModel, Field
from typing import Literal
from agentflowpy import SimpleAgent, Context, AGENT_START, AGENT_END
from dataclasses import dataclass, field
# from pydantic import BaseModel, Field
# #### MESSAGE AS RAW CLASS #####
# class Message:
# def __init__(self, content:str, role:str="user"):
# self.content = content
# self.role = role
# def __str__(self):
# return f"Message(content={self.content}, role={self.role})"
#### MESSAGE AS DATACLASS #####
@dataclass
class Message:
content:str
role:str = field(default="user")
# ##### MESSAGE AS Pydantic BaseModel #####
# class Message(BaseModel):
# content:str
# role:str = Field(default="user")
def get_message(context: Context[Message]):
msg = input("Enter your message (don't use 'badword'!): ")
context.messages.append(Message(role="user", content=msg))
return "filter_message"
def filter_message(context: Context[Message]):
last_user_msg = next((m for m in reversed(context.messages) if m.role == "user"), None)
is_bad = "badword" in last_user_msg.content.lower()
msg_i = context.messages.index(last_user_msg)
if is_bad:
last_user_msg.content = last_user_msg.content.lower().replace("badword", "****")
context.messages.append(Message(role="assistant", content="You have used a bad-word"))
print("Message contained bad word")
context.messages[msg_i] = last_user_msg
return AGENT_END if is_bad else "chatbot"
def chatbot(context: Context[Message]):
last_user_msg = next((m for m in reversed(context.messages) if m.role == "user"), None)
if last_user_msg:
response = f"Echoing your message: {last_user_msg.content}" # Mock cahtbot functionality
else:
response = "Hello! How can I assist you today?"
context.messages.append(Message(role="assistant", content=response))
return AGENT_END
agent = SimpleAgent[Message]()
# Register steps
agent.register(func=get_message, tag=AGENT_START)
agent.register(func=filter_message, tag="filter_message")
agent.register(func=chatbot, tag="chatbot")
# Add Context
agent.add_context("cx", Context[Message]())
while True:
agent.run("cx")
print("Final message history:")
for m in agent.get_context("cx").messages:
print(">", m)
print("\nNEW CYCLE STARTED")