o
    i6                  
   @  s  d dl mZ d dl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
 d dlmZ d dlmZ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 d
dlm Z m!Z! d
dl"m#Z#m$Z$ d
dl%m&Z& z\d dl'Z'd dl(Z(d dl)m*Z* d dl+m,Z,m-Z- d dl.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z5m6Z6m7Z7 d dl8m9Z9 d dl:m;Z;m<Z<m=Z= d dl>m?Z? d dl@mAZA d dlBmCZC d dlDmEZE W n eFy ZG zeFdeGdZG[Gww dZHeI d  ZJ	 d!ZKG d"d# d#e;ZLG d$d% d%e<ZMe=jNjOeLeMd& e ZPePjQdRd)d*ZRdSdTd-d.ZS	dUd+d/d0dVd5d6ZT			dWdXdDdEZU		dYdZdIdJZVG dKdL dLe,ZWd[dPdQZXdS )\    )annotationsN)CancelledError)Sequence)	ExitStack)datetimetimezone)Path)Anycast)get_literal_values   )__version__)
AgentDepsT)AbstractAgentAgent)	UserError)ModelMessageModelResponse)KnownModelNameinfer_model)OutputDataT)PromptSession)AutoSuggestFromHistory
Suggestion)Buffer)Document)FileHistory)ConsoleConsoleOptionsRenderResult)Live)	CodeBlockHeadingMarkdown)Status)Style)Syntax)Textu   Please install `rich`, `prompt-toolkit`, `pyperclip` and `argcomplete` to use the Pydantic AI CLI, you can use the `cli` optional group — `pip install "pydantic-ai-slim[cli]"`)clicli_exitz.pydantic-aizprompt-history.txtc                   @     e Zd ZdZddd	Zd
S )SimpleCodeBlockzCustomized code blocks in markdown.

    This avoids a background color which messes up copy-pasting and sets the language name as dim prefix and suffix.
    consoler   optionsr   returnr   c                 c  sR    t | j }t| jddV  t|| j| jdddV  td| j ddV  d S )NdimstyledefaultT)themebackground_color	word_wrap/)strtextrstripr'   
lexer_namer&   r3   )selfr,   r-   code r=   V/var/www/html/karishye-ai-python/venv/lib/python3.10/site-packages/pydantic_ai/_cli.py__rich_console__A   s
   z SimpleCodeBlock.__rich_console__Nr,   r   r-   r   r.   r   __name__
__module____qualname____doc__r?   r=   r=   r=   r>   r+   ;   s    r+   c                   @  r*   )LeftHeadingzTCustomized headings in markdown to stop centering and prepend markdown style hashes.r,   r   r-   r   r.   r   c                 c  s:    t dt| jdd    d| jj tdddV  d S )N#r    T)boldr0   )r'   inttagr8   plainr%   )r;   r,   r-   r=   r=   r>   r?   K   s   8zLeftHeading.__rich_console__Nr@   rA   r=   r=   r=   r>   rF   H   s    rF   )fenceheading_openr.   r7   c                  C  sF   t tj} |  j}|r|| nd}dt   d| dtj dS )N zHelp the user by responding to their request, the output should be concise and always written in markdown.
The current date and time is rH   z.
The user is running .)	r   nowr   utc
astimezonetzinfotznamesysplatform)now_utcrT   rU   r=   r=   r>   cli_system_promptY   s   
rY   pai	prog_namec                 C  s   t t| d dS )zRun the CLI and exit.r[   N)rV   exitr(   r\   r=   r=   r>   r)   d   s   r)   zopenai:gpt-5)r[   default_model	args_listSequence[str] | Noner^   rJ   c             
   C  sp  t j|dt dt jd}|jdddd |jdd	dd
