
    +#h+L                     F   d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dlZd dl	Z	d dl
mZ d dlZd dlmZ d dlmZ d dlmZmZ d Zd Z G d	 d
ej,                        Z G d dej,                        Zddddej,                  fdZ G d dej,                        Zd Zd Zy)    N)	AnnotatedListTupleUnion)	FieldInfo)passages2text)
Prediction)ensure_signaturemake_signaturec                      dt         j                  ffd}t        |       dk(  r't        | d         rt              dk(  r || d         S |S )Nreturnc                     t        |       }|j                  j                         ^ }}t        t	        |fi |      S )zIDecorator that creates a predictor module based on the provided function.)_func_to_signatureoutput_fieldskeys_StripOutputTypedPredictorfunc	signature_
output_keykwargss       W/var/www/html/sandstorm/venv/lib/python3.12/site-packages/dspy/functional/functional.py
_predictorzpredictor.<locals>._predictor   s<    &t,	"00557JN9??LL       r   dspyModulelencallable)argsr   r   s    ` r   	predictorr$      sM    MDKK M 4yA~(47+Fq0@$q'""r   c                      dt         j                  ffd}t        |       dk(  r't        | d         rt              dk(  r || d         S |S )Nr   c                     t        |       }|j                  j                         ^ }}t        t	        |fi |      S )zPDecorator that creates a chain of thought module based on the provided function.)r   r   r   r   TypedChainOfThoughtr   s       r   _cotzcot.<locals>._cot    s=    &t,	"00557J/	DVDjQQr   r   r   r   )r#   r   r(   s    ` r   cotr)      sK    Rdkk R 4yA~(47+Fq0@DG}Kr   c                   *     e Zd Z fdZd Zd Z xZS )r   c                 >    t         |           || _        || _        y N)super__init__r$   r   )selfr$   r   	__class__s      r   r.   z_StripOutput.__init__.   s    "$r   c                 ^    t        | j                  j                         | j                        S r,   )r   r$   copyr   r/   s    r   r2   z_StripOutput.copy3   s     DNN//14??CCr   c                 D     | j                   di |}|| j                     S )N )r$   r   )r/   r   
predictions      r   forwardz_StripOutput.forward6   s$    #T^^-f-
$//**r   )__name__
__module____qualname__r.   r2   r7   __classcell__r0   s   @r   r   r   -   s    %
D+r   r   c                   "     e Zd ZdZ fdZ xZS )FunctionalModulezXTo use the @cot and @predictor decorators, your module needs to inheret form this class.c                     t         |           t        |       D ]F  }t        | |      }t	        |t
        j                        s*|j                         | j                  |<   H y r,   )	r-   r.   dirgetattr
isinstancer   r    r2   __dict__)r/   nameattrr0   s      r   r.   zFunctionalModule.__init__>   sO    I 	2D4&D$,&*iikd#	2r   )r8   r9   r:   __doc__r.   r;   r<   s   @r   r>   r>   ;   s    b2 2r   r>      max_retriesr   c                    t        | |      } dj                  | j                  j                               }t	        j
                  dd|z   dz         }|xs |}t        | j                  d|      |      S )z@Just like TypedPredictor, but adds a ChainOfThought OutputField., z/Reasoning: Let's think step by step in order toz${produce the z	}. We ...prefixdesc	reasoningrH   )r
   joinr   r   r   OutputFieldr   prepend)r   instructionsrO   rI   output_keysDEFAULT_RATIONALEs         r   r'   r'   F   s     L9I))I3388:;K((@+k9 ..I	
   r   c            
            e Zd Zddddd fdZddZd ZdefdZd	ed
e	ee
f   dededef
dZd
eded	edefdZdej                  fdZdej"                  fdZ xZS )r   rG   FrI   	wrap_jsonexplain_errorsc                    t         |           t        ||      | _        t	        j
                  |      | _        || _        || _        || _	        y)ad  Like dspy.Predict, but enforces type annotations in the signature.

        Args:
            signature: The signature of the module. Can use type annotations.
            max_retries: The number of times to retry the prediction if the output is invalid.
            wrap_json: If True, json objects in the input will be wrapped in ```json ... ```
        N)
r-   r.   r
   r   r   Predictr$   rI   rX   rY   )r/   r   rS   rI   rX   rY   r0   s         r   r.   zTypedPredictor.__init__[   sE     	))\Bi0&",r   r   c                 p    t        | j                  | j                  | j                  | j                        S )NrW   )r   r   rI   rX   rY   r3   s    r   r2   zTypedPredictor.copyj   s/    NN((nn..	
 	
