Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Langchain prompt single braces #816

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion langfuse/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,20 @@ def get_langchain_prompt(self):

@staticmethod
def _get_langchain_prompt_string(content: str):
return re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content)
# replace single `{` with the temporary replacement content
content = re.sub(r'(?<!{){(?!{)', '<LANGFUSE_REPLACE_OPEN>', content)

# replace single `}` with the temporary replacement content
content = re.sub(r'(?<!})}(?!})', '<LANGFUSE_REPLACE_CLOSE>', content)

# replace all double braces with single braces for langchain vars
content = re.sub(r"{{\s*(\w+)\s*}}", r"{\g<1>}", content)

# replace temporary replacements with double braces
content = re.sub('<LANGFUSE_REPLACE_OPEN>', '{{', content)
content = re.sub('<LANGFUSE_REPLACE_CLOSE>', '}}', content)

return content

@staticmethod
def _compile_template_string(content: str, data: Dict[str, Any] = {}) -> str:
Expand Down
16 changes: 16 additions & 0 deletions tests/test_langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -1659,7 +1659,23 @@ def test_get_langchain_prompt_with_jinja2():
langfuse_prompt.get_langchain_prompt()
== 'this is a {template} template that should remain unchanged: {{ handle_text(payload["Name"], "Name is") }}'
)

def test_get_langchain_prompt_with_braces():
langfuse = Langfuse()

prompt = 'This is a {{test}} with another {{test} that leads to {this}'
langfuse.create_prompt(
name="test_braces",
prompt=prompt,
labels=["production"],
)

langfuse_prompt = langfuse.get_prompt("test_braces")

assert (
langfuse_prompt.get_langchain_prompt()
== 'This is a {test} with another {{test}} that leads to {{this}}'
)

def test_get_langchain_prompt():
langfuse = Langfuse()
Expand Down