|
21 | 21 | from semantic_kernel.agents import AzureAIAgentThread |
22 | 22 | from semantic_kernel.exceptions.agent_exceptions import AgentException |
23 | 23 |
|
24 | | -from azure.ai.agents.models import TruncationObject |
| 24 | +from azure.ai.agents.models import TruncationObject, MessageRole, ListSortOrder |
25 | 25 |
|
26 | 26 | from cachetools import TTLCache |
27 | 27 |
|
28 | 28 | from helpers.utils import format_stream_response |
29 | | -from helpers.azure_openai_helper import get_azure_openai_client |
30 | 29 | from common.config.config import Config |
| 30 | +from agents.chart_agent_factory import ChartAgentFactory |
31 | 31 |
|
32 | 32 | # Constants |
33 | 33 | HOST_NAME = "CKM" |
@@ -86,47 +86,59 @@ def __init__(self, request : Request): |
86 | 86 | if ChatService.thread_cache is None: |
87 | 87 | ChatService.thread_cache = ExpCache(maxsize=1000, ttl=3600.0, agent=self.agent) |
88 | 88 |
|
89 | | - def process_rag_response(self, rag_response, query): |
| 89 | + async def process_rag_response(self, rag_response, query): |
90 | 90 | """ |
91 | | - Parses the RAG response dynamically to extract chart data for Chart.js. |
| 91 | + Uses the ChartAgent directly (agentic call) to extract chart data for Chart.js. |
92 | 92 | """ |
93 | 93 | try: |
94 | | - client = get_azure_openai_client() |
95 | | - |
96 | | - system_prompt = """You are an assistant that helps generate valid chart data to be shown using chart.js with version 4.4.4 compatible. |
97 | | - Include chart type and chart options. |
98 | | - Pick the best chart type for given data. |
99 | | - Do not generate a chart unless the input contains some numbers. Otherwise return a message that Chart cannot be generated. |
100 | | - Only return a valid JSON output and nothing else. |
101 | | - Verify that the generated JSON can be parsed using json.loads. |
102 | | - Do not include tooltip callbacks in JSON. |
103 | | - Always make sure that the generated json can be rendered in chart.js. |
104 | | - Always remove any extra trailing commas. |
105 | | - Verify and refine that JSON should not have any syntax errors like extra closing brackets. |
106 | | - Ensure Y-axis labels are fully visible by increasing **ticks.padding**, **ticks.maxWidth**, or enabling word wrapping where necessary. |
107 | | - Ensure bars and data points are evenly spaced and not squished or cropped at **100%** resolution by maintaining appropriate **barPercentage** and **categoryPercentage** values.""" |
108 | 94 | user_prompt = f"""Generate chart data for - |
109 | 95 | {query} |
110 | 96 | {rag_response} |
111 | 97 | """ |
112 | | - logger.info(">>> Processing chart data for response: %s", rag_response) |
113 | | - |
114 | | - completion = client.chat.completions.create( |
115 | | - model=self.azure_openai_deployment_name, |
116 | | - messages=[ |
117 | | - {"role": "system", "content": system_prompt}, |
118 | | - {"role": "user", "content": user_prompt}, |
119 | | - ], |
120 | | - temperature=0, |
| 98 | + |
| 99 | + agent_info = await ChartAgentFactory.get_agent() |
| 100 | + agent = agent_info["agent"] |
| 101 | + client = agent_info["client"] |
| 102 | + |
| 103 | + thread = client.agents.threads.create() |
| 104 | + |
| 105 | + client.agents.messages.create( |
| 106 | + thread_id=thread.id, |
| 107 | + role=MessageRole.USER, |
| 108 | + content=user_prompt |
| 109 | + ) |
| 110 | + |
| 111 | + run = client.agents.runs.create_and_process( |
| 112 | + thread_id=thread.id, |
| 113 | + agent_id=agent.id |
121 | 114 | ) |
122 | 115 |
|
123 | | - chart_data = completion.choices[0].message.content.strip().replace("```json", "").replace("```", "") |
124 | | - logger.info(">>> Generated chart data: %s", chart_data) |
| 116 | + if run.status == "failed": |
| 117 | + print(f"[Chart Agent] Run failed: {run.last_error}") |
| 118 | + return {"error": "Chart could not be generated due to agent failure."} |
| 119 | + |
| 120 | + chart_json = "" |
| 121 | + messages = client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING) |
| 122 | + for msg in messages: |
| 123 | + if msg.role == MessageRole.AGENT and msg.text_messages: |
| 124 | + chart_json = msg.text_messages[-1].text.value.strip() |
| 125 | + break |
| 126 | + |
| 127 | + client.agents.threads.delete(thread_id=thread.id) |
| 128 | + |
| 129 | + chart_json = chart_json.replace("```json", "").replace("```", "").strip() |
| 130 | + chart_data = json.loads(chart_json) |
| 131 | + |
| 132 | + if not chart_data or "error" in chart_data: |
| 133 | + return { |
| 134 | + "error": chart_data.get("error", "Chart could not be generated from this data."), |
| 135 | + "hint": "Try asking a question with some numerical values, like 'sales per region' or 'calls per day'." |
| 136 | + } |
125 | 137 |
|
126 | | - return json.loads(chart_data) |
| 138 | + return chart_data |
127 | 139 |
|
128 | 140 | except Exception as e: |
129 | | - logger.error("Error processing RAG response: %s", e) |
| 141 | + logger.error("Agent error in chart generation: %s", e) |
130 | 142 | return {"error": "Chart could not be generated from this data. Please ask a different question."} |
131 | 143 |
|
132 | 144 | async def stream_openai_text(self, conversation_id: str, query: str) -> StreamingResponse: |
@@ -254,7 +266,7 @@ async def complete_chat_request(self, query, last_rag_response=None): |
254 | 266 | return {"error": "A previous RAG response is required to generate a chart."} |
255 | 267 |
|
256 | 268 | # Process RAG response to generate chart data |
257 | | - chart_data = self.process_rag_response(last_rag_response, query) |
| 269 | + chart_data = await self.process_rag_response(last_rag_response, query) |
258 | 270 |
|
259 | 271 | if not chart_data or "error" in chart_data: |
260 | 272 | return { |
|
0 commit comments