<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Osama Malik, AI Agent Engineer]]></title><description><![CDATA[Osama Malik, AI Agent Engineer]]></description><link>https://osamamalik.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Thu, 26 Nov 2026 13:18:04 GMT</lastBuildDate><atom:link href="https://osamamalik.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[The layers I put in front of agents]]></title><description><![CDATA[Prompt injection defence in BleedStop is a stack of checks in front of the model, not one classifier score. The default check is a phrase list. A DeBERTa…]]></description><link>https://osamamalik.hashnode.dev/the-layers-i-put-in-front-of-agents</link><guid isPermaLink="true">https://osamamalik.hashnode.dev/the-layers-i-put-in-front-of-agents</guid><category><![CDATA[llm]]></category><category><![CDATA[AI]]></category><category><![CDATA[Security]]></category><category><![CDATA[agents]]></category><dc:creator><![CDATA[Osama Malik]]></dc:creator><pubDate>Thu, 19 Nov 2026 06:12:01 GMT</pubDate><content:encoded><![CDATA[<p>Prompt injection defence in BleedStop is a stack of checks in front of the model, not one classifier score. The default check is a phrase list. A DeBERTa classifier is a second stage I turn on, and on my held out set it caught 77.5% of injections at a 5% false positive rate.</p>
<p>Everything in this post is from <a href="https://osamamalik.me/bleedstop.html">the BleedStop case study</a> or from the public repo, <a href="https://github.com/usmamalik345/bleedstop">usmamalik345/bleedstop</a>, especially the README and <code>classifier/server.py</code>. The spend guard around these checks is in the <a href="https://osamamalik.me/blog/bleedstop-cost-and-security-guard.html">BleedStop deep dive</a>.</p>
<h2>What runs if I change nothing</h2>
<p>The phrase list is the default detector. The README says the ONNX sidecar runs only when <code>BLEEDSTOP_DETECTOR</code> is <code>classifier</code> or <code>both</code>. Until that flag is set, the live demo's server check is the phrase list. The model that runs in the browser on the demo page is a demo only. It does not protect the API.</p>
<p>On the phrase list, the honest held out number is weak. The README's agent guard row calls the held out set 22.5%, with 0% false positives, and calls that the honest number. A later note in the same README, phrase list only, cutoff 0.6, normaliser off, is the same rate as a fraction: 9 of 40 on the held out set (N=80, false positive rate 0 of 40). Dev, which the regex was tuned on, is 53 of 55 (N=112, benign 57, false positive rate 0 of 57), which is the 96.4% in the summary table. Lowering the cutoff to 0.3 did not raise dev recall and raised the dev false positive rate to 1 of 57, so the cutoff stayed at 0.6. Turning normalisation on did not raise dev recall. <code>BLEEDSTOP_NORMALIZE</code> stays off.</p>
<p>That is why I do not lead with 96.4%. That figure is the set the phrase list was tuned on.</p>
<h2>The second stage, when I turn it on</h2>
<p><code>classifier/server.py</code> serves <code>protectai/deberta-v3-base-prompt-injection-v2</code> with FastAPI. With <code>CLASSIFIER_URL</code> set, <code>/agent/precheck</code> and the MCP gateway run the regex first, then the classifier. There is also a small ONNX sidecar under <code>services/classifier/</code>, on CPU, the same 8 bit model the browser demo can load. The case study describes that browser build as a DeBERTa classifier quantized to 8 bit.</p>
<p>Mode <code>both</code> runs the phrase list first and sends only text the phrase list allowed on to <code>POST /classify</code>. The timeout is <code>BLEEDSTOP_CLASSIFIER_TIMEOUT_MS</code>, default 800. If the sidecar is down or slow, <code>BLEEDSTOP_CLASSIFIER_FAILMODE=open</code> is the default: keep the phrase list verdict, log a warning, and increment <code>bleedstop_classifier_errors_total</code>. <code>closed</code> turns that outage into a block. That is safer against injection, and it also means a dead sidecar stops those calls.</p>
<p>The README's comparison, which is the table I trust for this post, is:</p>
<table>
<thead>
<tr>
<th>Set</th>
<th>Phrase list recall / false positive rate</th>
<th>Classifier recall / false positive rate</th>
<th>Two stage recall / false positive rate</th>
</tr>
</thead>
<tbody><tr>
<td>deepset/prompt-injections, all 662</td>
<td>4.2% / 0%</td>
<td>41.4% / 1.0%</td>
<td>41.4% / 1.0%</td>
</tr>
<tr>
<td>BleedStop held out, 80</td>
<td>22.5% / 0%</td>
<td>77.5% / 5.0%</td>
<td>80.0% / 5.0%</td>
</tr>
<tr>
<td>BleedStop dev (phrase list tuned on it), 112</td>
<td>96.4% / 0%</td>
<td>83.6% / 7.0%</td>
<td>96.4% / 7.0%</td>
</tr>
</tbody></table>
<p>The 77.5% at a 5% false positive rate on the case study is this classifier row, held out, N=80. It is not the phrase list. Two stage recall on that set is 80.0% at the same 5.0% false positive rate, slightly higher than the classifier alone.</p>
<p>Latency in the README, on 4 CPU threads: phrase list p50 about 9 microseconds; classifier p50 about 46 to 49 ms, p99 55 to 132 ms. The README's caveats, which I share: deepset includes German rows and the model is English only; training overlap with public sets cannot be ruled out; the PINT row in the report is the public 8 row example file, not a PINT score; Llama Prompt Guard 2 is gated and I did not evaluate it.</p>
<p>The browser build is the same DeBERTa v2 model in the visitor's browser with onnxruntime-web, an 8 bit weight only build (256 MB, served from GitHub Pages, loaded only on click). Against the fp32 ONNX it gave identical labels on the held out, dev and deepset test sets. Single threaded inference was p50 245 ms in headless Chrome on the build box. That check is still a demo. Server side enforcement on the live demo remains the phrase list until <code>BLEEDSTOP_DETECTOR</code> is set. The README says free Docker hosting for the sidecar was not available, because Hugging Face Docker Spaces need a PRO plan, which is why the demo can run the model in the browser instead.</p>
<h2>The decision is still not the model</h2>
<p>A detector score does not spend money. <code>POST /decide</code> still returns ALLOW, LIMIT, CHALLENGE or DENY from the rules, and Redis still enforces the budget. The golden set on the case study is a different measurement from the injection table: 12,140 labeled requests, precision 100%, benign false positive rate 0.0%, recall 48.0%. The golden set and the rules share an author, so I do not call that a field result.</p>
<p>On the MCP path, the README says every <code>tools/call</code> goes through, in order: a definition pin (trust on first use, sha256 over name, description, inputSchema and annotations), a tool description poisoning scan, a per tenant Cedar policy in <code>config/mcp-policy.cedar</code>, the agent injection guard on the arguments, then the normal budget decision. Tool results are scanned for indirect injection. <code>MCP_GATEWAY_MODE=shadow</code> logs without blocking. The threat mapping is in <code>docs/THREAT-MODEL.md</code>.</p>
<p>For <code>npm run evals:mcp</code>, 70 hand written tool definitions, the README reports poisoning scan precision 100%, recall 80% (20 of 25), false positive rate 0% (0 of 45). Rug pull detection caught 180 of 180 mutations, with 0 false alarms on 45 unchanged lists. Added latency per <code>tools/call</code> over HTTP, n=2000, was p50 2.21 ms, p95 2.84 ms, p99 3.89 ms. The misses are the 5 of 25 poisonings the README calls subtle and polite, with no trigger phrase. I wrote that eval set, so I treat the recall as optimistic. The README says the same.</p>
<h2>What I will not claim</h2>
<ul>
<li>I will not quote 96.4% as held out performance. That is the dev set the phrase list was tuned on.</li>
<li>I will not quote 77.5% as the phrase list. That is the classifier, on the held out set of 80, at a 5% false positive rate.</li>
<li>I will not say the browser model protects the API. It does not.</li>
<li>I will not say the server classifier is on in the public demo. It is off until <code>BLEEDSTOP_DETECTOR</code> is set.</li>
<li>Fail open means a dead sidecar keeps the phrase list verdict. If you need a dead sidecar to block, that is the closed mode, and it will also block when the sidecar is simply down.</li>
</ul>
<p><a href="https://github.com/usmamalik345/bleedstop">BleedStop repo</a> · <a href="https://osamamalik.me/bleedstop.html">Case study</a> · <a href="https://osamamalik.me/blog/bleedstop-cost-and-security-guard.html">Cost guard deep dive</a> · <a href="https://osamamalik.me/hire/">Hire me</a></p>
<p>Originally published at <a href="https://osamamalik.me/blog/prompt-injection-defence.html">https://osamamalik.me/blog/prompt-injection-defence.html</a></p>
]]></content:encoded></item><item><title><![CDATA[Fixing function call timeouts in Pipecat]]></title><description><![CDATA[Pipecat pull request 5760 keeps a function call timeout armed across intermediate results. I wrote it, and it was merged on 15 Sep 2026. Only a final…]]></description><link>https://osamamalik.hashnode.dev/fixing-function-call-timeouts-in-pipecat</link><guid isPermaLink="true">https://osamamalik.hashnode.dev/fixing-function-call-timeouts-in-pipecat</guid><category><![CDATA[Python]]></category><category><![CDATA[AI]]></category><category><![CDATA[agents]]></category><category><![CDATA[Open Source]]></category><dc:creator><![CDATA[Osama Malik]]></dc:creator><pubDate>Wed, 18 Nov 2026 06:11:25 GMT</pubDate><content:encoded><![CDATA[<p>Pipecat pull request 5760 keeps a function call timeout armed across intermediate results. I wrote it, and it was merged on 15 Sep 2026. Only a final result clears the deadline.</p>
<p>The pull request is <a href="https://github.com/pipecat-ai/pipecat/pull/5760">pipecat-ai/pipecat #5760</a>. Its title is <code>fix(llm): keep function-call timeout armed across intermediate results</code>. It closes issue <a href="https://github.com/pipecat-ai/pipecat/issues/5481">#5481</a>. I did not start Pipecat. This is one fix in the framework.</p>
<h2>What was broken</h2>
<p>Pipecat can limit how long a function call is allowed to run. That limit is the per tool <code>timeout_secs</code>, or the global <code>function_call_timeout_secs</code> when the tool does not set its own. When the handler reports a result, the service runs <code>function_call_result_callback</code>.</p>
<p>Before this change, that callback cancelled the timeout task for every result, including a result marked <code>FunctionCallResultProperties(is_final=False)</code>. An intermediate update is how a tool reports progress while it is still working. Cancelling the timeout there meant a progress report disarmed the deadline. A tool could say "working", then hang, and the timeout would not fire.</p>
<p>The changelog line that landed with the pull request says the same thing: an async tool that reported progress no longer cancels its own deadline, and only a final result clears it.</p>
<h2>What I changed</h2>
<p>The cancel moved inside the <code>is_final</code> branch in <code>src/pipecat/services/llm_service.py</code>. A final result still marks the call settled and still cancels the timeout task if it is running. An intermediate result leaves the task armed. The deadline is not restarted either. It still covers the handler's whole execution, measured from when the call started.</p>
<p>I updated the docs on <code>register_function</code> and <code>register_direct_function</code> so they say this. A call that runs past the deadline is still cancelled: the handler is thrown <code>asyncio.CancelledError</code>, the call is settled as cancelled, and inference runs so the model can report that it did not complete.</p>
<p>The pull request says an earlier attempt, <a href="https://github.com/pipecat-ai/pipecat/pull/5491">#5491</a>, was closed without review, and that 5760 reopens that approach against current main. I am taking that from the pull request text.</p>
<h2>What the tests check</h2>
<p>The new coverage is in <code>tests/test_llm_service.py</code>, class <code>TestFunctionCallTimeout</code>. The pull request's test plan is <code>uv run pytest tests/test_llm_service.py::TestFunctionCallTimeout</code>. I am describing the tests that are in the merged diff. I have not rerun them for this post.</p>
<h3>An intermediate update must not disarm the deadline</h3>
<p><code>test_intermediate_result_does_not_disarm_the_deadline</code> registers a tool that first calls the result callback with "working" and <code>is_final=False</code>, then sleeps long enough to pass <code>timeout_secs</code>. The assertions in the diff are:</p>
<ul>
<li>The tool's later side effect does not run.</li>
<li>The handler observes <code>CancelledError</code> for that call.</li>
<li>The frames are <code>FunctionCallsStartedFrame</code>, <code>FunctionCallInProgressFrame</code>, a <code>FunctionCallResultFrame</code> whose properties are not final, then <code>FunctionCallCancelFrame</code>.</li>
<li>The cancel frame has <code>run_llm</code> set.</li>
</ul>
<h3>A hanging tool with no update still times out</h3>
<p><code>test_a_hanging_async_tool_times_out_without_any_update</code> is the control. The tool only sleeps, then would return a final result. It never gets there. The frames are the started frame, the in progress frame, and the cancel frame. There is no result frame, because nothing was reported.</p>
<p>The diff also adds <code>changelog/5760.fixed.md</code>. GitHub records 3 files changed on the pull request.</p>
<h2>What I am not claiming</h2>
<ul>
<li>I am not a Pipecat maintainer. The pull request was merged on 15 Sep 2026. The merge is on the pull request page.</li>
<li>I am not describing review comments I did not quote here. The behavior above is the merged diff and the pull request body.</li>
<li>This does not change LiveKit. My LiveKit Agents pull request, <a href="https://github.com/livekit/agents/pull/7186">#7186</a>, is a different timeout, on <code>EndCallTool</code>, and it is still open. See the <a href="https://osamamalik.me/open-source.html">open source page</a>.</li>
</ul>
<p>The same page has the merged Genkit and Strands pull requests, which are not about this timeout.</p>
<p><a href="https://github.com/pipecat-ai/pipecat/pull/5760">Pull request 5760</a>
<a href="https://osamamalik.me/open-source.html">All four pull requests</a>
<a href="https://osamamalik.me/portfolio-agent/case-study.html">Agent Receptionist</a></p>
<p>Originally published at <a href="https://osamamalik.me/blog/pipecat-5760-function-call-timeout.html">https://osamamalik.me/blog/pipecat-5760-function-call-timeout.html</a></p>
]]></content:encoded></item><item><title><![CDATA[How I built BleedStop]]></title><description><![CDATA[BleedStop is a cost and security guard I built for LLM, SMS and payment APIs. An app calls POST /decide before it spends, and BleedStop answers ALLOW…]]></description><link>https://osamamalik.hashnode.dev/how-i-built-bleedstop</link><guid isPermaLink="true">https://osamamalik.hashnode.dev/how-i-built-bleedstop</guid><category><![CDATA[AI]]></category><category><![CDATA[agents]]></category><category><![CDATA[llm]]></category><category><![CDATA[Security]]></category><dc:creator><![CDATA[Osama Malik]]></dc:creator><pubDate>Tue, 17 Nov 2026 12:12:58 GMT</pubDate><content:encoded><![CDATA[<p>BleedStop is a cost and security guard I built for LLM, SMS and payment APIs. An app calls <code>POST /decide</code> before it spends, and BleedStop answers ALLOW, LIMIT, CHALLENGE or DENY from deterministic per tenant rules.</p>
<p>This is the longer note behind the <a href="https://osamamalik.me/bleedstop.html">case study</a>. The code is in <a href="https://github.com/usmamalik345/bleedstop">usmamalik345/bleedstop</a>. The stack on the case study is Node.js, Python, Postgres, Redis and Kubernetes. The numbers below are the ones I measured, or the ones the repository README already publishes. I am not adding a customer, a production cluster, or a savings figure that those pages do not state.</p>
<h2>Why the decision sits in front of the spend</h2>
<p>Once an agent can call tools and paid APIs, one prompt injection or one runaway loop can leak data or burn a budget. I mapped that to OWASP LLM10, Unbounded Consumption. BleedStop is the control plane in front of the spend. Rules are set per tenant. Budgets are enforced atomically across instances through Redis.</p>
<p>The hot path is deterministic. The repository README says agents only explain, and they are not the thing that denies a call. That is the design I want: a hanging model, or a poisoned prompt, should not be what decides whether money moves.</p>
<p>A call looks like this. The app, or the Node SDK Express middleware, asks <code>POST /decide</code>. BleedStop checks the request, including the phrase list and, when I turn it on, the classifier described in the <a href="https://osamamalik.me/blog/prompt-injection-defence.html">prompt injection post</a>. It checks the budget. It writes the decision. The caller gets ALLOW, LIMIT, CHALLENGE or DENY.</p>
<h2>Budgets, the audit log, and the deploy</h2>
<p>Redis holds the budget so several instances share one ceiling. On the case study, a correctness test of 2,000 concurrent calls against a $5 ceiling on 3 instances overspent by $0.000. The same shape behind a load balancer did 6,291 decisions per second, with p99 at 31.9 ms.</p>
<p>Every decision is written to a Postgres audit table. A trigger blocks UPDATE and DELETE, so a decision can be reviewed later and cannot be edited in place.</p>
<p>The Docker Compose stack is 3 API replicas, Redis, Postgres and nginx. The Helm chart adds readiness and liveness probes, a PodDisruptionBudget, an HPA and graceful drain. Around that I have Prometheus metrics, Grafana dashboards, alert rules, GitHub Actions CI, a Node SDK, a Python SDK, multi tenant YAML policy, and OpenTelemetry.</p>
<p>There is also an OpenAI compatible proxy in the repo. <code>POST /v1/chat/completions</code> reserves budget for the prompt plus a capped output. The README says DENY comes back as HTTP 429 and CHALLENGE as HTTP 403, in an OpenAI error shape, and LIMIT downgrades to the small model. The output cap is the smallest of the requested cap, <code>OPENAI_PROXY_MAX_OUTPUT_TOKENS</code> (1024), and the remaining budget. The README says that cap is enforced mid stream even if the upstream ignores <code>max_tokens</code>, and that reservations are committed with actual usage.</p>
<h2>What I measured</h2>
<p>All of the case study numbers were measured by me on one shared 8 vCPU Linux machine. The load generator, the load balancer and the services share that hardware, so I treat the absolute rates as a lower bound for a real cluster. Raw results are in the repository.</p>
<table>
<thead>
<tr>
<th>Test</th>
<th>Result</th>
</tr>
</thead>
<tbody><tr>
<td>Docker Compose stack (3 API replicas, Redis, Postgres, nginx), one 8 vCPU machine</td>
<td>5,433 decisions per second, p99 36.2 ms, 0 failed requests out of 60,000</td>
</tr>
<tr>
<td>3 instances behind a load balancer with Redis atomic budgets</td>
<td>6,291 decisions per second, p99 31.9 ms, $0.000 overspend against a $5 ceiling</td>
</tr>
<tr>
<td>Kubernetes rolling restart of 6 pods under load</td>
<td>0 failed requests out of 287,403. The README also records p99 33.2 ms for this run.</td>
</tr>
<tr>
<td>Postgres stopped for about 7 seconds under load</td>
<td>86,071 requests, 0 failed, 0 ledger rows dropped</td>
</tr>
<tr>
<td>Golden set of 12,140 labeled requests</td>
<td>Precision 100%, benign false positive rate 0.0%, recall 48.0%</td>
</tr>
<tr>
<td>Capped request against a live model API</td>
<td>64 output tokens instead of 2,618 (97.6% fewer)</td>
</tr>
</tbody></table>
<p>The README gives more detail on that capped request, and I am using it because it is the same comparison. It was a small run on Groq's free tier, model <code>openai/gpt-oss-20b</code>, a streaming request for 1500 words, with a 64 token cap. Groq honoured the rewritten <code>max_tokens</code>, so BleedStop's own mid stream cut was not what stopped it. The README's reconciled cost at the policy rate fell from $0.0271 to $0.00151 per request. The actual bill was $0, because the tier was free. Over 20 pairs of calls that did not stream, direct p50 was 245.8 ms and the path through BleedStop was 234.2 ms. The README says the proxy overhead was not measurable over internet noise at that size.</p>
<p>The overhead estimate the README does stand behind is the mock upstream: <code>npm run bench:openai</code>, n=1000 calls that do not stream, added latency p50 1.53 ms and p99 1.86 ms. A separate mock flood in that same section, 40 requests for 20,000 words against an upstream that ignores <code>max_tokens</code>, cut 40 of 40 streams. At the README's policy rate of $0.01 per 1,000 tokens, with tokens approximated as characters divided by 4, that is $10.70 unprotected and $0.41 through the proxy. I am not calling that a customer saving. It is a mock.</p>
<p>The README's attack suite row, which I did not put on the case study, says a 400,000 character token flood was 100% blocked, a shared device farm 97%, a retry storm 94%, and normal users 0% blocked. The summary row does not give the sample size, so I am not inventing one. The file it points at is <code>results/</code> in the repo.</p>
<h2>The public demo is not that measurement</h2>
<p>The live demo is <a href="https://bleedstop-demo.vercel.app">bleedstop-demo.vercel.app</a>. The README is explicit: it runs on Vercel Hobby functions, in memory, with no Redis and no Postgres. State is per function instance. Budgets, velocity windows and rate limits can reset on a cold start or when another instance handles the next call. The $5 cluster ceiling is not reliably enforced there. The measured numbers above come from the Compose and Kubernetes stack with Redis.</p>
<p>The README documents a demo key, <code>demo-public-key</code>, tenant <code>demo</code>, and this call. It says 500 estimated tokens come back ALLOW, and 400,000 estimated tokens come back DENY, against an unpaid token cap of 32,000.</p>
<pre><code class="language-bash">curl -s -X POST https://bleedstop-demo.vercel.app/decide \
  -H "Content-Type: application/json" -H "X-API-Key: demo-public-key" \
  -d '{"actorId":"demo-user-1","action":"llm.call","paid":false,"estimatedTokens":500,"signals":{"deviceFingerprint":"fp-demo-1"}}'
