
    'jen                       d Z ddlmZ ddlZddlZddlZddlZddlmZm	Z	 ddl
mZ ddlmZ ddlZddlZ ej        dej        ej        z            Z ej        dej                  ZdDdZddlmZ ddlmZ ddlmZ ddlmZ ddl m!Z!m"Z" ddl#m$Z$ ddl%m&Z& ddl'm(Z( ddl)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/ ddl0m1Z1m2Z2 ddl3m4Z4 e(d         Z5e G d d                      Z6 e&e6ej7        d          e4            ddd !          Z8e8j9        dEd'            Z:e8j9        dFd(            Z;e8j9        dGd*            Z<e8j9        dGd+            Z=e8j9        g fdHd0            Z>e8j9        dId3            Z?dJd6Z@dKd:ZAdLd<ZB e$e8e5jC        e5jD        =          ZEeEF                    ed>gd>gd>g?           eEG                    d@eAdAgB           eEG                    dCeBdAgB           dS )MuY  UI Agent — visualisation renderer for Enterprise Brain.

Receives raw query rows and a plain-text explanation from a data agent (e.g.
Tatasteel) and turns them into a frontend-ready widget stream.

Endpoints:
    POST /query         — sync: returns widget list JSON
    POST /query/stream  — SSE: streams text tokens then emits the widget
    )annotationsN)	dataclassfield)Path)Anyz```mermaid\s*\n(.*?)\n```z	<br\s*/?>textstrreturntuple[str, list[str]]c                    g dfd}t                               ||           }t                              d|                                          }|fS )a  Strip <br> tags and extract mermaid code blocks from *text*.

    Returns:
        (cleaned_text, list_of_mermaid_diagrams)

    Each extracted diagram is emitted as a ``{"type": "mermaid"}`` widget so
    the frontend can render it natively instead of parsing raw markdown.
    mre.Matchr
   r	   c                |                         |                     d                                                     dS )N    )appendgroupstrip)r   diagramss    D/var/www/html/ai-enterprise-brain/backend/chanakya/ui_agent/agent.py_pullz!_split_explanation.<locals>._pull(   s0    

((**+++r    r   )r   r   r
   r	   )_MERMAID_REsub
_BR_TAG_REr   )r   r   cleanedr   s      @r   _split_explanationr      sg     H      ooeT**GnnR))//11GHr   )logger)
RunContext)CORSMiddleware)Request)JSONResponseStreamingResponse)make_metadata_aware_app)EnterpriseAgent)AGENT_REGISTRY)deserialize_historyload_conversation_history)VALID_CHART_KEYSvalidate_chart_contentvalidate_highlight_content)AgentQueryResponseUIRenderRequest)make_ui_agent_instructionsui_agentc                  &   e Zd ZU dZ ee          Zded<   dZded<   dZ	ded<   dZ
ded	<    ee          Zd
ed<    ee          Zded<   dZded<    ee          Zded<    ed          Zded<    ed          Zded<   dZded<   dS )UIAgentDepsz%Per-request context for the UI agent.)default_factoryzlist[dict[str, Any]]rowsr   r	   questionexplanationmarket_context	list[str]storyline_hintsdecision_support_contextdc_explanationwidgetsN)defaultz
int | Nonepending_visualization_slotzasyncio.Queue | Noneprogress_queueGBPcurrency_code)__name__
__module____qualname____doc__r   listr3   __annotations__r4   r5   r6   r8   r9   r:   r;   r=   r>   r@    r   r   r1   r1   H   s'        //!&t!<!<!<D<<<<HKN!&t!<!<!<O<<<<5:U45P5P5PPPPPN %*E$$?$?$?G???? .3U4-@-@-@@@@@+05+>+>+>N>>>>Mr   r1   LITELLM_PROVIDER_BASE_URLzchanakya-alphazui-agent   )	deps_typeapi_baseinstructionslogfire_envservice_nameretriesctxRunContext[UIAgentDeps]
chart_typecontentdict[str, Any]c                  K   |                                                                 }|t          vrd}| j        j        }||                    d|d           d{V  |s<| j        j                            d|ddd           t          j	        d	|           d
S t          |                    d          t                    r^t          |                                          ddhk    r7|d         }d|                    d|          i|}t          j        d|           |                    d          |k    rKt          j        d|                    d          |           d|id |                                D             }| j        j        H| j        j                            ddd           t%          | j        j                  dz
  | j        _        | j        j        }	 t'          |          }|                                }n# t*          $ r}d| dcY d}~S d}~ww xY wd|d| j        j        |<   d| j        _        t          j	        d||t%          | j        j                             dS )uq  Store a frontend-ready visualisation widget.

    The agent is responsible for constructing ``content`` according to the
    exact ``BaseVisualizationConfig`` schema for the chosen ``chart_type``
    (schemas are listed in the system prompt).  This tool simply validates the
    type key and records the widget so the HTTP handler can return it.

    Args:
        chart_type: One of the supported chart keys (e.g. ``contract-bars``,
                    ``status-arc``, ``variation-split``, …).  Used only for
                    the ``widget_loading`` progress event; the ``"type"`` field
                    inside ``content`` is the authoritative discriminant.
        content:    Fully-formed ``BaseVisualizationConfig`` dict — constructed
                    by the agent by mapping SQL row columns to the schema fields
                    shown in the system prompt.
    z multi-metric-constellation-chartNwidget_loading)typewidget_typevisualizationT)rW   _emptyrW   rS   z0build_visualization empty content, chart_type={}zNo data to visualise.rS   rW   zFbuild_visualization: unwrapped double-nested content for chart_type={}zFbuild_visualization: content missing/wrong type ({!r}), injecting {!r}c                &    i | ]\  }}|d k    ||S )rW   rG   ).0kvs      r   
