{"openapi":"3.1.0","info":{"title":"Lucio Research","version":"0.1.0"},"paths":{"/api/health/app":{"get":{"tags":["API","Health"],"summary":"Application Health Checkup","description":"### Application Health check\nThis endpoint returns the status of the application.","operationId":"app_health_api_health_app_get","responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}}}}},"/api/research/run":{"post":{"tags":["API","Research"],"summary":"Run a research pipeline","description":"Triggers the full research pipeline asynchronously via a Taskiq worker and returns **202 Accepted** immediately with a ``stream_key``. This endpoint does not wait for the research result to finish. Instead, it queues the work, starts the research pipeline in the background, and streams progress and final output through Redis.\n\n## What this endpoint expects\n\nThe request body contains the following fields:\n\n- ``query``: The user's research question. This field is required and must not be empty or whitespace-only.\n- ``product``: The product that initiated the request. Supported values are ``web``, ``word``, ``outlook``, and ``studio``.\n- ``files``: Optional list of file objects describing documents already uploaded to Azure Blob Storage. Each object must contain:\n  - ``blob_name`` — the blob path inside the container.\n  - ``blob_bucket_name`` — the Azure Blob container name (e.g. ``\"lucio-platform\"``).\n  - ``file_name`` — the original file name.\n  - ``metadata`` (optional) — arbitrary key/value metadata for the file.\n\n  All three required string fields must not be empty or whitespace-only. If omitted, ``files`` defaults to an empty list.\n- ``chat_history``: Optional list of prior conversation messages. Each item must contain ``timestamp``, ``content``, and ``message_type``. Supported ``message_type`` values are ``user`` and ``assistant``. If omitted, it defaults to an empty list.\n- ``user_profile``: Optional free-text profile or background information about the user. If omitted, an empty string is used internally.\n\n**Note:** The legacy ``blob_file_paths`` field is no longer accepted. Sending it will result in a validation error. Use ``files`` instead.\n\n## Document upload requirements\n\nEach entry in ``files`` must reference a text file containing the extracted text of a document that should be processed by the research query.\n\nRules:\n\n- Upload files to Azure Blob Storage before calling this endpoint.\n- Set ``blob_bucket_name`` to the Azure container name (e.g. ``\"lucio-platform\"``).\n- ``blob_name`` is the blob path inside that container. It must follow this format: ``<organisation_id>/<user_id>/<product>/<file_name>``.\n- ``organisation_id`` must be the organisation identifier used by the system.\n- ``product`` in the path must be one of ``web``, ``word``, ``outlook``, or ``studio``.\n- The file must be a text file. Other file formats are not supported by this endpoint.\n\nFor optimal responses and citations, upload the extracted text in a page-based format using page tags such as:\n\n```text\n<page_number_1>\n...page text...\n</page_number_1>\n<page_number_2>\n...page text...\n</page_number_2>\n```\n\nUse ``\\n`` for line breaks and ``\\r`` for carriage returns. There is no need to otherwise format the text. Use only the page-number tags together with ``\\n`` and ``\\r`` to represent the extracted text content.\n\n## What happens after you call this endpoint\n\n1. A unique ``stream_key`` is generated.\n2. The request is queued for background execution via Taskiq.\n3. If ``files`` are provided, those blobs are fetched from Azure Blob Storage before the research graph runs.\n4. The pipeline may also extract URLs directly from the ``query`` and include them as additional research inputs.\n5. Progress updates, reasoning messages, and the final answer are written to a single Redis stream keyed by ``stream_key``.\n\n## Response\n\nA successful request returns ``202 Accepted`` with a response body like:\n\n```json\n{\n  \"status\": \"success\",\n  \"stream_key\": \"web_550e8400-e29b-41d4-a716-446655440000\"\n}\n```\n\nUse ``stream_key`` to read the research output. It is the only identifier you need to consume the result stream.\n\n## Where to read the output\n\nThe research output is delivered via a **single** Redis stream keyed by ``stream_key``. The Redis broker is accessible via the ``RESEARCH-BROKER-URL`` secret stored in Key Vault.\n\nEach stream chunk follows the OpenAI streaming response format with an added ``message_type`` field. Expected values are ``\"thought\"`` for progress or reasoning-style updates, and ``\"response\"`` for the answer stream.\n\n---\n\n## Reading the output\n\nUse the ``stream_key`` returned by this endpoint as the Redis stream key.\n\n### Option 1: Read directly from the Redis stream\n\nUse the Redis `XREAD` command with blocking to consume chunks as they arrive.\n\n```python\nimport json, redis\n\nr = redis.Redis(...)\nstream_key = '<stream_key from /run response>'\n\nlast_id = '0-0'\nwhile True:\n    results = r.xread({stream_key: last_id}, block=5000, count=100)\n    if not results:\n        continue\n    for _key, messages in results:\n        for stream_id, fields in messages:\n            last_id = stream_id\n            chunk = json.loads(fields[b'data'])\n            msg_type = chunk.get('message_type', 'response')\n            finish_reason = chunk['choices'][0].get('finish_reason')\n            if finish_reason in ('stop', 'error'):\n                break\n            content = chunk['choices'][0]['delta'].get('content', '')\n            print(f'[{msg_type}] {content}', end='')\n```\n\n### Option 2: Use the SSE proxy endpoint\n\n- `GET /research/stream/{stream_key}` — all chunks (response + thoughts)\n\nEach SSE `data:` payload is the same JSON chunk. Filter on ``message_type`` client-side. This is the easiest option for browser-based clients.\n\n## Example request\n\n```json\n{\n  \"query\": \"Summarise the employee termination risks in the attached contract and cite relevant case law.\",\n  \"product\": \"web\",\n  \"files\": [\n    {\n      \"blob_name\": \"65f2c9f1d7ab12cd34ef5678/user_123/web/employment_contract.txt\",\n      \"blob_bucket_name\": \"lucio-platform\",\n      \"file_name\": \"employment_contract.txt\"\n    }\n  ],\n  \"chat_history\": [\n    {\n      \"timestamp\": \"2026-04-22T10:00:00Z\",\n      \"content\": \"Focus on employer-side risks.\",\n      \"message_type\": \"user\"\n    }\n  ],\n  \"user_profile\": \"In-house counsel reviewing an employment agreement.\"\n}\n```\n\n---\n\n## Stream format (OpenAI-compatible + message_type)\n\n```json\n{\n  \"id\": \"chatcmpl-<stream_key>\",\n  \"object\": \"chat.completion.chunk\",\n  \"created\": 1712345678,\n  \"model\": \"<model>\",\n  \"message_type\": \"response\",\n  \"choices\": [{\n    \"index\": 0,\n    \"delta\": { \"content\": \"The court held...\" },\n    \"finish_reason\": null\n  }]\n}\n```","operationId":"run_research_endpoint_api_research_run_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunRequest"}}},"required":true},"responses":{"202":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/research/stream/{stream_key}":{"get":{"tags":["API","Research"],"summary":"SSE proxy for the Redis stream","description":"Proxy the Redis stream as Server-Sent Events.\n\nBoth response and thought chunks are delivered on this single\nendpoint. Clients can filter by the ``message_type`` field in\neach JSON chunk.","operationId":"stream_sse_api_research_stream__stream_key__get","parameters":[{"name":"stream_key","in":"path","required":true,"schema":{"type":"string","title":"Stream Key"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/assistant-file-agent/run":{"post":{"tags":["API","Assistant File Agent"],"summary":"Run Assistant File Agent Endpoint","operationId":"run_assistant_file_agent_endpoint_api_assistant_file_agent_run_post","requestBody":{"content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunRequest"}}},"required":true},"responses":{"202":{"description":"Successful Response","content":{"application/json":{"schema":{"$ref":"#/components/schemas/AgentRunResponse"}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}},"/api/assistant-file-agent/stream/{stream_key}":{"get":{"tags":["API","Assistant File Agent"],"summary":"SSE proxy for the assistant file Redis stream","operationId":"stream_assistant_file_response_sse_api_assistant_file_agent_stream__stream_key__get","parameters":[{"name":"stream_key","in":"path","required":true,"schema":{"type":"string","title":"Stream Key"}}],"responses":{"200":{"description":"Successful Response","content":{"application/json":{"schema":{}}}},"422":{"description":"Validation Error","content":{"application/json":{"schema":{"$ref":"#/components/schemas/HTTPValidationError"}}}}}}}},"components":{"schemas":{"AgentRunFile":{"properties":{"blob_name":{"type":"string","title":"Blob Name","description":"Blob name within the bucket"},"blob_bucket_name":{"type":"string","title":"Blob Bucket Name","description":"Azure Blob container name"},"file_name":{"type":"string","title":"File Name","description":"Original file name"},"metadata":{"anyOf":[{"additionalProperties":true,"type":"object"},{"type":"null"}],"title":"Metadata","description":"Optional client-provided metadata for the file"}},"additionalProperties":false,"type":"object","required":["blob_name","blob_bucket_name","file_name"],"title":"AgentRunFile","description":"A user-provided file reference for an agent run."},"AgentRunRequest":{"properties":{"query":{"type":"string","title":"Query","description":"The user's query"},"product":{"$ref":"#/components/schemas/SourceProduct","description":"Source product that initiated this run"},"files":{"items":{"$ref":"#/components/schemas/AgentRunFile"},"type":"array","title":"Files","description":"List of uploaded documents with storage metadata"},"chat_history":{"items":{"$ref":"#/components/schemas/ChatHistoryItem"},"type":"array","title":"Chat History","description":"Optional list of previous conversation messages"},"user_profile":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Profile","description":"Optional free-text user profile string"},"user_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"User Id","description":"Optional authenticated user ID for skill resolution"},"organization_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Organization Id","description":"Optional organization ID for skill resolution"},"chat_session_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Chat Session Id","description":"Optional chat session ID for reusing an active execution session"},"india_hosted":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"India Hosted","description":"Whether the org is India-hosted, so every AI call goes to Bedrock in India (core/ai_route.py). Sent by the api, which has the org."},"selected_model":{"anyOf":[{"$ref":"#/components/schemas/RealModelName"},{"type":"null"}],"description":"Optional model override for the final synthesis step. Must be a valid RealModelName value (e.g. 'claude-sonnet-4.6', 'gpt-5.4'). If omitted, defaults to claude-sonnet-4.6."}},"type":"object","required":["query","product"],"title":"AgentRunRequest","description":"Universal payload for stateless streamed agent runs."},"AgentRunResponse":{"properties":{"status":{"type":"string","title":"Status","default":"success"},"stream_key":{"type":"string","title":"Stream Key","description":"Unique ID for this run; use as the Redis stream key"}},"type":"object","required":["stream_key"],"title":"AgentRunResponse","description":"Shared response for stateless streamed agent runs."},"ChatHistoryItem":{"properties":{"timestamp":{"type":"string","title":"Timestamp","description":"ISO 8601 timestamp"},"content":{"type":"string","title":"Content","description":"Message content"},"message_type":{"type":"string","title":"Message Type","description":"Message type: 'user' or 'assistant'"}},"type":"object","required":["timestamp","content","message_type"],"title":"ChatHistoryItem","description":"A single message in the chat history."},"HTTPValidationError":{"properties":{"detail":{"items":{"$ref":"#/components/schemas/ValidationError"},"type":"array","title":"Detail"}},"type":"object","title":"HTTPValidationError"},"RealModelName":{"type":"string","enum":["gemini-2.5-flash-lite","gemini-3-flash-preview","gemini-3.5-flash-preview","gemini-3.1-pro-preview","claude-opus-4.7","claude-opus-5","claude-opus-5.5","claude-sonnet-4.6","gpt-5.4","gpt-5.6-luna","gpt-6.1-sol","glm-5.2","text-embedding-3-large"],"title":"RealModelName","description":"Canonical model identifiers used across the codebase."},"SourceProduct":{"type":"string","enum":["web","word","outlook","studio"],"title":"SourceProduct","description":"An enumeration representing the source products for document chunks.\nAttributes:\n    WEB: Represents chats created from web app.\n    WORD: Represents chats created from Microsoft Word plugin.\n    OUTLOOK: Represents chats created from Microsoft Outlook plugin.\n    STUDIO: Represents chats created from Lucio Studio."},"ValidationError":{"properties":{"loc":{"items":{"anyOf":[{"type":"string"},{"type":"integer"}]},"type":"array","title":"Location"},"msg":{"type":"string","title":"Message"},"type":{"type":"string","title":"Error Type"},"input":{"title":"Input"},"ctx":{"type":"object","title":"Context"}},"type":"object","required":["loc","msg","type"],"title":"ValidationError"}}}}