|
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 | 29 | from helpers.azure_openai_helper import get_azure_openai_client |
30 | 30 | from common.config.config import Config |
| 31 | +from agents.chart_agent_factory import ChartAgentFactory |
31 | 32 |
|
32 | 33 | # Constants |
33 | 34 | HOST_NAME = "CKM" |
@@ -86,49 +87,118 @@ def __init__(self, request : Request): |
86 | 87 | if ChatService.thread_cache is None: |
87 | 88 | ChatService.thread_cache = ExpCache(maxsize=1000, ttl=3600.0, agent=self.agent) |
88 | 89 |
|
89 | | - def process_rag_response(self, rag_response, query): |
| 90 | + async def process_rag_response(self, rag_response, query): |
90 | 91 | """ |
91 | | - Parses the RAG response dynamically to extract chart data for Chart.js. |
| 92 | + Uses the ChartAgent directly (agentic call) to extract chart data for Chart.js. |
92 | 93 | """ |
93 | 94 | 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 | | - user_prompt = f"""Generate chart data for - |
109 | | - {query} |
110 | | - {rag_response} |
111 | | - """ |
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, |
| 95 | + combined_input = f"{query}\n{rag_response}" |
| 96 | + |
| 97 | + agent_info = await ChartAgentFactory.get_agent() |
| 98 | + agent = agent_info["agent"] |
| 99 | + client = agent_info["client"] |
| 100 | + |
| 101 | + thread = client.agents.threads.create() |
| 102 | + |
| 103 | + client.agents.messages.create( |
| 104 | + thread_id=thread.id, |
| 105 | + role=MessageRole.USER, |
| 106 | + content=combined_input |
| 107 | + ) |
| 108 | + |
| 109 | + print(f"thread with id:{thread.id}",flush=True) |
| 110 | + print(f"agent id:{agent.id}",flush=True) |
| 111 | + print(f"project clinet :{client}",flush=True) |
| 112 | + |
| 113 | + run = client.agents.runs.create_and_process( |
| 114 | + thread_id=thread.id, |
| 115 | + agent_id=agent.id |
121 | 116 | ) |
122 | 117 |
|
123 | | - chart_data = completion.choices[0].message.content.strip().replace("```json", "").replace("```", "") |
124 | | - logger.info(">>> Generated chart data: %s", chart_data) |
| 118 | + if run.status == "failed": |
| 119 | + print(f"[Chart Agent] Run failed: {run.last_error}") |
| 120 | + return {"error": "Chart could not be generated due to agent failure."} |
125 | 121 |
|
126 | | - return json.loads(chart_data) |
| 122 | + chart_json = "" |
| 123 | + messages = client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING) |
| 124 | + for msg in messages: |
| 125 | + if msg.role == MessageRole.AGENT and msg.text_messages: |
| 126 | + chart_json = msg.text_messages[-1].text.value.strip() |
| 127 | + break |
| 128 | + |
| 129 | + client.agents.threads.delete(thread_id=thread.id) |
| 130 | + |
| 131 | + chart_json = chart_json.replace("```json", "").replace("```", "").strip() |
| 132 | + chart_data = json.loads(chart_json) |
| 133 | + |
| 134 | + if not chart_data or "error" in chart_data: |
| 135 | + return { |
| 136 | + "error": chart_data.get("error", "Chart could not be generated from this data."), |
| 137 | + "hint": "Try asking a question with some numerical values, like 'sales per region' or 'calls per day'." |
| 138 | + } |
| 139 | + |
| 140 | + return chart_data |
127 | 141 |
|
128 | 142 | except Exception as e: |
129 | | - logger.error("Error processing RAG response: %s", e) |
| 143 | + logger.error("Agent error in chart generation: %s", e) |
130 | 144 | return {"error": "Chart could not be generated from this data. Please ask a different question."} |
131 | 145 |
|
| 146 | + |
| 147 | + # async def run_agent(): |
| 148 | + # chart_data = {"error": "Chart could not be generated."} |
| 149 | + # try: |
| 150 | + # agent_info = await ChartAgentFactory.get_agent() |
| 151 | + # agent = agent_info["agent"] |
| 152 | + # client = agent_info["client"] |
| 153 | + |
| 154 | + # thread = client.agents.threads.create() |
| 155 | + # client.agents.messages.create( |
| 156 | + # thread_id=thread.id, |
| 157 | + # role=MessageRole.USER, |
| 158 | + # content=combined_input |
| 159 | + # ) |
| 160 | + |
| 161 | + # print(f"thread with id:{thread.id}",flush=True) |
| 162 | + # print(f"agent id:{agent.id}",flush=True) |
| 163 | + # print(f"project clinet :{client}",flush=True) |
| 164 | + |
| 165 | + # run = client.agents.runs.create_and_process( |
| 166 | + # thread_id=thread.id, |
| 167 | + # agent_id=agent.id |
| 168 | + # ) |
| 169 | + |
| 170 | + # if run.status == "failed": |
| 171 | + # print(f"[Chart Agent] Run failed: {run.last_error}") |
| 172 | + # return {"error": "Chart could not be generated due to agent failure."} |
| 173 | + |
| 174 | + # chart_json = "" |
| 175 | + # messages = client.agents.messages.list(thread_id=thread.id, order=ListSortOrder.ASCENDING) |
| 176 | + # for msg in messages: |
| 177 | + # if msg.role == MessageRole.AGENT and msg.text_messages: |
| 178 | + # chart_json = msg.text_messages[-1].text.value.strip() |
| 179 | + # break |
| 180 | + |
| 181 | + # chart_json = chart_json.replace("```json", "").replace("```", "").strip() |
| 182 | + # client.agents.threads.delete(thread_id=thread.id) |
| 183 | + |
| 184 | + # chart_data = json.loads(chart_json) |
| 185 | + # except Exception as e: |
| 186 | + # print(f"[Chart Agent Error]: {e}") |
| 187 | + # return chart_data |
| 188 | + |
| 189 | + # # Run the async agent call synchronously |
| 190 | + # loop = asyncio.get_event_loop() |
| 191 | + # chart_data = loop.run_until_complete(run_agent()) |
| 192 | + |
| 193 | + # if not chart_data or "error" in chart_data: |
| 194 | + # return {"error": "Chart could not be generated from this data. Please ask a different question."} |
| 195 | + |
| 196 | + # return chart_data |
| 197 | + |
| 198 | + # except Exception as e: |
| 199 | + # logger.error("Agent error in chart generation: %s", e) |
| 200 | + # return {"error": "Chart could not be generated from this data. Please ask a different question."} |
| 201 | + |
132 | 202 | async def stream_openai_text(self, conversation_id: str, query: str) -> StreamingResponse: |
133 | 203 | """ |
134 | 204 | Get a streaming text response from OpenAI. |
@@ -254,7 +324,7 @@ async def complete_chat_request(self, query, last_rag_response=None): |
254 | 324 | return {"error": "A previous RAG response is required to generate a chart."} |
255 | 325 |
|
256 | 326 | # Process RAG response to generate chart data |
257 | | - chart_data = self.process_rag_response(last_rag_response, query) |
| 327 | + chart_data = await self.process_rag_response(last_rag_response, query) |
258 | 328 |
|
259 | 329 | if not chart_data or "error" in chart_data: |
260 | 330 | return { |
|
0 commit comments