88warnings .filterwarnings ("ignore" , category = UserWarning , module = "pydantic" )
99import litellm
1010import json
11+ import re
1112import time
1213import threading
1314import traceback
5253 "min_delay" , # minimum delay between queries for that model
5354]
5455
55- def any2message (message : str | List [Dict [str ,str ]]| Dict [str ,str ], vars : Optional [Dict ] = None ) -> List [Dict [str ,str ]]:
56+ def any2message (
57+ message : str | List [Dict [str ,str ]]| Dict [str ,str ],
58+ vars : Optional [Dict ] = None ,
59+ check4unreplaced : bool = False ,
60+ ) -> List [Dict [str ,str ]]:
5661 """
5762 Convert the different representations of prompt messages we use to the standard representation
5863 used by OpenAI and others.
@@ -69,6 +74,8 @@ def any2message(message: str|List[Dict[str,str]]|Dict[str,str], vars: Optional[D
6974 Args:
7075 message: A string, list of dictionaries or a dictionary representing the message(s).
7176 vars: A dictionary of variables to replace in the content of the messages.
77+ check4unreplaced: if True, and vars is not None, will check if there are any non-replaced template variables
78+ still in the prompt and throws and Exception if yes
7279
7380 Returns:
7481 A list of message dictionaries with the keys "role" and "content".
@@ -91,11 +98,16 @@ def any2message(message: str|List[Dict[str,str]]|Dict[str,str], vars: Optional[D
9198 raise ValueError (f"Error: message is a dict but not a dict of strings: { message } " )
9299 else :
93100 raise ValueError (f"Error: message is not a string or list or dict: { message } " )
94- if vars :
101+ if vars :
102+ unresolved = []
95103 for d in ret :
96104 if d ["content" ]:
97105 for k , v in vars .items ():
98106 d ["content" ] = d ["content" ].replace (f"${{{ k } }}" , str (v ))
107+ if check4unreplaced :
108+ unresolved .extend (re .findall (r'\$\{\w+\}' , d ["content" ]))
109+ if check4unreplaced and unresolved :
110+ raise Exception (f"Prompt contains unresolved template vars: { unresolved } " )
99111 return ret
100112
101113
0 commit comments