prefix-safe-json-langchain
Fail-closed cutoff guard for streamed LangChain and LangGraph tool calls.
Why this exists
When LangChain streams a tool call (for example ChatOpenAI(..., streaming=True)) and the response hits its output-token limit (finish_reason="length" / stop_reason="max_tokens") or the HTTP stream ends early without a finish signal, langchain-core repairs the truncated JSON arguments using parse_partial_json (langchain-ai/langchain#41285).
LangGraph's ToolNode then executes the repaired partial arguments as if they were complete. In agent-faultbench's cutoff suite (write_file expecting 40 lines / 2,120 bytes), streaming ChatOpenAI wrote 866 of 2,120 bytes to disk and the agent returned "Done." with no error.
psj_langchain adds a fail-closed post-model guard that inspects AIMessage.response_metadata before tool execution. Any tool_calls on an AIMessage without a positively confirmed completion signal are moved into invalid_tool_calls with an explanatory error, so the tool never runs and the model is told why.
Install
Experimental and not on PyPI yet. Install it from this repository:
pip install "prefix-safe-json-langchain @ git+https://github.com/canblmz1/prefix-safe-json#subdirectory=python"
If you use CutoffGuardMiddleware with LangChain v1 (langchain.agents.create_agent), add the middleware extra (or install langchain>=1.0.0):
pip install "prefix-safe-json-langchain[middleware] @ git+https://github.com/canblmz1/prefix-safe-json#subdirectory=python"
Requires Python >=3.10 and langchain-core>=0.3.0.
Usage
1. LangChain v1 create_agent middleware (CutoffGuardMiddleware)
from langchain.agents import create_agent
from langchain_openai import ChatOpenAI
from psj_langchain import CutoffGuardMiddleware
llm = ChatOpenAI(model="gpt-4o", streaming=True)
agent = create_agent(
model=llm,
tools=[write_file],
middleware=[CutoffGuardMiddleware()],
)
Works with both synchronous (agent.invoke(...)) and asynchronous (await agent.ainvoke(...)) runs via after_model and aafter_model.
2. LangGraph create_react_agent (post_model_cutoff_guard / make_post_model_hook)
from langchain_openai import ChatOpenAI
from langgraph.prebuilt import create_react_agent
from psj_langchain import post_model_cutoff_guard
llm = ChatOpenAI(model="gpt-4o", streaming=True)
agent = create_react_agent(
llm,
[write_file],
post_model_hook=post_model_cutoff_guard,
)
To customize allowed finish reasons:
from psj_langchain import DEFAULT_ALLOWED_FINISH_REASONS, make_post_model_hook
hook = make_post_model_hook(
allowed_finish_reasons=DEFAULT_ALLOWED_FINISH_REASONS | {"my_provider_done"}
)
3. Custom agent loops (guard_cut_off_tool_calls)
from psj_langchain import guard_cut_off_tool_calls
ai_message = guard_cut_off_tool_calls(llm_with_tools.invoke(messages))
# If ai_message was truncated or lacked a completion signal:
# ai_message.tool_calls == []
# ai_message.invalid_tool_calls == [InvalidToolCall(...)]
Fail-closed completion policy
guard_cut_off_tool_calls checks message.response_metadata whenever message.tool_calls is non-empty:
| Provider / signal | Passed (tool_calls kept) |
Blocked (moved to invalid_tool_calls) |
|---|---|---|
| OpenAI Chat Completions | finish_reason in {"tool_calls", "stop", "function_call"} |
"length", "content_filter", missing/None/"", unknown |
| OpenAI Responses API | status="completed" (and no incomplete_details) |
status="incomplete", incomplete_details truthy, status="in_progress", missing status & finish_reason |
| Anthropic | stop_reason in {"tool_use", "end_turn", "stop_sequence"} |
"max_tokens", "model_context_window_exceeded", missing |
| Google Gemini | finish_reason="STOP" (case-insensitive) |
"MAX_TOKENS", "MALFORMED_FUNCTION_CALL", "SAFETY", missing |
| AWS Bedrock / Ollama / Cohere | stopReason="tool_use" / done_reason="stop" / finish_reason="COMPLETE" |
"max_tokens" / done_reason="length" / done=False / missing |
Any unknown or missing completion signal is rejected by default (fail closed).
Limits (provider honesty)
This guard inspects LangChain's AIMessage.response_metadata rather than re-parsing raw HTTP/SSE frames. If a proxy or provider mislabels a truncated response with finish_reason="tool_calls" or status="completed", metadata-level inspection cannot detect that discrepancy. For raw wire-level SSE verification in Node.js/TypeScript, see the root package.
Running tests
From python/ (using the local .venv or an environment with pytest, langchain, langgraph, and langchain-openai installed):
cd python
.venv/Scripts/python.exe -m pytest -v # Windows
# .venv/bin/python -m pytest -v # macOS / Linux
The end-to-end tests in tests/test_e2e_cutoff.py start afb/suites/cutoff/server.py locally on an ephemeral port (no API key or external network access required during tests). Set CUTOFF_SERVER_PATH if the afb checkout lives outside the sibling scratchpad path.
License
Licensed under either of MIT or Apache-2.0, at your option.
Metadata
Release files for prefix-safe-json-langchain 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| prefix_safe_json_langchain-0.1.0.tar.gz | 16.5 kB | With provenance | Details for prefix_safe_json_langchain-0.1.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| prefix_safe_json_langchain-0.1.0-py3-none-any.whl | Python 3 | none | any | Details for prefix_safe_json_langchain-0.1.0-py3-none-any.whl |
Total release size: 27.5 kB
Release files / prefix_safe_json_langchain-0.1.0.tar.gz
| Download URL | prefix_safe_json_langchain-0.1.0.tar.gz |
|---|---|
| Size | 16.5 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
8e86f71338d457d34cd75bbe7bc98aa7330c07cd37d8c1c7feba3f722630ca79
|
|
BLAKE2b-256 checksum How to use checksums |
695bab09952397373c145577eb2120c16dce27a3dce1cad48341a3291c672be6
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logRelease files / prefix_safe_json_langchain-0.1.0-py3-none-any.whl
| Download URL | prefix_safe_json_langchain-0.1.0-py3-none-any.whl |
|---|---|
| Size | 11.1 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
90ea07b4923e36b77fb51dc19eeb788bdad7b1181d516fbf84eb89e47f097a9c
|
|
BLAKE2b-256 checksum How to use checksums |
be47261da3b7a359a973c68922a3f13ab2d6b7ec4df907488806f0827c737a3f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
Yes |
| Uploaded via |
twine/7.0.0 CPython/3.13.16
|
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logSecurity for prefix-safe-json-langchain 0.1.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
Full provenance
Both files in this release have been uploaded with provenance metadata.
Attestation for prefix_safe_json_langchain-0.1.0.tar.gz
PyPI Publish Attestation
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Dec 1, 2026.
Transparency logA note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.