
    HVi&                       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 d dlm	Z	m
Z
mZ  ee      j                         j                  d   Zedz  Z ee      ej$                  vr"ej$                  j'                  d  ee             d dlmZmZ d dlmZmZmZ d d	lmZmZmZ g d
Z G d de      Z ddZ!dddZ"ddZ#dddZ$e%dk(  r e& e$             y)    )annotationsN)Path)IterableOptionalSequence   src)	DAGParser	PlanGraph)	LLMClient	LLMConfigLLMClientError)PlanContextPlanRequestPlannerService)CHECK_BATTERYNAVIGATE	SCAN_AREAVERIFY_OBJECTSPEAKWAITIDENTIFY_PERSONALERT_OPERATORc                  J     e Zd Z	 	 	 d	 	 	 	 	 	 	 d fdZddZd fdZ xZS )TemplatedLLMClientc                `    t         |   |       || _        | j                  |      | _        y )N)config)super__init__max_plan_depth_load_templatesystem_prompt_template)selfr   system_prompt_pathr    	__class__s       scripts/live_plan_demo.pyr   zTemplatedLLMClient.__init__#   s1     	',&*&9&9:L&M#    c                t    |xs t         dz  dz  dz  dz  }|j                         sy |j                  d      S )Nr	   plannerprompts
system.txtutf-8encoding)ROOTexists	read_text)r#   r$   	candidates      r&   r!   z!TemplatedLLMClient._load_template-   sC    &_4%<)+Ci+OR^+^	!""G"44r'   c                   | j                   }|st        | 	  |      S |rdj                  t	        |            ndj                  t
              }t        j                  dddddddd	d
iddddddgdddddddddgddiddddddgddidgdd      }|j                  dt        j                  | j                  d            j                  dt        | j                              j                  d |      j                  d!|      S )"Nz, z'Explore office zone and report hazards.DAGplan_example_001s1	EXECUTIONrobotr   	min_level   )step_idtype
agent_roleactionparamss2r   office_zonenormal)destinationspeed)r;   r<   r=   r>   dependenciesr?   s3
PERCEPTIONr   targethazardss4r   reasonhazard_report)intentworkflow_topologyplan_idsteps   indentz{{SCHEMA_JSON}}z{{MAX_PLAN_DEPTH}}z{{ROBOT_CAPABILITIES}}z{{FEW_SHOT_EXAMPLES}})r"   r   _build_system_promptjoinsortedDEFAULT_ACTIONSjsondumpsreplaceschemastrr    )r#   available_actionstemplatecapabilitiesfew_shotr%   s        r&   rT   z'TemplatedLLMClient._build_system_prompt3   sK   ..7/0ABB ! IIf./0?+ 	
 ::C%*- $( +&-"1#."3 $( +&-",)-2?("S $( ,&-"-)-#+Y"7 $( +&-"2)-#+_"=1 	%L O(
V .

4;;q0QRW)3t/B/B+CDW-|<W,h7		
r'   )NN   )r   zOptional[LLMConfig]r$   Optional[Path]r    intreturnNone)r$   rb   rd   zOptional[str])r]   zOptional[set]rd   r\   )__name__
__module____qualname__r   r!   rT   __classcell__)r%   s   @r&   r   r   "   sM     '+-1 	N#N +N 	N
 
N59
 9
r'   r   c                X   dg}| j                   D ]8  }|d   }|j                  dd      }| d| }|j                  d| d| d       : | j                   D ]>  }|d   }|j                  d	g       xs g }|s!|D ]  }|j                  d| d
|         @ dj                  |      dz   S )Nzgraph TDr;   r>    z | z  z["z"]rE   z --> 
)rP   getappendrU   )
plan_graphlinesstepr;   r>   labeldepsparents           r&   
to_mermaidru   o   s    LE   0y/(B')3vh'r'"UG2./	0    6y/xx+1r 	6FLL2fXU7)45	66 99Ud""r'   c                   t        j                  d      }|j                  ddd       |j                  dd	       |j                  d
d	       |j                  dt        d       |j                  dd	       |j                  dd	       |j                  ddt        d       |j                  ddd       |j                  ddd       |j                  dt        dd        |j                  d!d"d#$       |j                  d%d d&       |j                  d't        d        |j                  d(t
        d        |j                  d)t        d        |j                  d*d"d+$       |j                  d,d"d-$       |j                  d.t        t        d/z  d0z  d1z  d2z        d3       |j                  d4t        t        d5z  d6z        d7       |j                  |       S )8Nz@Run live orchestrator planner call and emit graph visualization.)descriptionz--intentz=Explore the office area, identify people, and report hazards.zUser instruction for planner.)defaulthelpz