<dictcomp>z'build_visualization.<locals>.<dictcomp>   s#    !R!R!R41aa6kk!Qkkkr   )rW   _pendingr   Schema validation failed: u   
Only the fields listed above are wrong — keep all other fields exactly as they were. Fix only the failing fields and call build_visualization again with the corrected content.z:build_visualization chart_type={} slot={} total_widgets={}zWidget built.)r   lowerr)   depsr>   putr;   r   _logdebug
isinstancegetdictsetkeyswarningitemsr=   lenr*   
model_dump	Exception)	rP   rR   rS   ctqinnerslot	validatedexcs	            r   build_visualizationrx   n   s     , 
					!	!	#	#B	!!!/A}ee-bAABBBBBBBBB ' 	# "d33!
 !
 	 	 	 	
ErJJJ&& 	7;;y))400cFI#666	"7;;vr22<e<]_abbb
 {{6b  TKK	
 	
 	

 2S!R!R7==??!R!R!RS x*2d K KLLL.1#(2B.C.Ca.G+8.D	
*733	&&(( 
 
 
i i i i	
 	
 	
 	
 	
 	

 '6'JJCHT*.CH'JKRQUWZ[^[c[kWlWlmmm?s   )#H 
H'H"H'"H'c                   K   |r|                                 sdS | j        j                            d|                                 d           t	          j        dt          | j        j                             dS )uE  Insert a narrative text block at this exact position in the widget sequence.

    Call this instead of writing natural response text so that narrative appears
    interleaved with visualisations and highlights — not forced to the top.

    Args:
        content: Plain-English narrative for this position in the story.
    u   Empty text — skipped.r   r[   zbuild_text total_widgets={}zText block added.)r   rd   r;   r   rf   rg   ro   )rP   rS   s     r   
build_textrz      st        )'--// )((HVHHIIIJ,c#(2B.C.CDDDr   blockc                  K   |rt          |t                    st          j        d           dS |                    d          dk    r-t          j        d|                    d                     d|d<   |                    d          pg }|st          j        d           dS |d	d
         |d<   	 t          |          }|                                }n# t          $ r}d| dcY d	}~S d	}~ww xY w| j        j	        
                    d|d           t          j        dt          | j        j	                             dS )u  Insert a primary highlights widget surfacing key numbers.

        Use when key numbers need to be prominently visible. Can be called
        at any position — not required to be first.

    Args:
        block: A stats block, e.g.
               ``{"type": "stats", "items": [{"value": "93", "label": "Total NCEs"},
               {"value": "£35.5M", "label": "CE Exposure"}]}``.
    z;build_primary_highlights: empty or non-dict block, ignoringz No primary highlights to render.rW   statsz<build_primary_highlights: block type must be 'stats', got {}rn   z2build_primary_highlights: stats block has no itemsu2   Primary highlights block has no items — skipped.N   rb   u   
