Skip to content

bug(sdk-python): get_langchain_prompt drops the closing brace of nested JSON #18131

Description

@JoeyTan21

Describe the bug

get_langchain_prompt() drops a closing brace when a prompt contains compact nested JSON, so LangChain renders malformed JSON. This is the Python counterpart of #18027 (reported for the JS SDK).

Prompt text: Reply with JSON like {"user": {"name": "{{name}}"}}

get_langchain_prompt() returns Reply with JSON like {{"user": {{"name": "{name}"}} (two escaped opening braces, one escaped closing pair). PromptTemplate.from_template(...).format(name="Ann") renders Reply with JSON like {"user": {"name": "Ann"}, which is missing the final }. No error is raised. Each additional }} run in deeper nesting loses one more brace. Chat prompts are affected the same way, since ChatPromptClient.get_langchain_prompt() uses the same helper. Multi-line JSON, where closing braces are not adjacent, is not affected.

Cause: BasePromptClient._escape_json_for_langchain in langfuse/model.py treats every }} as an already-escaped pair and passes it through unchanged, even when the first } closes a JSON brace that the function doubled earlier.

To reproduce (no server needed)

from langchain_core.prompts import PromptTemplate
from langfuse.api import Prompt_Text
from langfuse.model import TextPromptClient

p = TextPromptClient(Prompt_Text(type="text", name="t", version=1, config={}, tags=[], labels=[],
                                 prompt='Example: {"a": {"b": 1}}'))
print(p.get_langchain_prompt())                                         # Example: {{"a": {{"b": 1}}
print(PromptTemplate.from_template(p.get_langchain_prompt()).format())  # Example: {"a": {"b": 1}

SDK and integration versions

langfuse-python main (4.16.0, commit 618e4702), langchain-core 1.2.22, Python 3.12. Client-side only, reproduced offline.

Are you interested in contributing a fix?

Yes, I have a small fix with regression tests ready for langfuse-python.

Disclosure: found, reproduced and the draft fix tested locally with the help of an AI coding agent (Claude Code); reviewed before filing.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions