
    {hD                     ,   d dl Z d dlmZmZ d dlmZmZmZ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	 Zd
 Z ee      e_         ee      e_         G d de      Z G d de      Z G d de      Z d        Zedk(  rd dlm 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 Z d dl,Z,d dl-m.Z. d dl/Z/de0dee   de$fdZ1dede$fdZ2defd Z3d&d!e4fd"Z5 e        Z6e6jo                  d#        e,jp                   e5d$%             yy)'    N)	BaseModelField)OptionalType	GeneratorAsyncGeneratorget_args)ChatHistory)BaseDynamicContextProviderSystemPromptGeneratorBaseIOSchema)PartialBase)	from_jsonc              +      K   d}| j                         }|D ]?  }||z  }t        |xs dj                         d      } |j                  |fdd i|}| A y wN z{}ztrailing-strings)partial_modestrictget_partial_modelr   encodemodel_validateclsjson_chunkskwargspotential_objectpartial_modelchunkobjs          b/var/www/html/hubwallet-dev/venv/lib/python3.12/site-packages/atomic_agents/agents/atomic_agent.pymodel_from_chunks_patchedr#      sq     ))+M E!)1T99;J\]*m**3FtFvF		s   AAc                   K   d}| j                         }|2 3 d {   }||z  }t        |xs dj                         d      } |j                  |fdd i|}| H7 C6 y wr   r   r   s          r"   model_from_chunks_async_patchedr%      sy     ))+M"  eE!)1T99;J\]*m**3FtFvF		{s&   A#A!AA!A A#A!!A#c                   0    e Zd ZU dZ edd      Zeed<   y)BasicChatInputSchemaz?This schema represents the input from the user to the AI agent..z3The chat message sent by the user to the assistant.descriptionchat_messageN__name__
__module____qualname____doc__r   r*   str__annotations__     r"   r'   r'   '   s    IIL# r3   r'   c                   0    e Zd ZU dZ edd      Zeed<   y)BasicChatOutputSchemaz@This schema represents the response generated by the chat agent..zThe chat message exchanged between the user and the chat agent. This contains the markdown-enabled response generated by the chat agent.r(   r*   Nr+   r2   r3   r"   r5   r5   0   s    JWL# r3   r5   c                   
   e Zd ZU  edd      Zej                  j                  ed<    edd      Ze	ed<    ed	d
      Z
ee   ed<    ed	d      Zee   ed<    edd      Zee	   ed<   ddiZ ed	d      Zee   ed<   y	)AgentConfig.z/Client for interacting with the language model.r(   clientgpt-4o-miniz*The model to use for generating responses.)defaultr)   modelNz+History component for storing chat history.historyz(Component for generating system prompts.system_prompt_generatorsystemzHThe role of the system in the conversation. None means no system prompt.system_rolearbitrary_types_allowedTz1Additional parameters passed to the API provider.model_api_parameters)r,   r-   r.   r   r8   
instructor
Instructorr1   r;   r0   r<   r   r
   r=   r   r?   model_configrA   dictr2   r3   r"   r7   r7   <   s    +0Bs+tFJ((t}:fgE3g%*4Er%sGXk"s?D"L@X&;<  "'&p"K#  .t4L+0Cv+w(4.wr3   r7   c                  H    d d xdd xf G fdd
} |       S )InputSchemac                      t         S Nr   r2   r3   r"   rG   rG   J   s    |+r3   OutputSchemac                      t         S rI   r   r2   r3   r"   rJ   rJ   J   s    <-Gr3   c                   "   e Zd ZW  ZdZdefdZd Zede	e
   fd       Zede	e
   fd       Zd Zdd