Only the fields listed above are wrong — keep all other fields exactly as they were. Fix only the failing fields and call build_primary_highlights again.primary_highlightsr[   z)build_primary_highlights total_widgets={}zPrimary highlights built.)rh   rj   rf   rm   ri   r+   rp   rq   rd   r;   r   rg   ro   )rP   r{   rn   rv   rw   s        r   build_primary_highlightsr      s       2
5$// 2RSSS11yyG##SUZU^U^_eUfUfgggfIIg$"E DIJJJCC 2A2YE'N
.u55	$$&& 
 
 
S S S S	
 	
 	
 	
 	
 	

 H%9eLLMMMJ:C@P<Q<QRRR&&s   3#C 
C1!C,&C1,C1c                  K   |rt          |t                    st          j        d           dS d|vrt          j        d           dS 	 t	          |          }|                                }n# t          $ r}d| dcY d}~S d}~ww xY w| j        j        	                    d	|d
           t          j
        d|                    d          t          | j        j                             dS )ur  Store a key-highlights block at this position in the widget sequence.

Can be called multiple times. The ``block`` must match one of the
``KeyHighlightBlock`` shapes in the system prompt — always include
``"type"`` as the first field.

    Args:
        block: A fully-formed ``KeyHighlightBlock`` dict, e.g.
               ``{"type": "ranked", "items": [...]}``.
    z7build_key_highlights: empty or non-dict block, ignoringzNo key highlights to render.rW   z:build_key_highlights: missing 'type' discriminant in blocku6   Key highlights block missing 'type' field — skipped.rb   u   
Only the fields listed above are wrong — keep all other fields exactly as they were. Fix only the failing fields and call build_key_highlights again.Nkey_highlightsr[   z-build_key_highlights type={} total_widgets={}zKey highlights built.)rh   rj   rf   rm   r+   rp   rq   rd   r;   r   rg   ri   ro   )rP   r{   rv   rw   s       r   build_key_highlightsr     s1       .
5$// .NOOO--UQRRRGG
.u55	$$&& 
 
 
O O O O	
 	
 	
 	
 	
 	

 H%5%HHIIIJ>		&@Q@QSVWZW_WgShShiii""s   #A/ /
B	9B>B	B	columnsr7   column_keyscurrency_keysc                  K   st          j        d           dS st          j        d           dS t                    t                    k    rSt          j        dt                    t                               dt                     dt                     dS | j        j        }|st          j        d	           d
S t          |d                                                   fdD             }|s;}t          j        d|t                               d| dt                     dS fdD             }|rt          j        d|           d'dfd|D             }t          |          fdt                    D             }	| j        j
        D ]}
|
                    d          dk    rq|
                    di                               d          k    rD|
                    di                               d          |k    rt          j        d            d S | j        j
                            dd||	d!d"           t          j        d#t                    t          |          t          | j        j
                             d$t                     d%t          |           d&S )(u  Render a data table using ALL rows from the query result.

    Call this when the user explicitly asks for a table, or when the data is
    record-level detail that no chart encodes better (e.g. a list of specific
    items, a multi-column detail view, raw lookup results).

    **Do NOT pass rows yourself.** This tool maps every row from the query
    result automatically using ``column_keys``.  You only declare which columns
    to show and which SQL key each column maps to.

    Args:
        columns:       Ordered list of human-readable column header strings.
                       Write what a business reader would see — never raw SQL
                       column names.
                       e.g. ``["Contractor", "Cost Impact (£)", "Status"]``.
        column_keys:   Ordered list of SQL column names from the raw query result,
                       corresponding 1-to-1 with ``columns``.
                       e.g. ``["contractor", "change_to_prices", "status"]``.
                       Must have the same length as ``columns``.
        currency_keys: Subset of ``column_keys`` whose values are monetary amounts
                       (GBP or converted currency).  The frontend uses this list to
                       apply compact currency formatting (1K / 1M) to those columns.
                       e.g. ``["change_to_prices", "base_contract"]``.
                       Omit or pass ``[]`` for columns that are counts, days, or text.
    z)build_table: empty columns list, skippingu&   Table skipped — no columns provided.z-build_table: empty column_keys list, skippingu*   Table skipped — no column_keys provided.z;build_table: columns/column_keys length mismatch ({} vs {})u   Table skipped — columns (z) and column_keys (z) must have the same length.z&build_table: no rows in deps, skippingu*   Table skipped — no query data available.r   c                    g | ]}|v |	S rG   rG   r]   r^   available_keyss     r   
<listcomp>zbuild_table.<locals>.<listcomp>b  s#    >>>a!~*=*=*=*=*=r   uQ   build_table: no column_keys match primary rows — keys={} available={}, skippingu4   Table skipped — none of the requested column_keys z7 exist in the primary query result. Available columns: z1. Use only columns from the primary rows dataset.c                    g | ]}|v|	S rG   rG   r   s     r   r   zbuild_table.<locals>.<listcomp>n  s#    CCCq1N+B+B+B+B+Br   u@   build_table: some column_keys not in primary rows — missing={}valr   r
   r	   c                (    | dS t          |           S )Nu   —)r	   )r   s    r   _fmtzbuild_table.<locals>._fmtr  s    ;53xxr   c                L    g | ]fd t                    D              S )c                T    i | ]$\  }}|                      |                    %S rG   ri   )r]   colkeyr   rows      r   r`   z*build_table.<locals>.<listcomp>.<dictcomp>x  s3    KKKXS#dd3773<<  KKKr   )zip)r]   r   r   r   r   s    @r   r   zbuild_table.<locals>.<listcomp>w  sL        	LKKKKWk1J1JKKK  r   c                "    g | ]\  }}|v 	|S rG   rG   )r]   r   r   currency_key_sets      r   r   zbuild_table.<locals>.<listcomp>~  s/       S@P9P9P9P9P9Pr   rW   tablerS   r   r3   z/build_table: duplicate table detected, skippingu*   Table already built — duplicate skipped.)rW   r   r3   currency_columnsr[   z,build_table cols={} rows={} total_widgets={}u   Table built — z
 columns, z rows.)r   r   r
   r	   )rf   rm   ro   rd   r3   rk   rl   rE   sortedr   r;   ri   r   rg   )rP   r   r   r   raw_rowsmatchingmissing	unmatchedmapped_rowsr   existingr   r   r   s    ``        @@@r   build_tabler   *  s     @  8@AAA77 <DEEE;;
7||s;''''ILL#k**	
 	
 	

?#g,, ? ?K  ? ? ?	

 x}H <=>>>;;!))++,,N>>>>;>>>H 

_T.))	
 	
 	

>7 > >8>~8N8N> > >	

 DCCCKCCCI dWYbccc   
       K =))   55  
 H$ @ @LL  G++Y++//	::gEEY++//77;FFLJKKK???H 0	
 
     	J6Gc+&&CH,<(=(=   Oc'llNNc+6F6FNNNNr   column	operationc                  K   | j         j        sdS t          j        | j         j                  }||j        vrd| dt          |j                   S t          j        ||         d                                          }|j        rd| dS 	 |	                    |          }n # t          $ r}d| d| d	cY d
}~S d
}~ww xY w| d| d| S )um  Compute an exact aggregate over a numeric column in the row data.

    ALWAYS call this tool instead of computing totals, averages, counts,
    medians, or any other arithmetic mentally from the raw rows.

    Supported operations: sum, mean, median, min, max, count, std, var.
    For grouped aggregates (e.g. sum per category), call this once per group
    filtering is not needed — pandas handles mixed types gracefully.

    Args:
        column:    Column name from the row data to aggregate.
        operation: Aggregation function — one of: sum, mean, median, min,
                   max, count, std, var.
    zNo row data available.zColumn 'z ' not found. Available columns: coerce)errorsz' has no numeric values.zOperation 'z
' failed: z:. Supported: sum, mean, median, min, max, count, std, var.N(z) = )rd   r3   pd	DataFramer   rE   
to_numericdropnaemptyaggrq   )rP   r   r   dfseriesresultrw   s          r   compute_aggregater     s     ( 8= (''	chm	$	$BRZT&TT$rzBRBRTTT]2f:h777>>@@F| ;:&::::rI&& r r rqYqq#qqqqqqqqqr ..&..f...s   B$ $
C.B<6C<Creq'UIRenderRequest'c                   d| j          d| j         d| j         g}| j        r|                    d| j        z              | j        r/|                    dt          j        | j                  z              | j        r|                    d| j        z              | j	        r:|                    dd
                    d	 | j	        D                       z              | j        r|                    d
| j        z              | j        r|                    d| j        z              |                    dt          | j                   dt          j        | j                              d
                    |          S )z'Build the full prompt for the UI agent.z
Question: z
Currency: zData agent explanation: us   Market & Industry Context (sourced from live web search — weave benchmarks and comparisons into your narrative):
ziDecision Support Context (additional Tata Steel analysis datasets gathered after the main answer query):
u   Decision Context Mapping (for your background reasoning only — DO NOT emit a build_text widget for this content; it is automatically rendered in a separate hidden panel):
u   Action items (highest-priority items the user should act on — surface the top item as a build_primary_highlights block and list the rest via build_key_highlights):

c              3      K   | ]	}d | V  
dS )z- NrG   )r]   as     r   	<genexpr>z#_build_ui_prompt.<locals>.<genexpr>  s(      ==QQ======r   uy   Urgency signal (use this to write the build_text narrative — emphasise the deadline or financial risk described here):
z8Cost of inaction (weave into the build_text narrative):
zRows (z	 total): 

)r4   r@   r5   r6   r   r9   jsondumpsr:   what_to_act_onjoinurgencycost_of_inactionro   r3   )r   partss     r   _build_ui_promptr     s    	$S\##(S&((43?44E
  
G !	
 	
 	

 # 
xj5667	
 	
 	
  
6  !	
 	
 	
  
aii==#*<=====>	
 	
 	

 { 
3k	
 	
 	

  
G"#	
 	
 	
 
LLH#ch--HH$*SX2F2FHHIII;;ur   requestr!   r"   c           
       K   	 |                                   d{V }t          di |}nQ# t          $ rD}t          t	          j        d| d                                          d          cY d}~S d}~ww xY w|j        t          |j                  }nt          |j
                   d{V }t          |j        |j        |j        |j        pd|j        pg |j        pg |j        pd|j                  }t)          |          }	 t+          j        d	|j        dd
                   5  t.          j                            |||           d{V }ddd           n# 1 swxY w Y   nn# t          $ ra}t5          j        d|           t          t	          j        t9          |          d                                                    cY d}~S d}~ww xY wt;          |j                  \  }}	d |j        D             }
t?          d |
D                       }g }|s|r|                     d|d           |d |	D             z  }||
z  }|j        r|                     d|j        d           |j        r|                     d|j        d           t          t	          j!        |                                                    S )u1   POST /query — sync render: returns widget list.NInvalid request: PIPELINE_ERRORmessagecode  status_coder   )r3   r4   r5   r6   r8   r9   r:   r@   {q}x   rs   rd   message_historyzui_agent render error: {}c                <    g | ]}|                     d           |S ra   r   r]   ws     r   r   z#_render_handler.<locals>.<listcomp>"  s)    GGGAQUU:5F5FGaGGGr   c              3  H   K   | ]}|                     d           dk    V  dS rW   r   Nr   r   s     r   r   z"_render_handler.<locals>.<genexpr>#  s1      JJa!%%--61JJJJJJr   r   r[   c                    g | ]}d |dS mermaidr[   rG   r]   ds     r   r   z#_render_handler.<locals>.<listcomp>'  s     DDDaq11DDDr   followup_questionsfollowup_explanationr;   rG   )"r   r-   rq   r"   r,   failurerp   historyr'   r(   conversation_idr1   r3   r4   r5   r6   r8   r9   r:   r@   r   logfirespanr/   agentrunrf   errorr	   r   r;   anyr   success)r   bodyr   rw   r   rd   promptr   
clean_textr   filled_widgetshas_text_widgetr;   s                r   _render_handlerr     s     	
\\^^######%%%% 
 
 
&1C118H  jll	
 
 
 	
 	
 	
 	
 	
 	

 {-ck:: 9#:M N NNNNNNNXO)/R+1r!$!=!C)/R'	 	 	D c""F
\%3<#5666 	b 	b#>--f4Q`-aaaaaaaaF	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 	b 
 
 