r   c                 "    d| j                    dS )z<Return a string representation of the TypedPredictor object.zTypedPredictor())r   r3   s    r   __repr__zTypedPredictor.__repr__r   s      022r   c                 H   t        j                  |j                               }| j                  rd|z   dz   } t	        j
                  t        dd            |      j                  }	 |j                  t        |             |S # t        j                  t        f$ r Y yw xY w)N```json

```
zjson_schema -> json_objectzIMake a very succinct json object that validates with the following schema)json_schema )jsondumpsmodel_json_schemarX   r   r[   r   json_objectmodel_validate_json_unwrap_jsonpydanticValidationError
ValueError)r/   type_schemarh   s       r   _make_examplezTypedPredictor._make_examplev   s    E3356>> 6)I5F
dll,[

 
 *k 		%%l;&?@  ((*5 		s   )B B! B!errortask_descriptionmodel_output
lm_explainc           	         t        |t        j                        rkg }|j                         D ]D  }dj	                  t        t        |d               }|j                  |d    d| d|d    d       F dj	                  |      }nt        |      }| j                  rF|rDt        |t              r|j                  }	|	d	   d
z   |	d   z   }|dz   | j                  |||      z   S |S )NrK   locmsgz: z (error type: typer^   z; rM    rN   
)rr   rs   rq   )rB   rk   rl   errorsrP   mapstrappendreprrY   r   json_schema_extra_make_explanation)
r/   rq   rr   rs   rt   r{   efields
error_textr#   s
             r   _format_errorzTypedPredictor._format_error   s     eX556F\\^ Q3sAeH#565
"VHN1V9+QOPQ 6*JeJ:*I6'99#'>C#7$v,#F ((%5!-$ )  r   c                      G d dt         j                        } t        j                  |      |||      j                  S )Nc                   "   e Zd ZU  ej                  d      Z ej                  d      Ze	e
d<    ej                  d      Ze	e
d<    ej                  d      Ze	e
d<    ej                  d	      Ze	e
d
<    ej                  d      Ze	e
d<   y)3TypedPredictor._make_explanation.<locals>.Signaturez
                I gave my language model a task, but it failed. Figure out what went wrong,
                and write instructions to help it avoid the error next time.zWhat I asked the model to dorN   rr   zThe output of the modellanguage_model_outputz1The validation error trigged by the models outputrq   z Explain what the model did wrongexplanationzFInstructions for the model to do better next time. A single paragraph.adviceN)r8   r9   r:   textwrapdedentrF   r   
InputFieldrr   r}   __annotations__r   rq   rQ   r   r   r5   r   r   	Signaturer      s    %hooPG %4DOO9W$XcX)8>W)X!3X(.abE3b/t//5WXKX*$**]FC r   r   )rr   r   rq   )r   r   r[   r   )r/   rr   rs   rq   r   s        r   r   z TypedPredictor._make_explanation   s<    	 	$ 't||I&-".
 &		r   c                    | j                   }| j                   j                  j                         D ]  \  }}|j                  d   dk(  }|j                  }|r|t
        u rBd }|j                  ||j                  j                  dd      |t        k7  rdndz   d |      }r|t        t        t        t
        fv rM|j                  ||j                  j                  dd      |t        k7  rd	|j                   d
ndz   d |      }	 t        j                  |      r;t+        j,                  |      t.        t0        fvrt        |t        j                         sVt        j"                  d|dft        j                         }|fd}|fd}t%        j&                  |j)                               }	n+d }|fd}t%        j&                  |j)                               }	| j2                  r|fd}d|	z   dz   }	|j                  ||j                  j                  dd      d|	z   z   |fd|fd|      } d}
d }|t4        t           t.        t           t6        t           t0        t           fv rt8        }nt+        j,                  |      t4        t.        t6        t0        fv rPt+        j:                  |      \  }t        j                  |      rt        |t        j                         rd }nd }d}
n4t        j                  |      rt        |t        j                         rd }d}
| j2                  r|
r|fd }|j                  ||!      } |S )"z]Add formats and parsers to the signature fields, based on the type annotations of the fields.__dspy_field_typeoutputc                 f    | j                         j                         } | dvrt        d      | dk(  S )N)truefalsezRespond with true or falser   )striplowerrm   xs    r   parsez0TypedPredictor._prepare_signature.<locals>.parse   s3    GGIOO-$55",-I"JJ F{*r   rN   rd   z (Respond with true or false)c                 <    t        | t              r| S t        |       S r,   rB   r}   r   s    r   <lambda>z3TypedPredictor._prepare_signature.<locals>.<lambda>       jC.@ c!f r   )rN   formatparserz (Respond with a single z value)c                 <    t        | t              r| S t        |       S r,   r   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   r   r   FOutput.)value__base__c                 0     ||       j                         S )N)r   model_dump_jsonr   rn   s     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   s    Q9W9W9Y r   c                 8    |j                  |       j                  S r,   )ri   r   r   s     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   s    5;T;TUV;W;];] r   c                 "    | j                         S r,   r   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   s    A,=,=,? r   c                 $    |j                  |       S r,   )ri   r   s     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   s    5;T;TUV;W r   c                     d ||       z   dz   S Nra   rb   r5   r   inners     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>   s    ;q;QT];] r   ra   z
```z2. Respond with a single JSON object. JSON Schema: c                 6    t        | t              r| S  ||       S r,   r   )r   to_jsons     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s    
1c@R1 X_`aXb r   c                 $     |t        |             S r,   )rj   )r   	from_jsons     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s    iUV>X r   )rN   r   r   rn   c                 <    t        | t              r| S t        |       S r,   r   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s    As);A Q r   c                 b    t        | t              r| S ddj                  d | D              z   dz   S )N[,c              3   <   K   | ]  }|j                           y wr,   r   ).0is     r   	<genexpr>zFTypedPredictor._prepare_signature.<locals>.<lambda>.<locals>.<genexpr>  s     QqjkRSRcRcReQqs   ])rB   r}   rP   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s.    :a+=a 3QqopQqIqCqtwCw r   c                 P    t        | t              r| S t        j                  |       S r,   )rB   r}   re   rf   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s    As1CA TU r   Tc                 F    t        | t              r| S | j                         S r,   )rB   r}   r   r   s    r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s    Z3-? QEVEVEX r   c                 B    t        | t              r| S d ||       z   dz   S r   r   r   s     r   r   z3TypedPredictor._prepare_signature.<locals>.<lambda>  s&    Jq#<Nq T_bghibjTjmvTv r   )r   )r   r   itemsr   
annotationboolwith_updated_fieldsgetr}   intfloatr8   inspectisclass
issubclassrk   	BaseModelcreate_modelre   rf   rg   typing
get_originlisttuplerX   r   r   r   get_args)r/   r   rD   field	is_outputrn   r   r   r   ro   is_jsonformat_
inner_types                r   _prepare_signaturez!TypedPredictor._prepare_signature   s	   NN	>>00668 T	PKD%//0CDPI$$ED=+ !* = ="4488D>Csl:PRTL$ !> !I sC55 ) = ="4488DQVZ]Q]5enn5EWMcegL$ !> !I   ."--e4T5MI&uh.@.@A ( 5 5hucl]e]o]o p27"Y49$]	!%E,C,C,E!F"?49$W	!%E,C,C,E!F~~29"]!,v!5!? ) = ="4488DORXXZ18c3<X# !> !I  GT#YS	5:uSzJJ+G&&u-$eU1KK$*OOE$:MZz2z*hN`N`7aw   #W"G__U+
5(BTBT0UXG"G>>g.5vG%99$w9O	iT	Pl r   c                    |j                         }| j                         }t        | j                        D ]y  } | j                  di |d|i}i }g }|j
                  D ]~  i }|j                  j                         D ]3  \  }	}
	 |	   }|
j                  j                  dd       } ||      ||	<   5 |r n(	  | j&                  di ||}|j)                  |        |r|j                         D ]w  \  }	}||d|	 d| <   |	dk(  rd}n|j                  |	   j                  d   }|dk(  rdnd|dz    d}|j)                  d|	 d| t/        j0                  d| d| d            }y 9t3        j4                  |j                  D ci c]  }||D cg c]  }||   	 c} c}}      c S  t        d      # t        j                  t        f$ r}| j                  ||j                  |	   |dz   | j                  k        ||	<   |
j                  j                  dd      }|j                  d      }|d	k(  rY d }~||d  |d | }}d
}|dz   | j                  k  rC||vr?| j!                  |
j"                        x}r"|j%                  |	|dz   |z   |z   dz   |z         }Y d }~-d }~ww xY w# t        j                  $ rm}| j                  ||j*                  dj-                  fd|j                  j                         D              |dz   | j                  k        |d<   Y d }~d }~ww xY wc c}w c c}}w )Nnew_signaturer   c                     | S r,   r5   r   s    r   r   z(TypedPredictor.forward.<locals>.<lambda>0  s    QR r   r   )rt   rN   rd   zJSON Schema: zYou MUST use this format: rz   r   z

c              3   Z   K   | ]"  \  }}d |j                   d   z   dz   |   z    $ yw)z> rM   ry   N)r   )r   rD   r   
completions      r   r   z)TypedPredictor.forward.<locals>.<genexpr>V  s=      $ +e !5#:#:8#DDsJZX\M]]$s   (+generalerror_r   zGeneral:rM   r   z (r^   z
Past Errorz in zAn error to avoid in the futurerL   z[Too many retries trying to get the correct output format. Try simplifying the requirements.r5   )r2   r   rangerI   r$   completionsr   r   r   r   rk   rl   rm   r   r   findrp   r   r   r   r~   rS   rP   r   r   r	   from_completions)r/   r   modified_kwargsr   try_iresultr{   parsed_resultsparsedrD   r   r   r   r   current_descr   suffixrM   exampler   rq   error_prefixnumberkeyrr   s                            @r   r7   zTypedPredictor.forward!  s    ++- ++-	4++, J	E#T^^OoOYOFFN$00 0
#,#:#:#@#@#B KD% *4 0!&!8!8!<!<X{!S'-e}t	< &::6:A"))&1M0b #)<<> KD%?DOfTF!E7$;<y('1'0'>'>t'D'V'VW_'`#(A:RRay?F ) 0 0 aw/%/xtL>#J!B!I  "22FOF]F]^sS>:a1S6::^ QJ	V n
 	
 %44jA '+'9'9%,,T2!',qy43C3C'C	 (: (t (-'>'>'B'B62'N(--o>7$/;AB/?bqAQ!=!AI(8(88 &l :,0,>,>u?O?O,P!P!P(1(E(E $%1D%86%AG%Kd%RU[%[ )F )I)@  // 	(,(:(:!.. $/8/F/F/L/L/N$  $)19t/?/?#? ); )F9%	: ;^sQ   -G ;%J5
L=L8$L= J2	A'J-	A!J-	-J2	5L5A"L00L58L=r,   )r   r   )r8   r9   r:   r.   r2   r_   r}   rp   	Exceptionr   r   r   r   r   r   r   r   r	   r7   r;   r<   s   @r   r   r   Z   s    -AQVgl -
3c .  Y/ 	
  
@# S QT Y\ 2YDNN YvS
4?? S
r   r   c                 (   t        j                  |       }t        j                  | d      }| j                  }| j
                  }i }|j                  j                         D ]  }|j                  dk(  r|j                  |j                  t              }i }t        j                  |      t        u r-t        d t        j                  |      D        d      }	|	|	|d<   |t        j                   d	i |f||j                  <    i }|j                  dt              }t        j                  |      t        u r-t        d t        j                  |      D        d      }	|	|	|d<   |t        j"                  d	i |f||<   t        j$                  ||      S )