eW    dW fdZdd
eW    deW d	W f   fdZdd
eW    dW fdZdd
eW    deW d	f   fdZdede	e   fdZdedefdZdefdZy	)AtomicAgenta  
    Base class for chat agents.

    This class provides the core functionality for handling chat interactions, including managing history,
    generating system prompts, and obtaining responses from a language model.

    Type Parameters:
        InputSchema: Schema for the user input, must be a subclass of BaseIOSchema.
        OutputSchema: Schema for the agent's output, must be a subclass of BaseIOSchema.

    Attributes:
        client: Client for interacting with the language model.
        model (str): The model to use for generating responses.
        history (ChatHistory): History component for storing chat history.
        system_prompt_generator (SystemPromptGenerator): Component for generating system prompts.
        system_role (Optional[str]): The role of the system in the conversation. None means no system prompt.
        initial_history (ChatHistory): Initial state of the history.
        current_user_input (Optional[InputSchema]): The current user input being processed.
        model_api_parameters (dict): Additional parameters passed to the API provider.
            - Use this for parameters like 'temperature', 'max_tokens', etc.
    configc                 T   |j                   | _         |j                  | _        |j                  xs
 t               | _        |j                  xs
 t               | _        |j                  | _        | j                  j                         | _        d| _	        |j                  xs i | _
        y)z
        Initializes the AtomicAgent.

        Args:
            config (AgentConfig): Configuration for the chat agent.
        N)r8   r;   r<   r
   r=   r   r?   copyinitial_historycurrent_user_inputrA   )selfrN   s     r"   __init__zAtomicAgent.__init__a   s     mm\\
~~6'-'E'E'`I^I`$!--#||002"&$*$?$?$E2!r3   c                 B    | j                   j                         | _        y)z:
        Resets the history to its initial state.
        N)rQ   rP   r<   rS   s    r"   reset_historyzAtomicAgent.reset_historyq   s     ++002r3   returnc                 ^    t        | d      rt        | j                        \  }}|S t        }|S N__orig_class__)hasattrr	   r[   r'   )rS   TI_s      r"   input_schemazAtomicAgent.input_schemaw   s4    4)*T001EB 	 &B	r3   c                 ^    t        | d      rt        | j                        \  }}|S t        }|S rZ   )r\   r	   r[   r5   )rS   r^   TOs      r"   output_schemazAtomicAgent.output_schema   s4    4)*T001EAr 	 'B	r3   c                     | j                   g | _        n-| j                   | j                  j                         dg| _        | xj                  | j                  j                         z  c_        y )N)rolecontent)r?   messagesr=   generate_promptr<   get_historyrV   s    r"   _prepare_messageszAtomicAgent._prepare_messages   s]    #DM !,,#;;KKMDM 	1133r3   N
user_inputc                    t        | j                  t        j                  j                        rJ d       |r=| j                  j                          || _        | j                  j                  d|       | j                           | j                  j                  j                  j                  d| j                  | j                  | j                  d| j                  }| j                  j                  d|       |S )a  
        Runs the chat agent with the given user input synchronously.

        Args:
            user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.

        Returns:
            OutputSchema: The response from the chat agent.
        zIThe run method is not supported for async clients. Use run_async instead.user)rf   r;   response_model	assistantr2   )
isinstancer8   rB   AsyncInstructorr<   initialize_turnrR   add_messageri   chatcompletionscreaterf   r;   rb   rA   rS   rj   responses      r"   runzAtomicAgent.run   s     KK**::
 	WV	W 
 LL((*&0D#LL$$VZ8 64;;##//66 
]]**--
 ''	
 	  h7r3   c              3   d  K   t        | j                  t        j                  j                        rJ d       |r=| j                  j                          || _        | j                  j                  d|       | j                           | j                  j                  j                  j                  d| j                  | j                  | j                  d| j                  ddi}|D ]  }|   | j                  di j!                         }| j                  j                  d|       |S w)a  
        Runs the chat agent with the given user input, supporting streaming output.

        Args:
            user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.

        Yields:
            OutputSchema: Partial responses from the chat agent.

        Returns:
            OutputSchema: The final response from the chat agent.
        zPThe run_stream method is not supported for async clients. Use run_async instead.rl   r;   rf   rm   streamTrn   r2   ro   r8   rB   rp   r<   rq   rR   rr   ri   rs   rt   create_partialr;   rf   rb   rA   
model_dump)rS   rj   response_streampartial_responsefull_response_contents        r"   
run_streamzAtomicAgent.run_stream   s#     KK**::
 	^]	^ 
 LL((*&0D#LL$$VZ8 E$++**66EE 
**]]--
 ''	

 
 !0 	#""	# !3 2 2 S5E5P5P5R S  .CD$$s   D.D0c                   K   t        | j                  t        j                  j                        sJ d       |r=| j                  j                          || _        | j                  j                  d|       | j                           | j                  j                  j                  j                  d| j                  | j                  | j                  d| j                   d{   }| j                  j                  d|       |S 7 "w)a  
        Runs the chat agent asynchronously with the given user input.

        Args:
            user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.

        Returns:
            OutputSchema: The response from the chat agent.

        Raises:
            NotAsyncIterableError: If used as an async generator (in an async for loop).
                                   Use run_async_stream() method instead for streaming responses.
        *The run_async method is for async clients.rl   rz   Nrn   r2   )ro   r8   rB   rp   r<   rq   rR   rr   ri   rs   rt   ru   r;   rf   rb   rA   rv   s      r"   	run_asynczAtomicAgent.run_async   s      $++z'8'8'H'HIwKwwILL((*&0D#LL$$VZ8 <))55<< 