.444&s3xx>NOOOZZ\\
 
 	
 	
 	
 	
 	
 	

 .co>>JGGGGGNJJ>JJJJJO$&G @z @:>>???DD8DDDDG~G
 W 4ATUUVVV
 X 63CUVVWWW*27CCCNNPPQQQs]   &+ 
A99A4.A94A9	#E- ,)E!E- !E%%E- (E%)E- -
G7AGGG StreamingResponse | JSONResponsec                  K   	 |                                   d{V }t          di |nQ# t          $ rD}t          t	          j        d| d                                          d          cY d}~S d}~ww xY wj        t          j                  nt          j
                   d{V t          j                    t          j        j        j        j        pdj        pg j        pg j        pdj        	  	        t-                    fd	}t/           |            d
ddd          S )u  POST /query/stream — SSE streaming render.

    SSE events (server → client, in order):
        data: {"type": "widget_loading", "widget_type": str}
        data: {"type": "text_chunk",     "content": str}
        data: {"type": "widget",         "widget": {...}}
        data: {"type": "done",           "success": true, "widgets": [...]}
        data: {"type": "error",          "message": str, "code": str}
    Nr   r   r   r   r   r   )	r3   r4   r5   r6   r8   r9   r:   r>   r@   c                  K   g t          j                    t          j                    dfd} fd}t          j         |                       }t          j         |                      }	                                  d {V }|ndt          j        |           dW V  9t          j        ||d           d {V  rd S d                              }t          |          \  }}d	 j
        D             }t          d
 |D                       }	g }