</code></pre>
<p>There is a project site at <a href="https://usmamalik345.github.io/bleedstop/">usmamalik345.github.io/bleedstop</a>. The browser classifier on the demo does not protect the API. I cover that in the <a href="https://osamamalik.me/blog/prompt-injection-defence.html">defence post</a>.</p>
<h2>Bugs that showed up under load</h2>
<p>Running the stack found problems unit tests did not. The case study says I found and fixed eight, and kept the evidence in the repository. Four of them are:</p>
<ul>
<li>Pods crash looping after loading 1.09 million rows at boot. Hydration is now skipped when Redis is authoritative, and otherwise capped to the top 50,000 rows by spend.</li>
<li>A Postgres writer that hung for good when the database went down. Connect and query timeouts fixed it.</li>
<li>Unhandled connection errors that crashed replicas when Postgres was stopped.</li>
<li>State kept per process, which split abuse signals across replicas behind a round robin load balancer. It now lives in Redis, and results match a single instance.</li>
</ul>
<p>I am not naming the other four here, because the case study does not name them and I am not going to reconstruct them from memory.</p>
<h2>What I will not claim</h2>
<ul>
<li>The golden set and the rules share an author, so the accuracy numbers are not field results. Recall on that set is 48.0%. Precision is 100%, with no benign false positives.</li>
<li>The case study lists these as not measured there: NetworkPolicy enforcement, multi node or cloud clusters, Postgres high availability, and real provider latency or pricing as a benchmark. The Groq run above is one small free tier check in the README, not that missing benchmark.</li>
<li>The Vercel demo is not the cluster that produced 5,433 decisions per second or the rolling restart result.</li>
<li>I do not have a production customer figure for money saved. Where the README prints a dollar amount, it is a policy rate or a local sample, and I have said which.</li>
</ul>
<p><a href="https://github.com/usmamalik345/bleedstop">Source and results</a><br /><a href="https://osamamalik.me/bleedstop.html">Case study</a><br /><a href="https://osamamalik.me/blog/prompt-injection-defence.html">Prompt injection layers</a><br /><a href="https://osamamalik.me/hire/">Hire me</a></p>
<p>Originally published at <a href="https://osamamalik.me/blog/bleedstop-cost-and-security-guard.html">https://osamamalik.me/blog/bleedstop-cost-and-security-guard.html</a>.</p>
]]></content:encoded></item></channel></rss>