diff --git a/docs/guides/openai-compatible-agent-api.md b/docs/guides/openai-compatible-agent-api.md index a258d8d39..9d86de551 100644 --- a/docs/guides/openai-compatible-agent-api.md +++ b/docs/guides/openai-compatible-agent-api.md @@ -57,7 +57,7 @@ curl http://127.0.0.1:8900/v1/chat/completions \ - If `/v1/chat/completions` fails, test `nanobot agent -m "Hello!"` first. - If remote clients cannot connect, check `api.host`, `api.port`, firewall, and API key configuration. -- If sessions mix together, pass unique `session_id` values. +- If sessions mix together, pass a distinct, stable `session_id` for each conversation. Requests without `session_id` all share the `api:default` session. See [session behavior](../openai-api.md#sessions-failures-and-retries) before changing existing IDs. ## Related nanobot docs diff --git a/docs/openai-api.md b/docs/openai-api.md index 829d72669..44f59ce01 100644 --- a/docs/openai-api.md +++ b/docs/openai-api.md @@ -44,7 +44,7 @@ curl http://127.0.0.1:8900/v1/models \ ## Behavior -- Conversation history: pass `"session_id"` in the request body to select a conversation; omit for a shared default session (`api:default`). This is not user authentication or a separate workspace. +- Conversation history: pass `"session_id"` in the request body to select a conversation; omit for a shared default session (`api:default`). The request's chat route matches that session for both JSON replies and SSE. This is not user authentication or a separate workspace. - Single-message input: each request must contain exactly one `user` message - Fixed model: omit `model`, or pass the same model shown by `/v1/models` - Streaming: set `stream=true` to receive Server-Sent Events (`text/event-stream`) with OpenAI-compatible delta chunks, terminated by `data: [DONE]`; omit or set `stream=false` for a single JSON response @@ -59,6 +59,8 @@ The API can start before provider/model setup is complete. Health checks remain All callers use the same configured API key, agent, workspace, long-term memory, and tool permissions. Any authorized caller can select any `session_id`; the server does not bind it to a user identity. A distinct ID separates conversation history, not access to files or memory. Use [separate instances](./multiple-instances.md) for separate trust boundaries, or enforce user-to-session authorization in your own application before forwarding requests. +Send a stable, non-empty string ID for each conversation. JSON IDs retain surrounding spaces, so `"chat-a"` and `" chat-a "` select different histories. Multipart IDs retain their existing whitespace trimming. Omitted or empty IDs use `api:default`, as does the explicit ID `"default"`. Existing session keys and stored histories are unchanged; no migration is required. + Requests with the same session ID are serialized within one API process. Different sessions can run concurrently and share workspace files; session locking does not make file changes transactional. Send one turn at a time per conversation when ordering matters. | Failure | Client-visible result | diff --git a/nanobot/api/server.py b/nanobot/api/server.py index d15d5faad..a901b6091 100644 --- a/nanobot/api/server.py +++ b/nanobot/api/server.py @@ -1,7 +1,8 @@ -"""OpenAI-compatible HTTP API server for a fixed nanobot session. +"""OpenAI-compatible HTTP API server for nanobot sessions. Provides /v1/chat/completions and /v1/models endpoints. -All requests route to a single persistent API session. +Requests without ``session_id`` share one persistent default session; each +``session_id`` owns an isolated session with its own chat route. """ from __future__ import annotations @@ -316,6 +317,8 @@ async def handle_chat_completions(request: web.Request) -> web.Response | web.St return _error_json(400, f"Only configured model '{model_name}' is available") session_key = f"api:{session_id}" if session_id else API_SESSION_KEY + # Keep the existing history identity; derive its route without normalizing the ID. + chat_id = session_key.removeprefix("api:") session_locks: dict[str, asyncio.Lock] = request.app[_SESSION_LOCKS_KEY] session_lock = session_locks.setdefault(session_key, asyncio.Lock()) @@ -359,7 +362,7 @@ async def handle_chat_completions(request: web.Request) -> web.Response | web.St media=media_paths if media_paths else None, session_key=session_key, channel="api", - chat_id=API_CHAT_ID, + chat_id=chat_id, on_stream=_on_stream, on_stream_end=_on_stream_end, ) @@ -403,7 +406,7 @@ async def handle_chat_completions(request: web.Request) -> web.Response | web.St media=media_paths if media_paths else None, session_key=session_key, channel="api", - chat_id=API_CHAT_ID, + chat_id=chat_id, hooks=[usage_capture], ) response_text = _response_text(response) diff --git a/tests/test_api_attachment.py b/tests/test_api_attachment.py index 7b9df945c..5154620b1 100644 --- a/tests/test_api_attachment.py +++ b/tests/test_api_attachment.py @@ -322,7 +322,12 @@ async def test_multipart_defaults_text_when_missing(aiohttp_client, mock_agent, @pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed") @pytest.mark.asyncio -async def test_multipart_with_session_id(aiohttp_client, mock_agent, tmp_path) -> None: +@pytest.mark.parametrize(("session_id", "chat_id"), [ + ("my-session", "my-session"), (" my-session ", "my-session"), (" ", "default"), +]) +async def test_multipart_with_session_id( + aiohttp_client, mock_agent, tmp_path, session_id, chat_id, +) -> None: """Multipart upload with session_id uses custom session key.""" import os original_cwd = os.getcwd() @@ -338,11 +343,12 @@ async def test_multipart_with_session_id(aiohttp_client, mock_agent, tmp_path) - resp = await client.post( "/v1/chat/completions", headers=AUTH_HEADERS, - data={"message": "hello", "session_id": "my-session", "files": data}, + data={"message": "hello", "session_id": session_id, "files": data}, ) assert resp.status == 200 call_kwargs = mock_agent.process_direct.call_args.kwargs - assert call_kwargs["session_key"] == "api:my-session" + assert call_kwargs["session_key"] == f"api:{chat_id}" + assert call_kwargs["chat_id"] == chat_id finally: os.chdir(original_cwd) diff --git a/tests/test_openai_api.py b/tests/test_openai_api.py index a3c202982..833e110a1 100644 --- a/tests/test_openai_api.py +++ b/tests/test_openai_api.py @@ -387,6 +387,46 @@ async def test_followup_requests_share_same_session_key(aiohttp_client) -> None: assert call_log == [API_SESSION_KEY, API_SESSION_KEY] +@pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed") +@pytest.mark.asyncio +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize(("session_id", "chat_id"), [ + ("chat-a", "chat-a"), + (" chat-a ", " chat-a "), + (" ", " "), + ("api:chat-a", "api:chat-a"), + ("会话:a", "会话:a"), + ("default", "default"), + (None, "default"), + ("", "default"), + (0, "default"), + (42, "42"), + ({"id": 1}, "{'id': 1}"), +]) +async def test_session_route_preserves_existing_json_identity( + aiohttp_client, mock_agent, session_id, chat_id, stream, +) -> None: + """Routing must not normalize or reject previously accepted session IDs.""" + app = create_app(mock_agent, model_name="m", api_key=API_KEY) + client = await aiohttp_client(app) + + resp = await client.post( + "/v1/chat/completions", + headers=AUTH_HEADERS, + json={ + "messages": [{"role": "user", "content": "hi"}], + "session_id": session_id, "stream": stream, + }, + ) + + assert resp.status == 200 + await resp.read() + call_kwargs = mock_agent.process_direct.call_args.kwargs + assert call_kwargs["session_key"] == f"api:{chat_id}" + assert call_kwargs["channel"] == "api" + assert call_kwargs["chat_id"] == chat_id + + @pytest.mark.skipif(not HAS_AIOHTTP, reason="aiohttp not installed") @pytest.mark.asyncio async def test_fixed_session_requests_are_serialized(aiohttp_client) -> None: diff --git a/tests/test_openai_api_sessions.py b/tests/test_openai_api_sessions.py new file mode 100644 index 000000000..8cc388396 --- /dev/null +++ b/tests/test_openai_api_sessions.py @@ -0,0 +1,192 @@ +"""Real HTTP, AgentLoop, tools and storage with a deterministic offline model.""" + +from __future__ import annotations + +import asyncio +import json +from contextlib import asynccontextmanager +from copy import deepcopy + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestClient, TestServer + +from nanobot.agent.loop import AgentLoop +from nanobot.agent.tools.context import current_request_context +from nanobot.api.server import API_CHAT_ID, API_SESSION_KEY, create_app +from nanobot.bus.queue import MessageBus +from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest + +pytestmark = pytest.mark.asyncio +AUTH = {"Authorization": "Bearer test-api-key"} + + +class RouteProvider(LLMProvider): + def __init__(self, *, hold_first=False): + super().__init__(provider_name="offline-api-test") + self.calls = [] + self.hold_first = hold_first + self.started = asyncio.Event() + self.release = asyncio.Event() + + def get_default_model(self): + return "offline-api-test" + + async def chat(self, messages, tools=None, **kwargs): + ctx = current_request_context() + assert ctx is not None + self.calls.append({ + "session_key": ctx.session_key, + "messages": deepcopy(self._sanitize_empty_content(messages)), + "tools": deepcopy(tools), + }) + if self.hold_first and len(self.calls) == 1: + self.started.set() + await asyncio.wait_for(self.release.wait(), 10) + if messages[-1]["role"] != "tool": + call_number = 1 + sum(len(message.get("tool_calls", [])) for message in messages) + return LLMResponse(content=None, tool_calls=[ToolCallRequest( + id=f"inspect-route-{call_number}", name="my", + arguments={"action": "check", "key": "request.chat_id"}, + )]) + return LLMResponse(content=json.dumps({ + "session_key": ctx.session_key, + "chat_id": ctx.chat_id, + "tool_result": messages[-1]["content"], + })) + + async def chat_stream(self, messages, tools=None, on_content_delta=None, **kwargs): + response = await self.chat(messages, tools, **kwargs) + if response.content and on_content_delta: + midpoint = len(response.content) // 2 + await on_content_delta(response.content[:midpoint]) + await on_content_delta(response.content[midpoint:]) + return response + + +@asynccontextmanager +async def runtime(workspace, provider, *, received=None): + agent = AgentLoop( + bus=MessageBus(), provider=provider, workspace=workspace, + restrict_to_workspace=True, max_iterations=3, + ) + app = create_app(agent, api_key="test-api-key") + if received is not None: + @web.middleware + async def observe_request(request, handler): + body = await request.json() + if body["messages"][0]["content"] == "SECOND_TURN": + received.set() + return await handler(request) + app.middlewares.append(observe_request) + client = TestClient(TestServer(app)) + try: + await client.start_server() + yield agent, client + finally: + await client.close() + await agent.aclose() + + +async def post(client, session_id, text, stream=False): + response = await client.post( + "/v1/chat/completions", headers=AUTH, + json={ + "session_id": session_id, "stream": stream, + "messages": [{"role": "user", "content": text}], + }, + ) + assert response.status == 200, await response.text() + if not stream: + return json.loads((await response.json())["choices"][0]["message"]["content"]) + body = await response.text() + assert body.endswith("data: [DONE]\n\n") + chunks = [json.loads(line[6:]) for line in body.splitlines() + if line.startswith("data: ") and line != "data: [DONE]"] + assert chunks[-1]["choices"][0]["finish_reason"] == "stop" + assert len({chunk["id"] for chunk in chunks}) == 1 + return json.loads("".join(chunk["choices"][0]["delta"].get("content", "") for chunk in chunks)) + + +def assert_route(result, chat_id): + assert result["session_key"] == f"api:{chat_id}" + assert result["chat_id"] == chat_id + # This is the real my tool result, not a mocked process_direct argument. + assert result["tool_result"] == f"request.chat_id: {chat_id!r}" + + +def assert_prefix(previous, following): + assert json.dumps(previous["messages"], ensure_ascii=False) == json.dumps( + following["messages"][:len(previous["messages"])], ensure_ascii=False, + ) + assert json.dumps(previous["tools"], ensure_ascii=False) == json.dumps( + following["tools"], ensure_ascii=False, + ) + + +@pytest.mark.parametrize("stream", [False, True]) +@pytest.mark.parametrize("second_id", ["alpha", " alpha ", "beta"]) +async def test_concurrent_requests_keep_routes_history_and_order(tmp_path, stream, second_id): + provider = RouteProvider(hold_first=True) + received = asyncio.Event() + async with runtime(tmp_path / "workspace", provider, received=received) as (_, client): + first = asyncio.create_task(post(client, "alpha", "FIRST_TURN", stream)) + tasks = [first] + try: + await asyncio.wait_for(provider.started.wait(), 10) + second = asyncio.create_task(post(client, second_id, "SECOND_TURN", stream)) + tasks.append(second) + await asyncio.wait_for(received.wait(), 10) + if second_id == "alpha": + # The second HTTP request reached the handler, but its session is busy. + assert len(provider.calls) == 1 + assert not second.done() + provider.release.set() + else: + assert_route(await asyncio.wait_for(second, 10), second_id) + assert not first.done() + provider.release.set() + assert_route(await asyncio.wait_for(first, 10), "alpha") + assert_route(await asyncio.wait_for(second, 10), second_id) + second_call = next(call for call in provider.calls + if "SECOND_TURN" in json.dumps(call["messages"])) + assert ("FIRST_TURN" in json.dumps(second_call["messages"])) == (second_id == "alpha") + finally: + provider.release.set() + await asyncio.gather(*tasks, return_exceptions=True) + + +@pytest.mark.parametrize("session_id", ["alpha", " alpha ", " ", None]) +async def test_old_history_survives_route_fix_restart_and_rollback(tmp_path, session_id): + workspace = tmp_path / "workspace" + # The pre-fix adapter passed this exact identity and the shared default route. + old_key = f"api:{session_id}" if session_id else API_SESSION_KEY + old_provider = RouteProvider() + async with runtime(workspace, old_provider) as (agent, _): + await agent.process_direct( + "LEGACY_HISTORY", session_key=old_key, channel="api", chat_id=API_CHAT_ID, + ) + + upgraded = RouteProvider() + async with runtime(workspace, upgraded) as (_, client): + result = await post(client, session_id, "UPGRADED_TURN") + assert_route(result, session_id or "default") + assert "LEGACY_HISTORY" in json.dumps(upgraded.calls[0]["messages"]) + # The ordinary prefix is byte-stable; replay also keeps structured tool history. + assert_prefix(old_provider.calls[0], upgraded.calls[0]) + old_tool_prefix = old_provider.calls[1]["messages"] + assert old_tool_prefix == upgraded.calls[0]["messages"][:len(old_tool_prefix)] + # A live tool continuation appends to, rather than rebuilds, the request prefix. + assert_prefix(upgraded.calls[0], upgraded.calls[1]) + + reopened = RouteProvider() + async with runtime(workspace, reopened) as (agent, client): + assert_route(await post(client, session_id, "AFTER_RESTART"), session_id or "default") + replay = json.dumps(reopened.calls[0]["messages"]) + assert "LEGACY_HISTORY" in replay and "UPGRADED_TURN" in replay + # Restoring the old adapter route still reads all post-upgrade messages. + await agent.process_direct( + "ROLLBACK_TURN", session_key=old_key, channel="api", chat_id=API_CHAT_ID, + ) + replay = json.dumps(reopened.calls[-1]["messages"]) + assert all(text in replay for text in ("LEGACY_HISTORY", "UPGRADED_TURN", "AFTER_RESTART"))