--robot-idz	ghost-v60)rx   z
--locationoffice_entryz--battery-levelN   )r<   rx   z
--venue-idzonyx-labz--mission-typeexplorationz	--actions*z$Allowed actions for planner context.)nargsrx   ry   z
--endpointz.https://modelapi.klass.dev/v1/chat/completionszModel API endpoint.z--modelzQwen3-Next-80B-A3B-FP8zModel id for API request.z--timeout-sr:   zLLM API timeout in seconds.)r<   rx   ry   z--no-response-format
store_truez8Do not send response_format=json_object in chat payload.)r>   ry   z--accept-languagez.Optional Accept-Language header, e.g. en-US,enz--max-tokensz--top-pz--top-kz--use-openai-sdkz<Use openai-python client against OpenAI-compatible endpoint.z--streamz<Enable streaming mode (chunks are accumulated before parse).z--system-promptr	   r)   r*   r+   zSystem prompt template file.z	--out-dir	artifactsplanner_demoz%Directory for JSON + Mermaid outputs.)	argparseArgumentParseradd_argumentrc   rW   floatr\   r/   
parse_args)argvparsers     r&   r   r      s\   $$VF O,  
 k:
n=
)R@
j9
(-@
3	   @"  
 ((  
 *	   G  
 =  
   
   
   
 K  
 K  
 D5L9,y8<GH+  
 D;&784  
 T""r'   c                    t               }g }| D ];  }|j                         }|r||v r|j                  |       |j                  |       = |S N)setstripaddrn   )actionsseenoutputitemvalues        r&   unique_actionsr      sR    5DF 

e Mr'   c                   t        |       }t        |j                        }t        |j                  |j
                  |j                  |j                   |j                  |j                  |j                  |j                  |j                  |j                  
      }t        |t        |j                         d      }t#        |      }t%        |j&                  |j(                  |j*                  ||j,                  |j.                        }t1        |j2                  |dt5        t7        j6                                      }t9        d|j                          t9        d	|j
                          t9        d
|j2                          	 |j;                  |      }t9        t?        j@                  |jB                  |jD                  |jF                  |jH                  |jJ                  |jL                  dd             |j:                  st9        d       ytO               }
|
jQ                  |j:                  |j2                        }|jR                  r|jT                  slt9        d       |jV                  rTt9        |jV                  jX                         |jV                  jZ                  rt9        |jV                  jZ                         yt        |j\                        }|j_                  dd       t7        j`                  d      }|d| dz  }|d| dz  }|jc                  t?        j@                  |j:                  d      d       |jc                  te        |jT                        d       t9        d|        t9        d|        t9        d       t9        |jg                  d             y# t<        $ r}	t9        d|	        Y d }	~	yd }	~	ww xY w) N)
endpointmodel	timeout_sinclude_response_formataccept_language
max_tokenstop_ptop_kuse_openai_sdkstreamra   )r   r$   r    )
llm_client)robot_idcurrent_locationbattery_levelr]   venue_idmission_typez
live-demo-)rM   context
request_idz[planner] endpoint=z[planner] model=z[planner] intent=z[error] LLM request failed: rQ   )successis_safe_noopattemptsfailure_reasontrace_idtotal_latency_msrR   z.[error] Planner did not return a plan payload.   )expected_intentz*[error] Returned plan could not be parsed.   T)parentsexist_okz%Y%m%d-%H%M%Szplan-z.jsonz.mmdr,   r-   z[ok] plan json: z[ok] graph mermaid: z
--- Mermaid Preview ---r   )4r   r   r   r   r   r   r   no_response_formatr   r   r   r   r   r   r   r   system_promptr   r   r   locationr   r   r   r   rM   rc   timeprintplanr   rX   rY   r   r   r   r   r   r   r
   parseokro   errormessagedetailsout_dirmkdirstrftime
write_textru   r1   )r   argsr   
llm_configr   servicer   requestresultexcr   parsedr   stamp	json_pathmermaid_paths                   r&   mainr      s#   dDT\\*Gjj..$($;$; ;,,??jjjj**{{J $ 2 23J
 
3G((!&&G {{DIIK 012G 

/0	TZZL
)*	dkk]
+,g&
 


!>> & 3 3"OO"("7"7"OO$*$;$; 
	
 ;;>?[F\\&++t{{\CF99F--:;<<&,,&&'||##fll**+4<< GMM$M.MM/*EE%..IuUG400LFKK:WMJv'8'89GL	YK
()	 
/0	
%&	,
 
 '
 
23]  ,SE23s   
N5 5	O>OO__main__)ro   r   rd   r\   r   )r   Optional[Sequence[str]]rd   zargparse.Namespace)r   zIterable[str]rd   z	list[str])r   r   rd   rc   )'
__future__r   r   rX   sysr   pathlibr   typingr   r   r   __file__resolver   r/   SRCr\   pathinsertplanner.dag_parserr
   r   planner.llm_clientr   r   r   planner.plannerr   r   r   rW   r   ru   r   r   r   rf   
SystemExit r'   r&   <module>r      s    "   
   / / H~''*
Uls8388HHOOAs3x  3 C C D D	J
 J
Z#$Q#h	Yx z
TV
 r'   