Skip to content

Commit aa3c9dc

Browse files
date changes
1 parent fb6bb20 commit aa3c9dc

File tree

4 files changed

+71
-11
lines changed

4 files changed

+71
-11
lines changed

src/backend/app_kernel.py

Lines changed: 64 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
from auth.auth_utils import get_authenticated_user_details
1111

1212
# Azure monitoring
13+
import re
14+
from dateutil import parser
1315
from azure.monitor.opentelemetry import configure_azure_monitor
1416
from config_kernel import Config
1517
from event_utils import track_event_if_configured
@@ -35,6 +37,7 @@
3537
# Updated import for KernelArguments
3638
from utils_kernel import initialize_runtime_and_context, rai_success
3739

40+
3841
# Check if the Application Insights Instrumentation Key is set in the environment variables
3942
connection_string = os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING")
4043
if connection_string:
@@ -71,7 +74,7 @@
7174
# Add this near the top of your app.py, after initializing the app
7275
app.add_middleware(
7376
CORSMiddleware,
74-
allow_origins=['*'],
77+
allow_origins=[frontend_url],
7578
allow_credentials=True,
7679
allow_methods=["*"],
7780
allow_headers=["*"],
@@ -81,6 +84,53 @@
8184
app.add_middleware(HealthCheckMiddleware, password="", checks={})
8285
logging.info("Added health check middleware")
8386

87+
def format_dates_in_messages(messages, target_locale="en-US"):
88+
"""
89+
Format dates in agent messages according to the specified locale.
90+
91+
Args:
92+
messages: List of message objects or string content
93+
target_locale: Target locale for date formatting (default: en-US)
94+
95+
Returns:
96+
Formatted messages with dates converted to target locale format
97+
"""
98+
# Define target format patterns per locale
99+
locale_date_formats = {
100+
"en-IN": "%d %b %Y", # 30 Jul 2025
101+
"en-US": "%b %d, %Y", # Jul 30, 2025
102+
}
103+
104+
output_format = locale_date_formats.get(target_locale, "%d %b %Y")
105+
# Match both "Jul 30, 2025, 12:00:00 AM" and "30 Jul 2025"
106+
date_pattern = r'(\d{1,2} [A-Za-z]{3,9} \d{4}|[A-Za-z]{3,9} \d{1,2}, \d{4}(, \d{1,2}:\d{2}:\d{2} ?[APap][Mm])?)'
107+
108+
def convert_date(match):
109+
date_str = match.group(0)
110+
try:
111+
dt = parser.parse(date_str)
112+
return dt.strftime(output_format)
113+
except Exception:
114+
return date_str # Leave it unchanged if parsing fails
115+
116+
# Process messages
117+
if isinstance(messages, list):
118+
formatted_messages = []
119+
for message in messages:
120+
if hasattr(message, 'content') and message.content:
121+
# Create a copy of the message with formatted content
122+
formatted_message = message.model_copy() if hasattr(message, 'model_copy') else message
123+
if hasattr(formatted_message, 'content'):
124+
formatted_message.content = re.sub(date_pattern, convert_date, formatted_message.content)
125+
formatted_messages.append(formatted_message)
126+
else:
127+
formatted_messages.append(message)
128+
return formatted_messages
129+
elif isinstance(messages, str):
130+
return re.sub(date_pattern, convert_date, messages)
131+
else:
132+
return messages
133+
84134
@app.post("/api/user_browser_language")
85135
async def user_browser_language_endpoint(
86136
user_language: UserLanguage,
@@ -211,6 +261,13 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
211261
}
212262

213263
except Exception as e:
264+
# Extract clean error message for rate limit errors
265+
error_msg = str(e)
266+
if "Rate limit is exceeded" in error_msg:
267+
match = re.search(r"Rate limit is exceeded\. Try again in (\d+) seconds?\.", error_msg)
268+
if match:
269+
error_msg = f"Rate limit is exceeded. Try again in {match.group(1)} seconds."
270+
214271
track_event_if_configured(
215272
"InputTaskError",
216273
{
@@ -219,7 +276,7 @@ async def input_task_endpoint(input_task: InputTask, request: Request):
219276
"error": str(e),
220277
},
221278
)
222-
raise HTTPException(status_code=400, detail=f"Error creating plan: {e}")
279+
raise HTTPException(status_code=400, detail=f"Error creating plan: {error_msg}") from e
223280

224281

225282
@app.post("/api/human_feedback")
@@ -660,7 +717,11 @@ async def get_plans(
660717

661718
plan_with_steps = PlanWithSteps(**plan.model_dump(), steps=steps)
662719
plan_with_steps.update_step_counts()
663-
return [plan_with_steps, messages]
720+
721+
# Format dates in messages according to locale
722+
formatted_messages = format_dates_in_messages(messages, config.get_user_local_browser_language())
723+
724+
return [plan_with_steps, formatted_messages]
664725

665726
all_plans = await memory_store.get_all_plans()
666727
# Fetch steps for all plans concurrently

src/backend/kernel_tools/product_tools.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,25 +10,25 @@
1010
import json
1111
from typing import get_type_hints
1212
from utils_date import format_date_for_user
13+
from app_config import config
1314

1415

1516
class ProductTools:
1617
"""Define Product Agent functions (tools)"""
1718

1819
agent_name = AgentType.PRODUCT.value
19-
20+
selecetd_language = config.get_user_local_browser_language()
2021
@staticmethod
2122
@kernel_function(
22-
description="Add an extras pack/new product to the mobile plan for the customer. For example, adding a roaming plan to their service."
23+
description="Add an extras pack/new product to the mobile plan for the customer. For example, adding a roaming plan to their service. Convert all date strings in the following text to short date format with 3-letter month (MMM) in the {selecetd_language} locale (e.g., en-US, en-IN), remove time, and replace original dates with the formatted ones"
2324
)
2425
async def add_mobile_extras_pack(new_extras_pack_name: str, start_date: str) -> str:
2526
"""Add an extras pack/new product to the mobile plan for the customer. For example, adding a roaming plan to their service. The arguments should include the new_extras_pack_name and the start_date as strings. You must provide the exact plan name, as found using the get_product_info() function."""
2627
formatting_instructions = "Instructions: returning the output of this function call verbatim to the user in markdown. Then write AGENT SUMMARY: and then include a summary of what you did."
27-
formatted_date = format_date_for_user(start_date)
2828
analysis = (
2929
f"# Request to Add Extras Pack to Mobile Plan\n"
3030
f"## New Plan:\n{new_extras_pack_name}\n"
31-
f"## Start Date:\n{formatted_date}\n\n"
31+
f"## Start Date:\n{start_date}\n\n"
3232
f"These changes have been completed and should be reflected in your app in 5-10 minutes."
3333
f"\n\n{formatting_instructions}"
3434
)

src/frontend/src/components/content/HomeInput.tsx

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,9 @@ const HomeInput: React.FC<HomeInputProps> = ({
7272
showToast("Failed to create plan", "error");
7373
dismissToast(id);
7474
}
75-
} catch (error) {
75+
} catch (error:any) {
7676
dismissToast(id);
77-
console.log("ERROR:", error);
78-
showToast(error instanceof Error ? error.message : String(error ?? ""), "error");
77+
showToast(JSON.parse(error?.message)?.detail, "error");
7978
} finally {
8079
setInput("");
8180
setSubmitting(false);

src/frontend/src/services/TaskService.tsx

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ export class TaskService {
190190
if (error?.response?.data?.message) {
191191
message = error.response.data.message;
192192
} else if (error?.message) {
193-
message = error.message;
193+
message = error.message?.detail ? error.message.detail : error.message;
194194
}
195195
// Throw a new error with a user-friendly message
196196
throw new Error(message);

0 commit comments

Comments
 (0)