Skip to content
Merged
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
8 changes: 8 additions & 0 deletions packages/uipath-codex-sdk/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,14 @@ The tenant's Claude, Gemini and Llama models do not. `uipath list-models`
lists what the tenant serves; pass the name as the gateway reports it
(`gpt-5-mini-2025-08-07`, not `gpt-5-mini`).

The gateway can serve a model from several deployments, and a reasoning
model's follow-up request fails (400 `invalid_encrypted_content`) when it lands
on a deployment other than the one that produced the reasoning Codex replays.
Every model call therefore carries the gateway's sticky-session headers, which
keep a run on one deployment. `uipath-llm-client` sends them for a
conversation (with the conversation id) and for a job (with the job key); for
a local run, the runtime's proxy sends them with Codex's thread id.

Verified with every sample: `gpt-5.6-terra`. Verified with the quickstart and
durable process samples: `gpt-6.1-sol` and `gpt-5-mini-2025-08-07`. Smaller
models follow tool instructions less reliably and can spend extra turns (for
Expand Down
8 changes: 4 additions & 4 deletions packages/uipath-codex-sdk/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "uipath-codex-sdk"
version = "0.1.0"
version = "0.1.1"
description = "Python SDK that enables developers to build and deploy OpenAI Codex SDK agents to the UiPath Cloud Platform"
readme = "README.md"
requires-python = ">=3.11"
Expand All @@ -9,10 +9,10 @@ dependencies = [
"aiohttp>=3.9.0",
"aiosqlite>=0.19.0",
"httpx>=0.27.0",
"uipath>=2.14.41, <2.15.0",
"uipath-platform>=0.2.34",
"uipath>=2.15.1, <2.16.0",
"uipath-platform>=0.3.4",
"uipath-runtime>=0.13.0, <0.14.0",
"uipath-llm-client[openai]>=1.17.1, <1.19.0",
"uipath-llm-client[openai]>=1.23.0, <1.24.0",
]
classifiers = [
"Intended Audience :: Developers",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,17 @@
import logging
import socket
import time
import uuid
from typing import Any, Protocol

import httpx
from aiohttp import web
from aiohttp.client_exceptions import ClientConnectionResetError
from opentelemetry.context import Context
from uipath.llm_client.settings.constants import (
HEADER_LLMGATEWAY_STICKY_SESSION,
HEADER_LLMGATEWAY_STICKY_SESSION_TRANSACTION_ID,
)

from ..telemetry import (
ModelCallSpan,
Expand All @@ -44,6 +49,12 @@
#: Path the durable tool host (an MCP endpoint) is mounted on.
MCP_PATH = "/mcp"

#: The gateway accepts a sticky-session transaction id of up to 128 characters.
MAX_TRANSACTION_ID_LENGTH = 128
#: Headers codex (0.161) puts its thread id in on every Responses request. The
#: id survives a suspend/resume, since the resumed run reopens the same thread.
CODEX_THREAD_ID_HEADERS = ("session-id", "thread-id")


class MountedHandler(Protocol):
"""An extra endpoint served next to the model routes (the tool host)."""
Expand Down Expand Up @@ -75,6 +86,8 @@ def __init__(
trace_context: Context | None = None,
) -> None:
self._upstream = upstream
# Sticky-session id for a request that carries no Codex thread id.
self._fallback_transaction_id = uuid.uuid4().hex
self._trace_context = trace_context
self._api_key = api_key.encode()
self._default_model = default_model
Expand Down Expand Up @@ -202,7 +215,11 @@ async def _relay_responses(self, request: web.Request) -> web.StreamResponse:

client = await self._upstream.get(model)
body = json.dumps(payload).encode()
headers = {"content-type": "application/json", **span.trace_headers()}
headers = {
"content-type": "application/json",
**span.trace_headers(),
**self._sticky_session_headers(request, client),
}
try:
if payload.get("stream"):
response, completed = await self._forward_stream(
Expand All @@ -221,6 +238,37 @@ async def _relay_responses(self, request: web.Request) -> web.StreamResponse:
)
return response

def _sticky_session_headers(
self, request: web.Request, client: httpx.AsyncClient
) -> dict[str, str]:
"""Sticky-session headers for a run uipath-llm-client did not pin.

The LLM Gateway can serve a model from several deployments. Codex calls
the Responses API with ``store: false`` and replays its encrypted
reasoning on each follow-up request, and only the deployment that
produced it can decrypt it: a follow-up served by another deployment
fails with 400 ``invalid_encrypted_content``. The gateway serves the
requests that carry the same sticky-session transaction id from one
deployment.

uipath-llm-client puts the headers on the upstream client when the run
has a conversation id or a job key, and then nothing is added here. A
local run has neither, so the proxy sends them, with Codex's thread id
as the transaction id (an id of its own if Codex sent none).
"""
if HEADER_LLMGATEWAY_STICKY_SESSION in client.headers:
return {}
thread_ids = (
request.headers.get(name, "").strip() for name in CODEX_THREAD_ID_HEADERS
)
transaction_id = next(filter(None, thread_ids), self._fallback_transaction_id)
return {
HEADER_LLMGATEWAY_STICKY_SESSION: "true",
HEADER_LLMGATEWAY_STICKY_SESSION_TRANSACTION_ID: transaction_id[
:MAX_TRANSACTION_ID_LENGTH
],
}

# --- forwarding -------------------------------------------------------

async def _forward_unary(
Expand Down
40 changes: 40 additions & 0 deletions packages/uipath-codex-sdk/tests/contract/test_durable_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,43 @@ def test_c7_turn_interrupt_pollutes_history(cenv: ContractEnv, evidence: Evidenc
assert aborted_outputs or marker, (
f"turn/interrupt left a clean history -> SIGKILL would NOT be necessary\n{evidence.dump()}"
)


# ---------------------------------------------------------------------------
# C8
# ---------------------------------------------------------------------------
def test_c8_model_requests_carry_the_thread_id(cenv: ContractEnv, evidence: Evidence):
"""C8: every Responses request carries the thread id in the ``session-id``
and ``thread-id`` headers, and a thread resumed in a new app-server keeps
sending the same id (the gateway proxy keeps a local run's model calls on
one LLM Gateway deployment with it)."""
from uipath_codex_sdk.runtime.gateway.proxy import CODEX_THREAD_ID_HEADERS

cid = new_call_id()
s, app2, host2, home2, cwd2 = suspend_and_restore(cenv, evidence, cid)
n_before = len(cenv.mock.snapshot())
assert n_before > 0, evidence.dump()
th2 = app2.thread_resume(s.thread_id, cwd=cwd2)
app2.raw(
"thread/inject_items",
{
"threadId": s.thread_id,
"items": [
{"type": "function_call_output", "call_id": cid, "output": OUR_OUTPUT}
],
},
)
handle = th2.turn("continue")
reqs = cenv.mock.wait_for_requests(n_before + 1, 30)
assert len(reqs) > n_before, (
f"no model request after turn/start\n{app2.stderr_tail()}\n{evidence.dump()}"
)
handle.run()

sent = [{k.lower(): v for k, v in r.headers.items()} for r in cenv.mock.snapshot()]
evidence.add(
"thread id headers per model request (before resume, after resume)",
([tuple(h.get(n) for n in CODEX_THREAD_ID_HEADERS) for h in sent], n_before),
)
for name in CODEX_THREAD_ID_HEADERS:
assert [h.get(name) for h in sent] == [s.thread_id] * len(sent), evidence.dump()
146 changes: 146 additions & 0 deletions packages/uipath-codex-sdk/tests/test_gateway_proxy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
"""Gateway proxy: LLM Gateway sticky-session headers on the upstream calls.

uipath-llm-client puts the headers on the upstream client for a job or a
conversation. The proxy sends them itself for a run that has neither.
"""

from __future__ import annotations

import json
from typing import Any

import httpx
import pytest
from aiohttp import ClientSession
from uipath.llm_client.settings.constants import (
HEADER_LLMGATEWAY_STICKY_SESSION as STICKY_SESSION,
)
from uipath.llm_client.settings.constants import (
HEADER_LLMGATEWAY_STICKY_SESSION_TRANSACTION_ID as TRANSACTION_ID,
)

from uipath_codex_sdk.runtime.gateway.proxy import CodexGatewayProxy

API_KEY = "secret"
COMPLETED = {"id": "resp_1", "object": "response", "status": "completed"}
SSE = (
b"event: response.completed\n"
b'data: {"type":"response.completed","response":{"id":"resp_1"}}\n\n'
)


class RecordingUpstream:
"""Stands in for ``UpstreamRegistry``; records the headers the gateway gets.

Args:
client_headers: Default headers of the upstream client, as
uipath-llm-client sets them (the sticky-session ones for a job).
"""

def __init__(self, client_headers: dict[str, str] | None = None) -> None:
self.headers: list[httpx.Headers] = []
self._client = httpx.AsyncClient(
base_url="http://gateway.test",
headers=client_headers,
transport=httpx.MockTransport(self._respond),
)

def _respond(self, request: httpx.Request) -> httpx.Response:
self.headers.append(request.headers)
if json.loads(request.content).get("stream"):
return httpx.Response(
200, content=SSE, headers={"content-type": "text/event-stream"}
)
return httpx.Response(200, json=COMPLETED)

async def get(self, model: str) -> httpx.AsyncClient:
return self._client

async def aclose(self) -> None:
await self._client.aclose()

def transaction_ids(self) -> list[str | None]:
return [h.get(TRANSACTION_ID) for h in self.headers]


async def _relay(
upstream: RecordingUpstream,
bodies: list[dict[str, Any]],
headers: dict[str, str] | None = None,
) -> None:
"""Post ``bodies`` to a proxy as Codex would, with Codex's ``headers``."""
proxy = CodexGatewayProxy(
upstream=upstream, # type: ignore[arg-type]
api_key=API_KEY,
default_model="m",
)
await proxy.start()
try:
async with ClientSession() as session:
for body in bodies:
async with session.post(
f"http://127.0.0.1:{proxy.port}/v1/responses",
json=body,
headers={"Authorization": f"Bearer {API_KEY}", **(headers or {})},
) as response:
assert response.status == 200
await response.read()
finally:
await proxy.stop()
await upstream.aclose()


@pytest.mark.parametrize("stream", [False, True], ids=["unary", "stream"])
async def test_unpinned_run_is_pinned_with_the_codex_thread_id(stream: bool) -> None:
upstream = RecordingUpstream()
await _relay(
upstream,
[{"input": "hi", "stream": stream}] * 2,
headers={"session-id": "thread-1", "thread-id": "thread-1"},
)
assert len(upstream.headers) == 2
for headers in upstream.headers:
assert headers[STICKY_SESSION] == "true"
assert headers[TRANSACTION_ID] == "thread-1"


@pytest.mark.parametrize(
("codex_headers", "expected"),
[
({"session-id": " thread-1 "}, "thread-1"),
({"thread-id": "thread-2"}, "thread-2"),
({"session-id": " ", "thread-id": "thread-2"}, "thread-2"),
({"session-id": "x" * 200}, "x" * 128),
],
ids=["trimmed", "thread-id", "blank-session-id", "capped"],
)
async def test_codex_thread_id_header_forms(
codex_headers: dict[str, str], expected: str
) -> None:
upstream = RecordingUpstream()
await _relay(upstream, [{"input": "hi"}], headers=codex_headers)
assert upstream.transaction_ids() == [expected]


async def test_llm_client_sticky_headers_are_left_alone() -> None:
# A job: uipath-llm-client put the headers, with the job key, on the client.
upstream = RecordingUpstream({STICKY_SESSION: "true", TRANSACTION_ID: "job-1"})
await _relay(
upstream,
[{"input": "a"}, {"input": "b", "stream": True}],
headers={"session-id": "thread-1"},
)
assert upstream.transaction_ids() == ["job-1", "job-1"]
assert [h[STICKY_SESSION] for h in upstream.headers] == ["true", "true"]


async def test_without_a_codex_thread_id_the_proxy_uses_one_id_of_its_own() -> None:
upstream = RecordingUpstream()
await _relay(upstream, [{"input": "a"}, {"input": "b", "stream": True}])
first, second = upstream.transaction_ids()
assert first and first == second
assert [h[STICKY_SESSION] for h in upstream.headers] == ["true", "true"]

other = RecordingUpstream()
await _relay(other, [{"input": "a"}])
assert other.transaction_ids() != [first]
Loading
Loading