|	s|r|
                    d|d           |
d |D             z  }
|D ]5}dt          j        d|d           dW V  |
                    |           6j        r=dj        d}dt          j        d|d           dW V  |
                    |           j        r=dj        d}dt          j        d|d           dW V  |
                    |           dt          j        ddit          j        |
                                                     dW V  d S )NFc                   K                                    st	 t          j                                        d           d {V }                     |            d {V  n# t          j        $ r Y pw xY w                                 t                                sA                                                               d {V                                  A                    d            d {V  d S )Ng?)timeout)is_setasynciowait_forri   re   TimeoutErrorr   
get_nowait)event
agent_donemergedr>   s    r   _drain_progresszC_render_stream_handler.<locals>.sse_events.<locals>._drain_progress`  s:      '')) ")"2>3E3E3G3GQU"V"V"VVVVVVVE **U+++++++++++   H	 !''))  %**,, >jj!:!:!<!<========= %**,, >**T"""""""""""s   A	A# #A54A5c                   K   	 t          j        d
j        d d                   5  t          j                            	          4 d {V } |                     d          2 3 d {V }                    |                               d|d           d {V  ;6 	 d d d           d {V  n# 1 d {V swxY w Y   d d d            n# 1 swxY w Y   nZ# t          $ rM}t          j        d	|           d                    d
t          |          dd           d {V  Y d }~nd }~ww xY w                                 d S #                                  w xY w)Nr   r   r   r   T)delta
text_chunkr[   z ui_agent stream render error: {}r   r   )rW   r   r   )r   r   r4   r/   r   
run_streamstream_textr   re   rq   rf   r   r	   rk   )streamchunkrw   r   rd   	full_text	had_errorr   r   r   r   s      r   
_run_agentz>_render_stream_handler.<locals>.sse_events.<locals>._run_agentk  s     !\%3<+=>>> W W'~88d\k8ll W W W W W W Wpv+1+=+=D+=+I+I W W W W W W W%%,,U333"(**lu-U-U"V"VVVVVVVVV ,J+IW W W W W W W W W W W W W W W W W W W W W W W W W W WW W W W W W W W W W W W W W W
  c c c
=sCCC 	jj'c#hhP`!a!abbbbbbbbbbbbbbc
      
    s   #C  )CB7(B#.6B7%C7
