Spaces:
No application file
No application file
File size: 6,726 Bytes
f6aeffd 19193e8 9f091b1 19193e8 f6aeffd 19193e8 f6aeffd 19193e8 f6aeffd 19193e8 76026dc f6aeffd 19193e8 76026dc f6aeffd 19193e8 f6aeffd 76026dc f6aeffd 9f091b1 583e2d6 9f091b1 76026dc 9f091b1 76026dc f6aeffd 9f091b1 f6aeffd 76026dc f6aeffd 76026dc f6aeffd 76026dc f6aeffd 76026dc f6aeffd 76026dc f6aeffd 76026dc f6aeffd 76026dc 583e2d6 76026dc f6aeffd | 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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 | import json
import os
import logging
import chainlit as cl
from autogen_agentchat.base import TaskResult
from core.teams.teams import get_or_create_team
# Set up logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Load translations
current_dir = os.path.dirname(os.path.abspath(__file__))
translations_dir = os.path.join(current_dir, ".chainlit", "translations")
translations_file = os.path.join(translations_dir, "en-US.json")
if os.path.exists(translations_file):
with open(translations_file, "r", encoding="utf-8") as f:
translations = json.load(f)
logger.debug("Translations loaded successfully.")
else:
translations = {}
logger.warning("Translations file not found. Using default texts.")
# Translation helper
def t(key: str, default: str = "") -> str:
keys = key.split(".")
value = translations
for k in keys:
value = value.get(k, {})
if not isinstance(value, dict):
break
return value if isinstance(value, str) else default
# Handle user messages
@cl.on_message
async def on_message(message: cl.Message):
logger.info(f"Received message from user: {message.content}")
try:
# Get or create the agent team
team = await get_or_create_team()
# Run the team stream for the provided message content
response_stream = team.run_stream(task=message.content)
async for msg in response_stream:
logger.debug(f"Stream message received: {msg}")
# Check if the message is a task result (termination condition)
if isinstance(msg, TaskResult):
await cl.Message(
content=t("messages.termination", "The task is complete."),
author="Agent Team",
).send()
# Reset team to None when task completes
cl.user_session.set("team", None)
break
# Handle regular messages in the stream
if hasattr(msg, "content") and msg.content:
source = getattr(
msg, "source", "unknown"
) # Use 'source' to identify sender
if source == "advisor_agent":
logger.debug(f"Advisor Agent response: {msg.content}")
await cl.Message(
content=f"Thinking...", author="Advisor Agent"
).send()
elif source in [
"housing_agent",
"job_training_agent",
"healthcare_agent",
"language_access_agent",
"civic_engagement_agent",
"immigration_agent",
]:
logger.debug(
f"Specialized Agent ({source}) response: {msg.content}"
)
await cl.Message(content=msg.content, author=source).send()
elif source == "user_proxy":
logger.debug(f"User proxy message: {msg.content}")
# await cl.Message(content=msg.content, author="User").send()
elif source == "TextMentionTermination":
# Handle termination message
logger.debug(f"Termination message received: {msg.content}")
await cl.Message(
content=t(
"messages.termination_mentioned",
"The task was terminated based on the conversation content.",
),
author="System",
).send()
cl.user_session.set("team", None)
break
else:
logger.warning(f"Unhandled source type: {source}")
else:
logger.warning(
"Message in stream has no content or unsupported structure."
)
except Exception as e:
logger.error(f"Error in on_message: {e}")
await cl.Message(
content=t("errors.unexpected", "An unexpected error occurred."),
author="System",
).send()
# Start session handlers
@cl.on_chat_start
async def on_chat_start():
logger.info("Chat session started.")
@cl.on_stop
async def on_stop():
cl.user_session.set("team", None)
await cl.Message(
content=t("messages.stopped", "The task has been stopped."),
author="System",
).send()
@cl.on_chat_end
async def on_chat_end():
cl.user_session.set("team", None)
logger.info("Chat session ended.")
@cl.on_chat_resume
async def on_chat_resume():
await cl.Message(
content=t(
"messages.welcome_back", "Welcome back! How can I assist you further?"
),
author="Assistant",
).send()
# Define starter messages
@cl.set_starters
async def set_starters():
"""Defines the starter messages available to users when initiating a chat."""
return [
cl.Starter(
label=t("starters.affordable_housing.label", "Affordable Housing"),
message=t("starters.affordable_housing.message", "Get help with housing."),
icon="/public/housing-policy-header.jpeg",
),
cl.Starter(
label=t("starters.job_training.label", "Job Training"),
message=t("starters.job_training.message", "Find job training resources."),
icon="/public/economy-policy-header.jpeg",
),
cl.Starter(
label=t("starters.healthcare_access.label", "Healthcare Access"),
message=t(
"starters.healthcare_access.message", "Access healthcare services."
),
icon="/public/medicare-for-all-header.jpeg",
),
cl.Starter(
label=t("starters.language_access.label", "Language Access"),
message=t(
"starters.language_access.message", "Language assistance services."
),
icon="/public/immigration-policy-header.jpeg",
),
cl.Starter(
label=t("starters.immigration_access.label", "Immigration Access"),
message=t(
"starters.immigration_access.message",
"Immigration assistance services.",
),
icon="/public/immigration-policy-header.jpeg",
),
cl.Starter(
label=t("starters.civic_engagement.label", "Civic Engagement"),
message=t(
"starters.civic_engagement.message", "Get involved in your community."
),
icon="/public/open-government-header.jpeg",
),
]
|