**t}}TEWEW
[_[t[t
 
 	  h7
s   C$D&D	'#Dc                  K   t        | j                  t        j                  j                        sJ d       |r=| j                  j                          || _        | j                  j                  d|       | j                           | j                  j                  j                  j                  d| j                  | j                  | j                  d| j                  ddi}d}|2 3 d{   }|}| 7 6 |r= | j                  di |j!                         }| j                  j                  d|       yyw)	a@  
        Runs the chat agent asynchronously with the given user input, supporting streaming output.

        Args:
            user_input (Optional[InputSchema]): The input from the user. If not provided, skips adding to history.

        Yields:
            OutputSchema: Partial responses from the chat agent.
        r   rl   rz   r{   TNrn   r2   r|   )rS   rj   r   last_responser   r   s         r"   run_async_streamzAtomicAgent.run_async_stream   s)     $++z'8'8'H'HIwKwwILL((*&0D#LL$$VZ8 E$++**66EE 
**]]--
 ''	

 
 &5 	# 	#",M""	#o $6D$6$6$T9Q9Q9S$T!LL$$[2GH s+   C)D?+C>/C<0C>3	D?<C>>AD?provider_namec                     || j                   j                  vrt        d| d      | j                   j                  |   S )a/  
        Retrieves a context provider by name.

        Args:
            provider_name (str): The name of the context provider.

        Returns:
            BaseDynamicContextProvider: The context provider if found.

        Raises:
            KeyError: If the context provider is not found.
        Context provider '' not found.r=   context_providersKeyErrorrS   r   s     r"   get_context_providerz AtomicAgent.get_context_provider  sD      < < N NN/lKLL++==mLLr3   providerc                 6    || j                   j                  |<   y)z
        Registers a new context provider.

        Args:
            provider_name (str): The name of the context provider.
            provider (BaseDynamicContextProvider): The context provider instance.
        N)r=   r   )rS   r   r   s      r"   register_context_providerz%AtomicAgent.register_context_provider+  s     IQ$$66}Er3   c                     || j                   j                  v r| j                   j                  |= yt        d| d      )z
        Unregisters an existing context provider.

        Args:
            provider_name (str): The name of the context provider to remove.
        r   r   Nr   r   s     r"   unregister_context_providerz'AtomicAgent.unregister_context_provider5  sA     D88JJJ,,>>}M/lKLLr3   rI   )r,   r-   r.   __type_params__r/   r7   rT   rW   propertyr   r   r_   rb   ri   r   rx   r   r   r   r   r   r0   r   r   r   r   ).type_paramsrG   rJ   s   r"   rM   rM   J   s"   ,F{ F 3 d<0   tL1  4h{3 | :%%Xk%: %%iP\^bdpPpFq %%N(;*? < :!I+1F !IR`amosasRt !IFM# M$?Y:Z M"Qs QF` Q
M 
Mr3   rM   r2   ).generic_baser   rG   rJ   s    @@@r"   #<generic parameters of AtomicAgent>r   J   s!    +-G+ uM uM uMr3   __main__)Console)Panel)Table)Syntax)box)OpenAIAsyncOpenAI)LivetitleschemarX   c                 Z   t        | t        j                        }|j                  dd       |j                  dd       |j                  dd       |j                  j                         D ]9  \  }}|j                  |t        |j                        |j                  xs d	       ; |S )
zCreate a table displaying schema information.

        Args:
            title (str): Title of the table
            schema (Type[BaseModel]): Schema to display

        Returns:
            Table: Rich table containing schema information
        r   r   r   cyanstyler   magentaDescriptiongreenr   )
r   r   ROUNDED
add_columnmodel_fieldsitemsadd_rowr0   
annotationr)   )r   r   schema_table
field_namefields        r"   _create_schema_tabler   N  s     5ckk:v6i8W=!'!4!4!:!:!< 	]J  S1A1A-BEDUDUD[Y[\	] r3   agentc                    t        dt        j                        }|j                  dd       |j                  dd       |j	                  d| j
                         |j	                  d	t        t        | j                        j                               |j	                  d
t        t        | j                        j                               |S )zCreate a table displaying agent configuration.

        Args:
            agent (AtomicAgent): Agent instance

        Returns:
            Table: Rich table containing configuration information
        zAgent Configurationr   Propertyr   r   ValueyellowModelHistoryzSystem Prompt Generator)r   r   r   r   r   r;   r0   typer<   r,   r=   )r   
info_tables     r"   _create_config_tabler   b  s     !6CKKH
j7gX67EKK09c$u}}*=*F*F&GH4c$u?\?\:]:f:f6ghr3   c           
         t               }|j                  t        j                  ddd             t	        d| j
                        }|j                  |       t	        d| j                        }|j                  |       t        |       }|j                  |       | j                  j                         }|j                  t        t        |ddd	
      ddd             y)z@Display information about the agent's configuration and schemas.z([bold blue]Agent Information[/bold blue]blue   r   border_stylepaddingzInput SchemazOutput SchemamarkdownmonokaiT)themeline_numberszSample System Promptr   F)r   r   expandN)r   printr   fitr   r_   rb   r   r=   rg   r   )r   consoleinput_schema_tableoutput_schema_tabler   system_prompts         r"   display_agent_infor   u  s    )II:#	
 2.%BTBTU() 3?EDWDWX)* *%0
j! 55EEG}j	PTU,$		
r3   	streamingc                   K   | rCt        j                  t                     }t        |d      }t	        t
        t        f   |      }nBt        j                  t                     }t        |d      }t	        t
        t        f   |      }t        |       t               }|j                  t        j                  d|  ddd             	 |j                  d      }|j                         d	k(  r|j                  d
       y|j                  |      }|j                  d       | rat!        |d      5 }|j#                  |      2 3 d{   }|j%                         }	t'        j(                  |	d      }
|j+                  |
       B|j-                  |      }|j%                         }	t'        j(                  |	d      }
|j                  |
       7 6 	 ddd       # 1 sw Y   xY ww)zInteractive chat loop with the AI agent.

        Args:
            streaming (bool): Whether to use streaming mode for responses
        r9   )r8   r;   z>[bold blue]Interactive Chat Mode[/bold blue]
[cyan]Streaming: z[/cyan]
Type 'exit' to quitr   r   r   z
[bold green]You:[/bold green] exitz[yellow]Goodbye![/yellow])r*   z![bold blue]Assistant:[/bold blue]   )r   refresh_per_secondN   )indent)rB   from_openair   r7   rM   r'   r5   r   r   r   r   r   r   inputlowerr_   r   r   r~   jsondumpsupdaterx   )r   r8   rN   r   r   user_messagerj   liver   response_jsonjson_strrw   s               r"   	chat_loopr     s     ++KM:F mDF 46K KLVTE++FH5F mDF 46K KLVTE 	5!)II$$-; /&& $	
 "==)KLL!!#v-9:+++FJMM=>'a@ .D272H2H2T . ..(8(C(C(E#'::mA#FH- 99Z0 ( 3 3 5::mA>h'+ .2T. . .sI   D1G+3GG	G
G:GAG+GG	G+G($G+z#
[bold]Starting chat loop...[/bold]T)r   )F)9rB   pydanticr   r   typingr   r   r   r   r	   "atomic_agents.context.chat_historyr
   -atomic_agents.context.system_prompt_generatorr   r   !atomic_agents.base.base_io_schemar   instructor.dsl.partialr   jiterr   r#   r%   classmethodmodel_from_chunksmodel_from_chunks_asyncr'   r5   r7   rM   r,   rich.consoler   
rich.panelr   
rich.tabler   rich.syntaxr   richr   openair   r   asyncio	rich.liver   r   r0   r   r   r   boolr   r   r   rx   r2   r3   r"   <module>r      s    % F F : ; .  !,,E F &12Q&R #< 	L 	x) xuMp z$  "*C i U (K E & 
+  
D2(4 2(h iGMM89GKK	D)*W r3   