C	CC	CC  CC  CC  E  
D7*AD2-E 2D77E E&Tzdata: r   )return_exceptionsr   c                <    g | ]}|                     d           |S r   r   r   s     r   r   z>_render_stream_handler.<locals>.sse_events.<locals>.<listcomp>  s)    KKKz9J9JK!KKKr   c              3  H   K   | ]}|                     d           dk    V  dS r   r   r   s     r   r   z=_render_stream_handler.<locals>.sse_events.<locals>.<genexpr>  s1      NN!aeeFmmv5NNNNNNr   r   r[   c                    g | ]}d |dS r   rG   r   s     r   r   z>_render_stream_handler.<locals>.sse_events.<locals>.<listcomp>  s     HHH!Y155HHHr   widget)rW   r  r   r   rW   doner   )r   QueueEventcreate_taskri   r   r   gatherr   r   r;   r   r   r8   r:   r,   r   rp   )r   r  
drain_task
agent_taskitem
agent_textr   r   r   r   r;   r   fqfer   r  r  r   rd   r   r>   r   r   s                 @@@@r   
sse_eventsz*_render_stream_handler.<locals>.sse_eventsZ  s:     !	 ']__
			# 		# 		# 		# 		# 		# 		#	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! 	! ():):;;
(66
	2%%%%%%D|14:d++1111111		2 nZtLLLLLLLLLL 	FWWY''
1*==
HKKT\KKKNN~NNNNN(* 	D: 	DNNFzBBCCCHHxHHHH 	 	AL4:x1&E&EFFLLLLLLLNN1  	.3;NOOBM4:x2&F&FGGMMMMMMMNN2  	0S=OPPBM4:x2&F&FGGMMMMMMMNN2utz66"n5G5OX_5`5`5`5k5k5m5m"noouuuuuuuuur   ztext/event-streamzno-cacheno)zCache-ControlzX-Accel-Buffering)
media_typeheadersrG   )r   r-   rq   r"   r,   r   rp   r   r'   r(   r   r   r  r1   r3   r4   r5   r6   r8   r9   r:   r@   r   r#   )	r   r   rw   r  rd   r   r>   r   r   s	       @@@@@r   _render_stream_handlerr  1  s     	
\\^^######%%%% 
 
 
&1C118H  jll	
 
 
 	
 	
 	
 	
 	
 	

 {-ck:: 9#:M N NNNNNNN$+MOONXO)/R+1r!$!=!C)/R%'
 
 
D c""FIv Iv Iv Iv Iv Iv Iv Iv IvV 
&",4HH   s   &0 
A>9A93A>9A>)namedescription*)allow_originsallow_methodsallow_headersz/queryPOST)methodsz/query/stream)r   r	   r
   r   )rP   rQ   rR   r	   rS   rT   r
   r	   )rP   rQ   rS   r	   r
   r	   )rP   rQ   r{   rT   r
   r	   )
rP   rQ   r   r7   r   r7   r   r7   r
   r	   )rP   rQ   r   r	   r   r	   r
   r	   )r   r   r
   r	   )r   r!   r
   r"   )r   r!   r
   r   )HrD   
__future__r   r   r   osredataclassesr   r   pathlibr   typingr   pandasr   r   compileDOTALL
IGNORECASEr   r   r   logurur   rf   pydantic_air   starlette.middleware.corsr    starlette.requestsr!   starlette.responsesr"   r#   backend.chanakya.a2a_contextr$   backend.chanakya.baser%   backend.chanakya.configr&   &backend.chanakya.conversation._historyr'   r(   )backend.chanakya.nl2sql_core.chart_configr)   r*   r+   backend.chanakya.schemasr,   r-    backend.chanakya.ui_agent.promptr.   _cfgr1   environr/   toolrx   rz   r   r   r   r   r   r   r  r  r  appadd_middleware	add_routerG   r   r   <module>rA     s-    # " " " " "   				 				 ( ( ( ( ( ( ( (                 
 bj5ry2=7PQQRZbm44
   & " ! ! ! ! ! " " " " " " 4 4 4 4 4 4 & & & & & & ? ? ? ? ? ? ? ? @ @ @ @ @ @ 1 1 1 1 1 1 2 2 2 2 2 2 a a a a a a a a         
 I H H H H H H H G G G G G Gj!        6 ?Z34++--    
S S S Sl 
   & 
)' )' )' )'X 
!# !# !# !#F 

  "	nO nO nO nO nOb 
$/ $/ $/ $/T+ + + +b6R 6R 6R 6Rrx x x x| 	      %%%	     h& : : : o5x H H H H Hr   