z5Make a dspy.Signature based on a function definition.T)include_extrasr/   c              3   B   K   | ]  }t        |t              s|  y wr,   r   r   args     r   r   z%_func_to_signature.<locals>.<genexpr>  s     \zRUWZG[\   NrN   r   c              3   B   K   | ]  }t        |t              s|  y wr,   r   r   s     r   r   z%_func_to_signature.<locals>.<genexpr>  s     XS:cSVCWSXr   r5   )r   r   r   get_type_hintsr8   rF   
parametersvaluesrD   r   r}   r   r   nextr   r   r   rQ   r   )
r   sigannotationsr   rS   r   paramr   r   rN   s
             r   r   r   w  sc   


D
!C''TBKJ<<LF &&( 
E:: __UZZ5
Z(I5\
(C\^bcD!%v($//*CF*CDuzz
E F3/J$	1XFOOJ$?XZ^_!F6N$d&6&6&@&@AF:>>&,//r   c                    | j                         } | j                  d      rK| j                  d      st        d      | j                  d      st        d      | dd j                         } | j                  d      r| j                  d      st        d	      t	        j
                  t	        j                  |             S )
Nz```z```jsonz%json output should start with ```jsonz-Don't write anything after the final json ```   {}z-json output should start and end with { and })r   
startswithrm   endswithujsonrf   loads)r   s    r   rj   rj     s    \\^F  +DEEu%LMM"##%S!)=HII;;u{{6*++r   )NN)r   re   r   r   r   r   r   r   rk   r  pydantic.fieldsr   r   dsp.templatesr   dspy.primitives.predictionr	   dspy.signatures.signaturer
   r   r$   r)   r    r   r>   r'   r   r   rj   r5   r   r   <module>r     s        0 0   %  ' 1 F+4;; +2t{{ 2UV [_[f[f (Z
T[[ Z
z0B
,r   