| dd}dd ttjD }t	||_
|jdddd |jddddd |jdddddd |jdddd |jdddd t| || }t }d | d!t d"}|jr|j|d#d$ d%S |jr|| d& |D ]}	|jd'|	 d#d$ qd%S t}
|jrtjt  z
|jd(\}}W n ty   |d) Y d*S w t|}t||}
t|
ts|d+|j d, d*S |jd-u}|
jd-u s|rz
t |jp||
_W n! t!y } z|d.|j d/| d0 W Y d-}~d*S d-}~ww t|
jt"r |
jn
|
jj# d(|
jj$ }|jrD|rD|j| d1|j d2| d3d#d$ n |jrW|j| d1|j d3d#d$ n|j| d4| d3d#d$ |j% }|j&d5krqd6}n|j&dkrzd7}n|j&}t't"|j( }rzt)*t+|
|||| W d%S  t,y   Y d%S w zt)*t-||
|||W S  t,y   Y d%S w )8z5Run the CLI and return the exit code for the process.zPydantic AI CLI vz



Special prompts:
* `/exit` - exit the interactive mode (ctrl-c and ctrl-d also work)
* `/markdown` - show the last markdown output of the last question
* `/multiline` - toggle multiline mode
* `/cp` - copy the last response to clipboard
)progdescriptionformatter_classprompt?z0AI Prompt, if omitted fall into interactive mode)nargshelpz-mz--modelzpModel to use, in format "<provider>:<model>" e.g. "openai:gpt-5" or "anthropic:claude-sonnet-4-5". Defaults to "z".c                 S  s   g | ]}d |v r|qS ):r=   ).0nr=   r=   r>   
<listcomp>   s    zcli.<locals>.<listcomp>z-az--agentzTCustom Agent to use, in format "module:variable", e.g. "mymodule.submodule:my_agent")rg   z-lz--list-models
store_truez"List all available models and exit)actionrg   z-tz--code-themezWhich colors to use for code, can be "dark", "light" or any theme from pygments.org/styles/. Defaults to "dark" which works well on dark terminals.dark)rf   rg   r2   z--no-streamz Disable streaming from the modelz	--versionzShow version and exitz[green]z - Pydantic AI CLI vz[/green]F)	highlightr   z"

[green]Available models:[/green]z  rh   zE[red]Error: Agent must be specified in "module:variable" format[/red]r   z[red]Error: z is not an Agent instance[/red]NzError initializing [magenta]z[/magenta]:
[red]z[/red]z using custom agent [magenta]z[/magenta] with [magenta]z
[/magenta]z with [magenta]lightr2   monokai).argparseArgumentParserr   RawTextHelpFormatteradd_argumentr   r   	__value__argcompleteChoicesCompleter	completerautocomplete
parse_argsr   versionprintlist_models	cli_agentagentrV   pathappendosgetcwdsplit
ValueError	importlibimport_modulegetattr
isinstancer   modelr   r   r7   system
model_name	no_stream
code_themer
   rd   asynciorun	ask_agentKeyboardInterruptrun_chat)r_   r[   r^   parserargqualified_model_namesargsr,   name_versionr   r   module_pathvariable_namemodulemodel_arg_seter   streamr   rd   r=   r=   r>   r(   i   s   	







*r(   r   boolr   &AbstractAgent[AgentDepsT, OutputDataT]r,   r   r   
config_dirPath | Nonedepsr   message_historySequence[ModelMessage] | Nonec              
     s  |pt t }|jjddd |jdd ttt|d}	d}
|r&t|ng }	 zt	g d}|	j
| d||
dI d H }W n ttfyK   Y d	S w | sQq(|  d
d}|drqt|||
||\}}
|d urp|S nNzt||| ||||I d H }W n> ty   |d Y n1 ty } z%t|dd }|dt|j d|  |r|d| d W Y d }~nd }~ww q))NT)parentsexist_ok)r   )historyF)	/markdown
/multiline/exit/cpu    ➤ )auto_suggest	multiliner   rH   -r6   z[dim]Interrupted[/dim]	__cause__z
[red]z:[/red] z[dim]Caused by: z[/dim])PYDANTIC_AI_HOMEPROMPT_HISTORY_FILENAMEparentmkdirtouchr   r   r7   listCustomAutoSuggestprompt_asyncr   EOFErrorstriplowerreplace
startswithhandle_slash_commandr   r   r}   	Exceptionr   typerB   )r   r   r,   r   r[   r   r   r   prompt_history_pathsessionr   messagesr   r8   ident_prompt
exit_valuer   causer=   r=   r>   r      sD   
 
r   rd   r   list[ModelMessage]c                   s  t d|d}|s8| | j|||dI d H }W d    n1 s!w   Y  t|j}	|t|	|d | S | t }
| j|||d4 I d H d}t	dd|dd}|2 zM3 d H W }t
|r||j4 I d H -}|  |
| |jd d	2 z3 d H W }	|tt|	|d q{6 W d   I d H  n1 I d H sw   Y  qV6 W d   I d H  n1 I d H sw   Y  |jd usJ |j W  d    W  d    S 1 sw   Y  W d    d S 1 sw   Y  d S )
Nu   [dim]Working on it…[/dim])r,   )r   r   )r   rO      ellipsis)refresh_per_secondr,   vertical_overflow)debounce_by)r$   r   r7   outputr}   r#   all_messagesr   iterr    r   is_model_request_noder   ctxstopenter_contextstream_outputupdateresult)r   rd   r   r,   r   r   r   statusr   contentstack	agent_runlivenodehandle_streamr=   r=   r>   r     s6   	


