Update server.py
Browse files
server.py
CHANGED
@@ -827,11 +827,15 @@ def format_workflow_output(raw_output, agent_responses=None):
|
|
827 |
if not raw_output:
|
828 |
return "β No output received"
|
829 |
|
|
|
|
|
|
|
|
|
830 |
lines = raw_output.split('\n')
|
831 |
formatted_lines = []
|
832 |
|
833 |
for line in lines:
|
834 |
-
line = line.strip()
|
835 |
if not line:
|
836 |
formatted_lines.append("")
|
837 |
continue
|
@@ -857,10 +861,12 @@ def format_workflow_output(raw_output, agent_responses=None):
|
|
857 |
if isinstance(response, dict):
|
858 |
# Format dictionary responses nicely
|
859 |
for key, value in response.items():
|
860 |
-
|
861 |
-
|
|
|
|
|
862 |
else:
|
863 |
-
formatted_lines.append(f"{
|
864 |
else:
|
865 |
# Format string responses
|
866 |
response_str = str(response)
|
@@ -880,7 +886,6 @@ def format_workflow_output(raw_output, agent_responses=None):
|
|
880 |
|
881 |
return '\n'.join(formatted_lines)
|
882 |
|
883 |
-
|
884 |
def format_agent_responses(agent_responses):
|
885 |
"""Create a dedicated section for agent responses"""
|
886 |
if not agent_responses:
|
@@ -889,23 +894,31 @@ def format_agent_responses(agent_responses):
|
|
889 |
formatted = ["## π± Agent Responses", ""]
|
890 |
|
891 |
for agent_name, response in agent_responses.items():
|
892 |
-
|
|
|
|
|
893 |
|
894 |
-
|
|
|
|
|
895 |
formatted.append(f"### β {clean_name}")
|
896 |
-
formatted.append(f"**Error:** {
|
897 |
else:
|
898 |
formatted.append(f"### β
{clean_name}")
|
899 |
|
900 |
if isinstance(response, dict):
|
901 |
for key, value in response.items():
|
902 |
-
|
903 |
-
|
904 |
-
|
|
|
|
|
905 |
elif isinstance(value, list):
|
906 |
-
|
|
|
|
|
907 |
else:
|
908 |
-
formatted.append(f"```\n{
|
909 |
else:
|
910 |
response_str = str(response)
|
911 |
if len(response_str) > 300:
|
@@ -915,45 +928,10 @@ def format_agent_responses(agent_responses):
|
|
915 |
|
916 |
formatted.append("")
|
917 |
|
|
|
|
|
918 |
return '\n'.join(formatted)
|
919 |
|
920 |
-
|
921 |
-
def format_alert_summary(raw_data):
|
922 |
-
"""Format alert summary"""
|
923 |
-
if not raw_data or 'alert_data' not in raw_data:
|
924 |
-
return "No alert data available"
|
925 |
-
|
926 |
-
alert_data = raw_data['alert_data']
|
927 |
-
|
928 |
-
summary = f"""
|
929 |
-
## π¨ Alert Summary
|
930 |
-
|
931 |
-
**π Location:** {alert_data['location']['village']}, {alert_data['location']['district']}, {alert_data['location']['state']}
|
932 |
-
|
933 |
-
**πΎ Crop Information:**
|
934 |
-
- **Crop:** {alert_data['crop']['name'].title()}
|
935 |
-
- **Growth Stage:** {alert_data['crop']['stage']}
|
936 |
-
- **Season:** {alert_data['crop']['season'].title()}
|
937 |
-
|
938 |
-
**π€οΈ Weather Conditions:**
|
939 |
-
- **Temperature:** {alert_data['weather']['temperature']}
|
940 |
-
- **Expected Rainfall:** {alert_data['weather']['expected_rainfall']}
|
941 |
-
- **Wind Speed:** {alert_data['weather']['wind_speed']}
|
942 |
-
- **Rain Probability:** {alert_data['weather']['rain_probability']}%
|
943 |
-
|
944 |
-
**β οΈ Alert Details:**
|
945 |
-
- **Type:** {alert_data['alert']['type'].replace('_', ' ').title()}
|
946 |
-
- **Urgency:** {alert_data['alert']['urgency'].upper()}
|
947 |
-
- **AI Enhanced:** {'β
Yes' if alert_data['alert']['ai_generated'] else 'β No'}
|
948 |
-
|
949 |
-
**π¨ Alert Message:**
|
950 |
-
{alert_data['alert']['message']}
|
951 |
-
|
952 |
-
**π― Action Items:**
|
953 |
-
{chr(10).join([f"- {item.replace('_', ' ').title()}" for item in alert_data['alert']['action_items']])}
|
954 |
-
"""
|
955 |
-
return summary
|
956 |
-
|
957 |
def run_workflow_ui(district):
|
958 |
"""Run workflow directly using internal functions"""
|
959 |
if not district:
|
@@ -1005,7 +983,7 @@ def run_workflow_ui(district):
|
|
1005 |
logger.exception(f"UI workflow error: {e}")
|
1006 |
return error_msg, "", "", gr.File(visible=False)
|
1007 |
|
1008 |
-
#
|
1009 |
def create_gradio_interface():
|
1010 |
with gr.Blocks(
|
1011 |
title="BIHAR AgMCP - Agricultural Weather Alerts",
|
@@ -1082,6 +1060,7 @@ def run_fastapi():
|
|
1082 |
log_level=LOG_LEVEL.lower()
|
1083 |
)
|
1084 |
|
|
|
1085 |
if __name__ == "__main__":
|
1086 |
if os.getenv("SPACE_ID") or os.getenv("GRADIO_SERVER_NAME"):
|
1087 |
# HuggingFace Spaces - start FastAPI in background, Gradio in foreground
|
@@ -1103,4 +1082,5 @@ if __name__ == "__main__":
|
|
1103 |
)
|
1104 |
else:
|
1105 |
logger.info("Starting MCP Weather Server (API only)...")
|
1106 |
-
run_fastapi()
|
|
|
|
827 |
if not raw_output:
|
828 |
return "β No output received"
|
829 |
|
830 |
+
# Ensure raw_output is a string
|
831 |
+
if not isinstance(raw_output, str):
|
832 |
+
raw_output = str(raw_output)
|
833 |
+
|
834 |
lines = raw_output.split('\n')
|
835 |
formatted_lines = []
|
836 |
|
837 |
for line in lines:
|
838 |
+
line = str(line).strip() # Ensure line is string
|
839 |
if not line:
|
840 |
formatted_lines.append("")
|
841 |
continue
|
|
|
861 |
if isinstance(response, dict):
|
862 |
# Format dictionary responses nicely
|
863 |
for key, value in response.items():
|
864 |
+
key_str = str(key)
|
865 |
+
value_str = str(value)
|
866 |
+
if len(value_str) > 200:
|
867 |
+
formatted_lines.append(f"{key_str}: {value_str[:200]}...")
|
868 |
else:
|
869 |
+
formatted_lines.append(f"{key_str}: {value_str}")
|
870 |
else:
|
871 |
# Format string responses
|
872 |
response_str = str(response)
|
|
|
886 |
|
887 |
return '\n'.join(formatted_lines)
|
888 |
|
|
|
889 |
def format_agent_responses(agent_responses):
|
890 |
"""Create a dedicated section for agent responses"""
|
891 |
if not agent_responses:
|
|
|
894 |
formatted = ["## π± Agent Responses", ""]
|
895 |
|
896 |
for agent_name, response in agent_responses.items():
|
897 |
+
# Ensure agent_name is string
|
898 |
+
agent_name_str = str(agent_name)
|
899 |
+
clean_name = agent_name_str.replace("π± ", "").replace("π ", "").replace("ποΈ ", "").replace("π€ ", "")
|
900 |
|
901 |
+
# Convert response to string for error checking
|
902 |
+
response_str = str(response)
|
903 |
+
if response_str.startswith('Error:'):
|
904 |
formatted.append(f"### β {clean_name}")
|
905 |
+
formatted.append(f"**Error:** {response_str}")
|
906 |
else:
|
907 |
formatted.append(f"### β
{clean_name}")
|
908 |
|
909 |
if isinstance(response, dict):
|
910 |
for key, value in response.items():
|
911 |
+
key_str = str(key)
|
912 |
+
value_str = str(value)
|
913 |
+
formatted.append(f"**{key_str.title()}:**")
|
914 |
+
if len(value_str) > 300:
|
915 |
+
formatted.append(f"```\n{value_str[:300]}...\n```")
|
916 |
elif isinstance(value, list):
|
917 |
+
# Handle list values
|
918 |
+
list_str = '\n'.join([str(item) for item in value])
|
919 |
+
formatted.append(f"```\n{list_str}\n```")
|
920 |
else:
|
921 |
+
formatted.append(f"```\n{value_str}\n```")
|
922 |
else:
|
923 |
response_str = str(response)
|
924 |
if len(response_str) > 300:
|
|
|
928 |
|
929 |
formatted.append("")
|
930 |
|
931 |
+
# Ensure all items in formatted list are strings
|
932 |
+
formatted = [str(item) for item in formatted]
|
933 |
return '\n'.join(formatted)
|
934 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
935 |
def run_workflow_ui(district):
|
936 |
"""Run workflow directly using internal functions"""
|
937 |
if not district:
|
|
|
983 |
logger.exception(f"UI workflow error: {e}")
|
984 |
return error_msg, "", "", gr.File(visible=False)
|
985 |
|
986 |
+
# Updated Gradio interface
|
987 |
def create_gradio_interface():
|
988 |
with gr.Blocks(
|
989 |
title="BIHAR AgMCP - Agricultural Weather Alerts",
|
|
|
1060 |
log_level=LOG_LEVEL.lower()
|
1061 |
)
|
1062 |
|
1063 |
+
# Usage in your main section:
|
1064 |
if __name__ == "__main__":
|
1065 |
if os.getenv("SPACE_ID") or os.getenv("GRADIO_SERVER_NAME"):
|
1066 |
# HuggingFace Spaces - start FastAPI in background, Gradio in foreground
|
|
|
1082 |
)
|
1083 |
else:
|
1084 |
logger.info("Starting MCP Weather Server (API only)...")
|
1085 |
+
run_fastapi()
|
1086 |
+
|