Skip to content

Commit 91119fd

Browse files
committed
Allow checking for unresolved template vars in prompts
1 parent 4fdaec1 commit 91119fd

File tree

2 files changed

+15
-3
lines changed

2 files changed

+15
-3
lines changed

llms_wrapper/llms.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
warnings.filterwarnings("ignore", category=UserWarning, module="pydantic")
99
import litellm
1010
import json
11+
import re
1112
import time
1213
import threading
1314
import traceback
@@ -52,7 +53,11 @@
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

llms_wrapper/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
11
import importlib.metadata
2-
__version__ = "0.9.1.6"
2+
__version__ = "0.9.1.7"
33

0 commit comments

Comments
 (0)