((Rr   c                      s.   e Zd Zdd fddZd fddZ  ZS )r   Nspecial_suggestionslist[str] | Nonec                   s   t    |pg | _d S N)super__init__r   )r;   r   	__class__r=   r>   r   /  s   
zCustomAutoSuggest.__init__bufferr   documentr   r.   Suggestion | Nonec                   sJ   t  ||}|j }| jD ]}||r"t|t|d    S q|S r   )r   get_suggestiontext_before_cursorr   r   r   r   len)r;   r   r   
suggestionr8   specialr   r=   r>   r   3  s   


z CustomAutoSuggest.get_suggestionr   )r   r   )r   r   r   r   r.   r   )rB   rC   rD   r   r   __classcell__r=   r=   r   r>   r   .  s    r   r   r   tuple[int | None, bool]c              
   C  sX  | dkr=z|d j }W n ty   |d Y d |fS w |d |D ]}|jdkr8|t|jd|ddd	 q$d |fS | d
krX| }|rO|d d |fS |d d |fS | dkre|d d|fS | dkr|rrt|d ts{|d d |fS |d j}|r|	  }rt
| |d d |fS |d d |fS |d|  d d |fS )Nr   z([dim]No markdown output available.[/dim]z-[dim]Markdown output of last question:[/dim]
r8   markdownTr2   )lexerr3   r5   r4   r   zdEnabling multiline mode. [dim]Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.[/dim]zDisabling multiline mode.r   u   [dim]Exiting…[/dim]r   r   z'[dim]No output available to copy.[/dim]z+[dim]Copied last output to clipboard.[/dim]z#[dim]No text content to copy.[/dim]z%[red]Unknown command[/red] [magenta]`z`[/magenta])parts
IndexErrorr}   	part_kindr&   r   r   r   r8   r   	pyperclipcopy)r   r   r   r,   r   r   parttext_to_copyr=   r=   r>   r   ?  s\   '

"







r   )r.   r7   )rZ   )r[   r7   r   )r_   r`   r[   r7   r^   r7   r.   rJ   )NNN)r   r   r   r   r,   r   r   r7   r[   r7   r   r   r   r   r   r   r.   rJ   )NN)r   r   rd   r7   r   r   r,   r   r   r7   r   r   r   r   r.   r   )r   r7   r   r   r   r   r,   r   r   r7   r.   r   )Y
__future__r   _annotationsrr   r   r   r   rV   r   collections.abcr   
contextlibr   r   r   pathlibr   typingr	   r
   typing_inspection.introspectionr   rO   r   _run_contextr   r   r   r   
exceptionsr   r   r   r   modelsr   r   r   r   rw   r   prompt_toolkitr   prompt_toolkit.auto_suggestr   r   prompt_toolkit.bufferr   prompt_toolkit.documentr   prompt_toolkit.historyr   rich.consoler   r   r   	rich.liver    rich.markdownr!   r"   r#   rich.statusr$   
rich.styler%   rich.syntaxr&   	rich.textr'   ImportError_import_error__all__homer   r   r+   rF   elementsr   r   system_promptrY   r)   r(   r   r   r   r   r=   r=   r=   r>   <module>   s    
|3"