# Cancel native Linc session turn Source: https://docs.case.dev/api-reference/agentslinc/cancel-native-linc-session-turn /openapi.json post /linc/v1/sessions/{id}/cancel Sends an abort RPC to the session runtime, ending the current turn while keeping the session alive. Body handling is intentionally lenient — cancel is a stop control, so unknown fields are ignored and an invalid or missing body is treated as empty rather than rejected. # Create native Linc session Source: https://docs.case.dev/api-reference/agentslinc/create-native-linc-session /openapi.json post /linc/v1/sessions Creates a native Linc session in a sandboxed runtime with scoped Case.dev credentials. This endpoint starts the sandbox actor only; messages and event replay use separate endpoints. # End native Linc session Source: https://docs.case.dev/api-reference/agentslinc/end-native-linc-session /openapi.json delete /linc/v1/sessions/{id} # Get native Linc session state Source: https://docs.case.dev/api-reference/agentslinc/get-native-linc-session-state /openapi.json get /linc/v1/sessions/{id}/state # Ingest native Linc session events Source: https://docs.case.dev/api-reference/agentslinc/ingest-native-linc-session-events /openapi.json post /linc/v1/sessions/{id}/events/ingest Runtime ingest endpoint for sandbox runtimes. Frames are persisted for replay; terminal frames emit the durable Linc session ended webhook. # Replace a persistent Linc conversation scope Source: https://docs.case.dev/api-reference/agentslinc/replace-a-persistent-linc-conversation-scope /openapi.json put /linc/v1/sessions/{id}/scope Stops the conversation worker, applies a newly authorized object scope, revokes its prior managed credential, and resumes the same native conversation in its existing workspace. # Replay completed native Linc messages Source: https://docs.case.dev/api-reference/agentslinc/replay-completed-native-linc-messages /openapi.json get /linc/v1/sessions/{id}/messages Returns completed Pi/Linc message entries derived from durable native Linc events. This is the stable session-message read model for callers that need to persist or recover chat history without depending on a live SSE stream. # Replay native Linc events Source: https://docs.case.dev/api-reference/agentslinc/replay-native-linc-events /openapi.json get /linc/v1/sessions/{id}/events Returns persisted native Pi/Linc event envelopes after the requested cursor. Live delivery is handled by the Linc stream service. # Send native Pi RPC command Source: https://docs.case.dev/api-reference/agentslinc/send-native-pi-rpc-command /openapi.json post /linc/v1/sessions/{id}/rpc Forwards a native Pi/Linc RPC command object to the sandbox-local Linc bridge unchanged. The route returns after Pi accepts or rejects the command; native events are read through the events endpoint. # Upload a runtime image for model input Source: https://docs.case.dev/api-reference/agentslinc/upload-a-runtime-image-for-model-input /openapi.json post /linc/v1/images Inference transport for Linc. Stores a private image without creating a Vault object and returns a renewable presigned download URL. Requires API-key authentication with inference read access. # Create compute environment Source: https://docs.case.dev/api-reference/compute/create-compute-environment /openapi.json post /compute/v1/environments Creates a new compute environment for running serverless workloads. Each environment gets its own isolated namespace with a unique domain for hosting applications and APIs. The first environment created becomes the default environment for the organization. # Create secret group Source: https://docs.case.dev/api-reference/compute/create-secret-group /openapi.json post /compute/v1/secrets Creates a new secret group in a compute environment. Secret groups organize related secrets for use in serverless functions and workflows. If no environment is specified, the group is created in the default environment. **Features:** - Organize secrets by logical groups (e.g., database, APIs, third-party services) - Environment-based isolation - Validation of group names - Conflict detection for existing groups # Delete compute environment Source: https://docs.case.dev/api-reference/compute/delete-compute-environment /openapi.json delete /compute/v1/environments/{name} Permanently delete a compute environment and all its associated resources. This will stop all running deployments and clean up related configurations. The default environment cannot be deleted if other environments exist. # Delete secret group or key Source: https://docs.case.dev/api-reference/compute/delete-secret-group-or-key /openapi.json delete /compute/v1/secrets/{group} Delete an entire secret group or a specific key within a secret group. When deleting a specific key, the remaining secrets in the group are preserved. When deleting the entire group, all secrets and the group itself are removed. # Get compute environment Source: https://docs.case.dev/api-reference/compute/get-compute-environment /openapi.json get /compute/v1/environments/{name} Retrieve a specific compute environment by name. Returns environment configuration including status, domain, and metadata for your serverless compute infrastructure. # Get compute pricing information Source: https://docs.case.dev/api-reference/compute/get-compute-pricing-information /openapi.json get /compute/v1/pricing Returns current pricing for GPU instances. Prices are fetched in real-time and include a 20% platform fee. For detailed instance types and availability, use GET /compute/v1/instance-types. # Get compute usage and billing Source: https://docs.case.dev/api-reference/compute/get-compute-usage-and-billing /openapi.json get /compute/v1/usage Returns detailed compute usage statistics and billing information for your organization. Includes GPU and CPU hours, total runs, costs, and breakdowns by environment. Use optional query parameters to filter by specific year and month. # Get GPU instance Source: https://docs.case.dev/api-reference/compute/get-gpu-instance /openapi.json get /compute/v1/instances/{id} Retrieves detailed information about a GPU instance including SSH connection details, vault mount scripts, real-time cost tracking, and current status. SSH private key included for secure access. # Health check Source: https://docs.case.dev/api-reference/compute/health-check /openapi.json get /compute/v1/health Unauthenticated health check for the Compute service. # Launch GPU instance Source: https://docs.case.dev/api-reference/compute/launch-gpu-instance /openapi.json post /compute/v1/instances Launches a new GPU compute instance with automatic SSH key generation. Supports mounting Case.dev Vaults as filesystems. Instance boots in ~2-5 minutes. Perfect for batch OCR processing, AI model training, and intensive document analysis workloads. # List environments Source: https://docs.case.dev/api-reference/compute/list-environments /openapi.json get /compute/v1/environments Retrieve all compute environments for your organization. Environments provide isolated execution contexts for running code and workflows. # List GPU instance types Source: https://docs.case.dev/api-reference/compute/list-gpu-instance-types /openapi.json get /compute/v1/instance-types Retrieves all available GPU instance types with pricing, specifications, and regional availability. Includes T4, A10, A100, H100, and H200 GPUs powered by Lambda Labs. Perfect for AI model training, inference workloads, and legal document OCR processing at scale. # List GPU instances Source: https://docs.case.dev/api-reference/compute/list-gpu-instances /openapi.json get /compute/v1/instances Retrieves all GPU compute instances for your organization with real-time status updates from Lambda Labs. Includes pricing and runtime metrics. Perfect for monitoring AI workloads, document processing jobs, and cost tracking. # List secret groups Source: https://docs.case.dev/api-reference/compute/list-secret-groups /openapi.json get /compute/v1/secrets Retrieve all secret groups for a compute environment. Secret groups organize related secrets (API keys, credentials, etc.) that can be securely accessed by compute jobs during execution. # List secret keys in a group Source: https://docs.case.dev/api-reference/compute/list-secret-keys-in-a-group /openapi.json get /compute/v1/secrets/{group} Retrieve the keys (names) of secrets in a specified group within a compute environment. For security reasons, actual secret values are not returned - only the keys and metadata. # Set default environment Source: https://docs.case.dev/api-reference/compute/set-default-environment /openapi.json post /compute/v1/environments/{name}/default Sets a compute environment as the default for the organization. Only one environment can be default at a time - setting a new default will automatically unset the previous one. # Set secrets in group Source: https://docs.case.dev/api-reference/compute/set-secrets-in-group /openapi.json put /compute/v1/secrets/{group} Set or update secrets in a compute secret group. Secrets are encrypted with AES-256-GCM. Use this to manage environment variables and API keys for your compute workloads. # Terminate GPU instance Source: https://docs.case.dev/api-reference/compute/terminate-gpu-instance /openapi.json delete /compute/v1/instances/{id} Terminates a running GPU instance, calculates final cost, and cleans up SSH keys. This action is permanent and cannot be undone. All data on the instance will be lost. # Bind an application management key Source: https://docs.case.dev/api-reference/connectors/bind-an-application-management-key /openapi.json put /connectors/v1/applications/{id}/keys/{keyId} Requires an owner/admin Clerk session. Explicitly binds a non-system connector API key to one application. Allows multiple keys for controlled rotation. Does not grant Vault access or mint credentials. # Browse remote folders Source: https://docs.case.dev/api-reference/connectors/browse-remote-folders /openapi.json get /connectors/v1/connections/{id}/browse Browse the provider one level at a time. Without a site, container, or parent, returns top-level resources. Pass the stable browse_ref fields returned by one response to navigate into the next level. Returns 403 provider_scope_insufficient when the connection scope cannot browse server-side. Clio browsing shares request capacity with background runs; throttled responses include Retry-After when a retry deadline is known. # Create connection Source: https://docs.case.dev/api-reference/connectors/create-connection /openapi.json post /connectors/v1/connections Create a pending provider connection and return a one-time connect_url for the hosted OAuth flow. The user completes provider consent at connect_url and is redirected to return_url with ?connection_id=. # Create or upgrade a synced link Source: https://docs.case.dev/api-reference/connectors/create-or-upgrade-a-synced-link /openapi.json post /connectors/v1/sync-link Standing promise: backfill now, then stay current (the sync sweeper re-runs synced links on a schedule). Direction both creates paired import/export links and defaults export to a CaseMark Output subfolder. Same body as /transfer minus run_mode. Upserts links by (connection_id, direction, remote, vault_id); existing once-links are upgraded in place with their ledger and cursor preserved. Downgrade or pause via PATCH /links/{id}. # Delete connection Source: https://docs.case.dev/api-reference/connectors/delete-connection /openapi.json delete /connectors/v1/connections/{id} Unlink a provider account: revoke tokens at the provider and delete them. purge=true additionally deletes the vault documents its import links brought in. # Delete link Source: https://docs.case.dev/api-reference/connectors/delete-link /openapi.json delete /connectors/v1/links/{id} Delete a link and its ledger. vault_docs=delete additionally removes the vault documents an import link brought in (default: keep). # Ensure installation Source: https://docs.case.dev/api-reference/connectors/ensure-installation /openapi.json post /connectors/v1/installations Idempotently create (or return) the installation for (application, external_tenant_id) in this organization. Send the returned installation id as X-Case-Installation-Id on connector requests to scope them to this tenant. # Fetch one remote file Source: https://docs.case.dev/api-reference/connectors/fetch-one-remote-file /openapi.json post /connectors/v1/fetch Copy one provider file, named by an open_ref from browse, into a Vault (vault_id) or to a presigned S3 PUT URL (upload_url). Runs synchronously; files over 100 MB return 413 and belong in a transfer. A repeat for an unchanged provider version returns the first copy with 200. Vault copies are stored as uploaded: call POST /vault/{id}/ingest/{objectId} to index them. Fetched copies are never exported by a link. # Get Clio selection root Source: https://docs.case.dev/api-reference/connectors/get-clio-selection-root /openapi.json get /connectors/v1/links/{id}/selection Resolve the linked Clio matter root and existing folder ancestry for managing synced folders. Applies the provider account ACLs. # Get connection Source: https://docs.case.dev/api-reference/connectors/get-connection /openapi.json get /connectors/v1/connections/{id} Retrieve one provider connection, including account identity and health. # Get link Source: https://docs.case.dev/api-reference/connectors/get-link /openapi.json get /connectors/v1/links/{id} Retrieve one link: state, counts, and embedded active_run/last_run. Poll this after POST /transfer. # Health check Source: https://docs.case.dev/api-reference/connectors/health-check /openapi.json get /connectors/v1/health Unauthenticated health check for the Connectors service. # List connections Source: https://docs.case.dev/api-reference/connectors/list-connections /openapi.json get /connectors/v1/connections List provider connections for the organization, with health status. Returns at most `limit` connections (default 200, maximum 200). When `pagination.has_more` is true, replay `pagination.next_cursor` as `?cursor=` to fetch the following page. Cursors are opaque and are only valid for the exact filter set and installation/subject scope they were issued under. # List every file in a folder Source: https://docs.case.dev/api-reference/connectors/list-every-file-in-a-folder /openapi.json get /connectors/v1/connections/{id}/contents List every file under one folder, at any depth, as a flat paginated list, to preview what importing that folder would bring in. Pass the browse_ref fields of a folder or container. Each file carries its path relative to that folder. A page returns as soon as it holds files, so it may be shorter than page_size while cursor is still set; keep requesting until cursor is null. The listing stops after 10,000 files and sets truncated. Returns 422 contents_not_supported when the provider cannot list folder contents, and shares the provider request budget with browsing and background runs. # List installation vault grants Source: https://docs.case.dev/api-reference/connectors/list-installation-vault-grants /openapi.json get /connectors/v1/installations/{id}/vaults List the vaults an installation may use, with capabilities and revocation state. # List installations Source: https://docs.case.dev/api-reference/connectors/list-installations /openapi.json get /connectors/v1/installations List application installations (tenants) in this organization. Returns at most `limit` installations (default 200, maximum 200). When `pagination.has_more` is true, replay `pagination.next_cursor` as `?cursor=` to fetch the following page. Cursors are opaque and are only valid for the exact filter set and caller scope they were issued under. # List link objects (ledger) Source: https://docs.case.dev/api-reference/connectors/list-link-objects-ledger /openapi.json get /connectors/v1/links/{id}/objects Per-file transfer ledger for a link: provider item, vault object, path, content version, state, and error. # List links Source: https://docs.case.dev/api-reference/connectors/list-links /openapi.json get /connectors/v1/links List transfer links, filterable by vault, connection, direction, mode, and state. # Mint an installation credential Source: https://docs.case.dev/api-reference/connectors/mint-an-installation-credential /openapi.json post /connectors/v1/installations/{id}/tokens Bound application management API key only. Returns a 256-bit opaque bearer secret once; valid for 15 minutes, connector data-plane only. No refresh token. At most 4 overlapping credentials and 20 mints/minute per installation. The application server must derive tenant identity; this is not browser authentication. # Prepare Microsoft IT approval Source: https://docs.case.dev/api-reference/connectors/prepare-microsoft-it-approval /openapi.json post /connectors/v1/connections/{id}/microsoft-admin-approval Create a seven-day, replaceable IT approval link for a pending Microsoft connection. Approval does not connect an account. Only delegated document read scopes are requested. # Resolve a folder link Source: https://docs.case.dev/api-reference/connectors/resolve-a-folder-link /openapi.json get /connectors/v1/connections/{id}/resolve Resolve a pasted provider folder link to that folder's browse item, including its browse_ref, name, and path when the provider reports it cheaply. Supports Google Drive folder and open?id= links, Box folder and shared links, Dropbox shared links, and OneDrive/SharePoint sharing links. Returns 400 link_not_recognized for links of another provider or form, 422 link_not_folder for file links, 422 link_not_in_account when a Dropbox or Box shared folder is not in the connected account, 404 link_not_accessible when the account cannot see it, and 422 link_resolve_not_supported for providers without folder links. Shares the provider request budget with browsing. # Revoke an application management key binding Source: https://docs.case.dev/api-reference/connectors/revoke-an-application-management-key-binding /openapi.json delete /connectors/v1/applications/{id}/keys/{keyId} Requires an owner/admin Clerk session. Immediately invalidates tokens minted through this binding. Rebinding later does not revive those tokens. # Revoke an installation credential Source: https://docs.case.dev/api-reference/connectors/revoke-an-installation-credential /openapi.json delete /connectors/v1/installations/{id}/tokens/{tokenId} Issuing API key only; installation credentials cannot revoke or mint credentials. Immediate revocation on the next request. # Revoke installation vault grant Source: https://docs.case.dev/api-reference/connectors/revoke-installation-vault-grant /openapi.json delete /connectors/v1/installations/{id}/vaults/{vaultId} Revoke an installation's access to a vault. Links using the vault pause at their next run; nothing is deleted. # Search remote files and folders Source: https://docs.case.dev/api-reference/connectors/search-remote-files-and-folders /openapi.json get /connectors/v1/connections/{id}/search Search the provider's files by name, and by content where the provider supports it; with kind=folder, search folders by name. Without a scope, searches everything the connection can see; pass the browse_ref fields of a folder or container to search inside it. Folder results carry a browse_ref to open them with browse. Each response states whether its folder scope covers the whole subtree. Returns 422 search_not_supported when the provider has no search and search_kind_not_supported when it cannot search folders, and shares the provider request budget with browsing and background runs. # Transfer between provider folder and vault Source: https://docs.case.dev/api-reference/connectors/transfer-between-provider-folder-and-vault /openapi.json post /connectors/v1/transfer One-shot import (provider folder → vault), export (vault → provider folder), or both. Direction both creates paired import/export links and defaults export to a CaseMark Output subfolder. Upserts links by (connection_id, direction, remote, vault_id): first call backfills, later calls move only new/changed files via the ledger. Poll GET /links/{id} → active_run for progress. # Update link Source: https://docs.case.dev/api-reference/connectors/update-link /openapi.json patch /connectors/v1/links/{id} Pause/resume a link (state "paused" | "ready"), change its mode (synced -> once is the sync downgrade), or edit its policy in place. # Update provider availability Source: https://docs.case.dev/api-reference/connectors/update-provider-availability /openapi.json patch /connectors/v1/connections Enable or disable new runs and scheduled syncs for one provider across the authenticated organization or installation. This organization-wide operation requires explicit confirmation. Existing credentials, links, and imported files are preserved; active runs are not interrupted. # Upsert installation vault grant Source: https://docs.case.dev/api-reference/connectors/upsert-installation-vault-grant /openapi.json put /connectors/v1/installations/{id}/vaults/{vaultId} Grant (or update) an installation's access to a vault. Re-granting a revoked vault reactivates it. Import links need can_write; export links need can_read; mirror deletion and purge need can_manage. # Deep legal research Source: https://docs.case.dev/api-reference/legal/deep-legal-research /openapi.json post /legal/v1/research Perform comprehensive legal research with multiple query variations. Uses advanced deep search to find relevant sources across different phrasings of the legal issue. # Extract citations from URL Source: https://docs.case.dev/api-reference/legal/extract-citations-from-url /openapi.json post /legal/v1/citations-from-url Extract all legal citations and references from a document URL. Returns structured citation data including case citations, statute references, and regulatory citations. # Find legal sources Source: https://docs.case.dev/api-reference/legal/find-legal-sources /openapi.json post /legal/v1/find Search for legal sources including cases, statutes, and regulations from authoritative legal databases. Returns ranked candidates. Always verify with legal.verify() before citing. # Find similar legal sources Source: https://docs.case.dev/api-reference/legal/find-similar-legal-sources /openapi.json post /legal/v1/similar Find cases and documents similar to a given legal source. Useful for finding citing cases, related precedents, or similar statutes. # Get full text of legal document Source: https://docs.case.dev/api-reference/legal/get-full-text-of-legal-document /openapi.json post /legal/v1/full-text Retrieve the full text content of a legal document. Use after verifying the source with legal.verify(). Returns complete text with optional highlights and AI summary. # Health check Source: https://docs.case.dev/api-reference/legal/health-check /openapi.json get /legal/v1/health Unauthenticated health check for the Citations service. Verifies connectivity to the CourtListener API. # List federal and state courts Source: https://docs.case.dev/api-reference/legal/list-federal-and-state-courts /openapi.json post /legal/v1/courts Returns court IDs (slugs) and names for use with the docket search endpoint. Use the returned court ID as the `court` parameter in legal.docket(). # Look up USPTO trademark status Source: https://docs.case.dev/api-reference/legal/look-up-uspto-trademark-status /openapi.json post /legal/v1/trademark-search Look up trademark status and details from the USPTO Trademark Status & Document Retrieval (TSDR) system. Supports lookup by serial number or registration number. Returns mark text, status, owner, goods/services, Nice classification, filing/registration dates, and more. # Parse citations from text Source: https://docs.case.dev/api-reference/legal/parse-citations-from-text /openapi.json post /legal/v1/citations Parses legal citations from text and returns structured Bluebook components (case name, reporter, volume, page, year, court). Accepts either a single citation or a full text block. # Resolve jurisdiction Source: https://docs.case.dev/api-reference/legal/resolve-jurisdiction /openapi.json post /legal/v1/jurisdictions Search for a jurisdiction by name. Returns matching jurisdictions with their IDs for use in legal.find() and other legal research endpoints. # Search EDGAR filings and entity history Source: https://docs.case.dev/api-reference/legal/search-edgar-filings-and-entity-history /openapi.json post /legal/v1/sec-filing Search SEC EDGAR full-text filings via efts.sec.gov or fetch a filer's structured filing history via data.sec.gov. Returns direct SEC archive URLs with filing metadata and match snippets when available. # Search federal dockets and filings Source: https://docs.case.dev/api-reference/legal/search-federal-dockets-and-filings /openapi.json post /legal/v1/docket Search federal court dockets or retrieve a specific docket with optional filing entries. Use legal.listCourts() to resolve court slugs for filtering. # Search USPTO patent applications Source: https://docs.case.dev/api-reference/legal/search-uspto-patent-applications /openapi.json post /legal/v1/patent-search Search the USPTO Open Data Portal for US patent applications and granted patents. Supports free-text queries, field-specific search, filters by assignee/inventor/status/type, date ranges, and pagination. Covers applications filed on or after January 1, 2001. Data is refreshed daily. # Structured XBRL financial data from SEC filings Source: https://docs.case.dev/api-reference/legal/structured-xbrl-financial-data-from-sec-filings /openapi.json post /legal/v1/sec-xbrl Retrieve structured financial values reported to the SEC in XBRL, via data.sec.gov. Use this endpoint when you need numbers (net income, assets, shares outstanding, and so on); use sec-filing to find filing documents. Three types: "concept" returns one line item for one company over time; "facts" returns a catalog of every concept a company reports (or normalized facts for the concepts you name); "frames" returns one concept across all reporting companies for one calendar period. Each fact links back to its EDGAR filing index via secUrl. The same value is re-reported in later filings as a prior-period comparative, so by default (dedupe: true) only facts the SEC assigned a calendar frame are returned; set dedupe to false for every reported fact. Free. # Verify legal citations Source: https://docs.case.dev/api-reference/legal/verify-legal-citations /openapi.json post /legal/v1/verify Validates legal citations against authoritative case law sources (CourtListener database of ~10M cases). Returns verification status and case metadata for each citation found in the input text. Accepts either a single citation or a full text block containing multiple citations. # Chat completions Source: https://docs.case.dev/api-reference/llms/chat-completions /openapi.json post /llm/v1/chat/completions Create a completion for the provided prompt and parameters. Compatible with OpenAI's chat completions API. Supports 40+ models including GPT-4, Claude, Gemini, and CaseMark legal AI models. Includes streaming support, token counting, and usage tracking. # Create embeddings Source: https://docs.case.dev/api-reference/llms/create-embeddings /openapi.json post /llm/v1/embeddings Create vector embeddings from text using OpenAI-compatible models. Perfect for semantic search, document similarity, and building RAG systems for legal documents. # Get LLM configuration Source: https://docs.case.dev/api-reference/llms/get-llm-configuration /openapi.json get /llm/config Retrieves the AI Gateway configuration including all available language models and their specifications. This endpoint returns model information compatible with the Vercel AI SDK Gateway format, making it easy to integrate with existing AI applications. Use this endpoint to: - Discover available language models - Get model specifications and pricing - Configure AI SDK clients - Build model selection interfaces # Health check Source: https://docs.case.dev/api-reference/llms/health-check /openapi.json get /llm/v1/health Unauthenticated health check for the LLM service. # List available language models Source: https://docs.case.dev/api-reference/llms/list-available-language-models /openapi.json get /llm/v1/models Retrieve the curated list of available models: OpenAI, Anthropic, and Google models plus Case.dev's specialized CaseMark legal models. Returns OpenAI-compatible model metadata with pricing information. This endpoint is compatible with OpenAI's models API format, making it easy to integrate with existing applications. # Attach party to matter Source: https://docs.case.dev/api-reference/matters/attach-party-to-matter /openapi.json post /matters/v1/{id}/parties Attach a reusable party to a matter with a matter-specific role. # Create agent type Source: https://docs.case.dev/api-reference/matters/create-agent-type /openapi.json post /matters/v1/agent-types Create a reusable agent role for legal matter orchestration. # Create matter Source: https://docs.case.dev/api-reference/matters/create-matter /openapi.json post /matters/v1 Create a new legal matter and optionally link an existing primary vault. # Create matter log entry Source: https://docs.case.dev/api-reference/matters/create-matter-log-entry /openapi.json post /matters/v1/{id}/log Append a manual operational note or event to a matter log. # Create matter share Source: https://docs.case.dev/api-reference/matters/create-matter-share /openapi.json post /matters/v1/{id}/shares Grant another organization scoped access to this matter and its primary vault. # Create matter type Source: https://docs.case.dev/api-reference/matters/create-matter-type /openapi.json post /matters/v1/types Create a matter type with plain-English operating instructions and seeded work. # Create matter webhook subscription Source: https://docs.case.dev/api-reference/matters/create-matter-webhook-subscription /openapi.json post /matters/v1/{id}/events/subscriptions Creates a webhook subscription for matter and work-item events. # Create party Source: https://docs.case.dev/api-reference/matters/create-party /openapi.json post /matters/v1/parties Create a reusable legal party for the authenticated organization. # Create work item Source: https://docs.case.dev/api-reference/matters/create-work-item /openapi.json post /matters/v1/{id}/work-items Create an active work item on a matter. # Delete matter share Source: https://docs.case.dev/api-reference/matters/delete-matter-share /openapi.json delete /matters/v1/{id}/shares/{shareId} Revoke a matter share and its linked vault share. # Delete matter webhook subscription Source: https://docs.case.dev/api-reference/matters/delete-matter-webhook-subscription /openapi.json delete /matters/v1/{id}/events/subscriptions/{subscriptionId} Deactivates a matter webhook subscription. # Export matter log entries Source: https://docs.case.dev/api-reference/matters/export-matter-log-entries /openapi.json post /matters/v1/{id}/log/export Bulk export matter log entries for audits, visibility, and eval pipelines. Supports json, csv, tsv, and jsonl. Limited to 10,000 entries per request. # Get matter Source: https://docs.case.dev/api-reference/matters/get-matter /openapi.json get /matters/v1/{id} Get a single matter by ID. # Get matter type Source: https://docs.case.dev/api-reference/matters/get-matter-type /openapi.json get /matters/v1/types/{id} Get a single matter type. # Get party Source: https://docs.case.dev/api-reference/matters/get-party /openapi.json get /matters/v1/parties/{partyId} Get a reusable legal party by ID. # Get work item Source: https://docs.case.dev/api-reference/matters/get-work-item /openapi.json get /matters/v1/{id}/work-items/{workItemId} Get a single work item for a matter. # Inspect a content purge Source: https://docs.case.dev/api-reference/matters/inspect-a-content-purge /openapi.json get /matters/v1/content-purges/{purgeId} Owner-only receipt for operator diagnostics. Integrations must use unified content-purge webhooks rather than polling. # Inspect a Matter purge Source: https://docs.case.dev/api-reference/matters/inspect-a-matter-purge /openapi.json get /matters/v1/purges/{purgeId} Returns a Matter purge receipt for manual diagnostics. Integrations should subscribe to Matter purge webhooks rather than polling this route. # List agent types Source: https://docs.case.dev/api-reference/matters/list-agent-types /openapi.json get /matters/v1/agent-types List reusable agent roles for the authenticated organization. # List matter log entries Source: https://docs.case.dev/api-reference/matters/list-matter-log-entries /openapi.json get /matters/v1/{id}/log List the operational history for a matter. # List matter parties Source: https://docs.case.dev/api-reference/matters/list-matter-parties /openapi.json get /matters/v1/{id}/parties List parties attached to a matter. # List matter shares Source: https://docs.case.dev/api-reference/matters/list-matter-shares /openapi.json get /matters/v1/{id}/shares List cross-org shares for a matter. Owner only. # List matter types Source: https://docs.case.dev/api-reference/matters/list-matter-types /openapi.json get /matters/v1/types List matter types for the authenticated organization. # List matter webhook subscriptions Source: https://docs.case.dev/api-reference/matters/list-matter-webhook-subscriptions /openapi.json get /matters/v1/{id}/events/subscriptions Lists webhook subscriptions configured for a matter. # List matter work items Source: https://docs.case.dev/api-reference/matters/list-matter-work-items /openapi.json get /matters/v1/{id}/work-items List active work items for a matter, newest update first. Pagination is opt-in: pass `limit` (1-200) to receive a bounded page, then replay `pagination.next_cursor` as `?cursor=` while `pagination.has_more` is true. A request with neither `limit` nor `cursor` still returns every work item, and `pagination.limit` is null. That default will become a bounded page in a future release — paginate now to avoid the change. # List matters Source: https://docs.case.dev/api-reference/matters/list-matters /openapi.json get /matters/v1 List matters for the authenticated organization, newest update first. Pagination is opt-in: pass `limit` (1-200) to receive a bounded page, then replay `pagination.next_cursor` as `?cursor=` while `pagination.has_more` is true. Cursors are opaque and are only valid for the exact filter set they were issued under. A request with neither `limit` nor `cursor` still returns every matter, and `pagination.limit` is null. That default will become a bounded page in a future release — paginate now to avoid the change. # List parties Source: https://docs.case.dev/api-reference/matters/list-parties /openapi.json get /matters/v1/parties List reusable legal parties for the authenticated organization, newest update first. Pagination is opt-in: pass `limit` (1-200) to receive a bounded page, then replay `pagination.next_cursor` as `?cursor=` while `pagination.has_more` is true. A request with neither `limit` nor `cursor` still returns every party, and `pagination.limit` is null. That default will become a bounded page in a future release — paginate now to avoid the change. # Make work item decision Source: https://docs.case.dev/api-reference/matters/make-work-item-decision /openapi.json post /matters/v1/{id}/work-items/{workItemId}/decision Approve or block a work item. # Purge a Matter Source: https://docs.case.dev/api-reference/matters/purge-a-matter /openapi.json delete /matters/v1/{id} Queues a durable, idempotent purge of a Matter and all linked live content. Use matter purge webhooks for status changes; the inspection route is intended for manual diagnostics only. # Purge selected Matter content Source: https://docs.case.dev/api-reference/matters/purge-selected-matter-content /openapi.json post /matters/v1/{id}/content-purges Queues an idempotent hard deletion of explicitly owned content while preserving the Matter, Vault, and unrelated content. Use unified matter.content_purge webhooks for completion, not polling. # Update matter Source: https://docs.case.dev/api-reference/matters/update-matter /openapi.json patch /matters/v1/{id} Update mutable matter fields. # Update matter type Source: https://docs.case.dev/api-reference/matters/update-matter-type /openapi.json patch /matters/v1/types/{id} Update a matter type. # Update party Source: https://docs.case.dev/api-reference/matters/update-party /openapi.json patch /matters/v1/parties/{partyId} Update a reusable legal party. # Update work item Source: https://docs.case.dev/api-reference/matters/update-work-item /openapi.json patch /matters/v1/{id}/work-items/{workItemId} Update a matter work item. # Create a captioned media clip Source: https://docs.case.dev/api-reference/media/create-a-captioned-media-clip /openapi.json post /media/v1/clips # Get media clip job Source: https://docs.case.dev/api-reference/media/get-media-clip-job /openapi.json get /media/v1/clips/{id} # Health check Source: https://docs.case.dev/api-reference/media/health-check /openapi.json get /media/v1/health Unauthenticated health check for the Media service. # Retrieve transcript text Source: https://docs.case.dev/api-reference/media/retrieve-transcript-text /openapi.json post /media/v1/transcripts/retrieve Retrieves the full transcript text for a vault transcript object or an audio/video source object with a completed transcription job. When object_id is a source media object, access to that source object grants access to its generated transcript artifact. # Search transcript words Source: https://docs.case.dev/api-reference/media/search-transcript-words /openapi.json post /media/v1/transcripts/search # Add memory Source: https://docs.case.dev/api-reference/memory/add-memory /openapi.json post /memory/v1 Store memories from conversation messages. Automatically extracts facts and handles deduplication. Use tag_1 through tag_12 for filtering - these are generic indexed fields you can use for any purpose: - Legal app: tag_1=client_id, tag_2=matter_id - Healthcare: tag_1=patient_id, tag_2=encounter_id - E-commerce: tag_1=customer_id, tag_2=order_id # Bulk delete memories Source: https://docs.case.dev/api-reference/memory/bulk-delete-memories /openapi.json delete /memory/v1 Delete multiple memories matching tag filter criteria. CAUTION: This will delete all matching memories for your organization. # Delete memory Source: https://docs.case.dev/api-reference/memory/delete-memory /openapi.json delete /memory/v1/{id} Delete a single memory by its ID. # Get memory Source: https://docs.case.dev/api-reference/memory/get-memory /openapi.json get /memory/v1/{id} Retrieve a single memory by its ID. # Health check Source: https://docs.case.dev/api-reference/memory/health-check /openapi.json get /memory/v1/health Check if the Memory service is available. # List memories Source: https://docs.case.dev/api-reference/memory/list-memories /openapi.json get /memory/v1 List all memories with optional filtering by tags and category. # Search memories Source: https://docs.case.dev/api-reference/memory/search-memories /openapi.json post /memory/v1/search Search memories using semantic similarity. Filter by tag fields to narrow results. Use tag_1 through tag_12 for filtering - these are generic indexed fields you define: - Legal app: tag_1=client_id, tag_2=matter_id - Healthcare: tag_1=patient_id, tag_2=encounter_id # Download OCR results Source: https://docs.case.dev/api-reference/ocr/download-ocr-results /openapi.json get /ocr/v1/{id}/download/{type} Download OCR processing results in various formats by redirecting to the OCR service download URL. # Get OCR job status Source: https://docs.case.dev/api-reference/ocr/get-ocr-job-status /openapi.json get /ocr/v1/{id} Retrieve the status and results of an OCR job. Returns job progress and metadata; full extracted text is included only when include_text=true. # Health check Source: https://docs.case.dev/api-reference/ocr/health-check /openapi.json get /ocr/v1/health Unauthenticated health check for the OCR service. # Process document with OCR Source: https://docs.case.dev/api-reference/ocr/process-document-with-ocr /openapi.json post /ocr/v1/process Submit a document for OCR processing to extract text, detect tables, forms, and other features. Supports PDFs, images, and scanned documents. Returns a job ID that can be used to track processing status. # Detect privileged content Source: https://docs.case.dev/api-reference/privilege/detect-privileged-content /openapi.json post /privilege/v1/detect Analyzes text or vault documents for legal privilege review. Detects attorney-client privilege, work product doctrine, and common interest privilege. Returns structured review flags with confidence scores and policy-friendly rationale suitable for discovery workflows and privilege logs. This endpoint is an AI-assisted triage tool and does not replace attorney judgment. **Size Limit:** Maximum 200,000 characters (larger documents rejected). **Permissions:** Requires `chat` permission. When using `document_id`, also requires `vault` permission. **Note:** When analyzing vault documents, results are automatically stored in the document's `privilege_analysis` metadata field. # Extract content from URLs Source: https://docs.case.dev/api-reference/search/extract-content-from-urls /openapi.json post /search/v1/contents Scrapes and extracts text content from web pages, PDFs, and documents. Useful for legal research, evidence collection, and document analysis. Supports live crawling, subpage extraction, and content summarization. # Find similar content Source: https://docs.case.dev/api-reference/search/find-similar-content /openapi.json post /search/v1/similar Find web pages and documents similar to a given URL. Useful for legal research to discover related case law, statutes, or legal commentary that shares similar themes or content structure. # Generate AI-powered answers from web search Source: https://docs.case.dev/api-reference/search/generate-ai-powered-answers-from-web-search /openapi.json post /search/v1/answer Generate comprehensive answers to questions using web search results. Supports two modes: native provider answers or custom LLM-powered answers using Case.dev's AI gateway. Perfect for legal research, fact-checking, and gathering supporting evidence for cases. # Health check Source: https://docs.case.dev/api-reference/search/health-check /openapi.json get /search/v1/health Unauthenticated health check for the Search service. # Perform intelligent web search Source: https://docs.case.dev/api-reference/search/perform-intelligent-web-search /openapi.json post /search/v1/search Executes intelligent web search queries with advanced filtering and customization options. Ideal for legal research, case law discovery, and gathering supporting documentation for litigation or compliance matters. # Browse available skills Source: https://docs.case.dev/api-reference/skills/browse-available-skills /openapi.json get /skills/catalog Browse public and organization skills using one authenticated catalog. Returns metadata only; skill content is loaded separately. # Create custom skill Source: https://docs.case.dev/api-reference/skills/create-custom-skill /openapi.json post /skills Create an org-scoped custom skill. The skill will be searchable via /skills/resolve alongside curated skills. # Delete custom skill Source: https://docs.case.dev/api-reference/skills/delete-custom-skill /openapi.json delete /skills/{slug} Soft-delete an org-scoped custom skill by slug. The skill will no longer appear in search results. # Export skill tree Source: https://docs.case.dev/api-reference/skills/export-skill-tree /openapi.json get /skills/{slug}/export Export a skill as an installable filesystem tree for sandbox runtimes. Authenticated org-scoped custom skills are resolved before curated skills. Slugs of merged skills are permanent aliases: they export the surviving skill (slug, root and files describe the target) with `redirected_from` set to the requested slug. # List custom skills Source: https://docs.case.dev/api-reference/skills/list-custom-skills /openapi.json get /skills/custom List all custom skills for the authenticated organization. Supports cursor-based pagination. # Read skill Source: https://docs.case.dev/api-reference/skills/read-skill /openapi.json get /skills/{slug} Read the full content of a legal skill by its slug. Returns markdown content, tags, and metadata. Slugs of merged skills are permanent aliases: they return the surviving skill with `redirected_from` set to the requested slug instead of an error. # Search skills Source: https://docs.case.dev/api-reference/skills/search-skills /openapi.json get /skills/resolve Search the Legal Skills Store using hybrid search (text + tag + semantic). Returns ranked results with relevance scores. # Update custom skill Source: https://docs.case.dev/api-reference/skills/update-custom-skill /openapi.json put /skills/{slug} Update an org-scoped custom skill by slug. Only provided fields are updated. Version is auto-incremented. # Get API Status Source: https://docs.case.dev/api-reference/system/get-api-status /openapi.json get /index Returns basic information about the Case.dev API including name, version, and health status. This endpoint can be used for health checks and API discovery. # Health check Source: https://docs.case.dev/api-reference/system/health-check /openapi.json get /system/health Unauthenticated health check for the System service. # List documented services Source: https://docs.case.dev/api-reference/system/list-documented-services /openapi.json get /services Returns the public Case.dev services catalog derived from docs.case.dev/services. This endpoint is unauthenticated and intended for discovery surfaces such as the case.dev homepage. # Detect language Source: https://docs.case.dev/api-reference/translation/detect-language /openapi.json post /translate/v1/detect Detect the language of text. Returns the most likely language code and confidence score. Supports batch detection for multiple texts. # Health check Source: https://docs.case.dev/api-reference/translation/health-check /openapi.json get /translate/v1/health Unauthenticated health check for the Translation service. # List supported languages Source: https://docs.case.dev/api-reference/translation/list-supported-languages /openapi.json get /translate/v1/languages Get the list of languages supported for translation. Optionally specify a target language to get translated language names. # Translate a document Source: https://docs.case.dev/api-reference/translation/translate-a-document /openapi.json post /translate/v1/document Translate one TXT, DOCX, or searchable PDF document. DOCX and PDF translations preserve the source document format and retain as much layout and formatting as possible. # Translate text Source: https://docs.case.dev/api-reference/translation/translate-text /openapi.json post /translate/v1/translate Translate text between languages using Google Cloud Translation API. Supports 100+ languages, automatic language detection, HTML preservation, and batch translation. # Create usage webhook subscription Source: https://docs.case.dev/api-reference/usage/create-usage-webhook-subscription /openapi.json post /usage/v1/subscriptions Creates a webhook subscription for usage, balance, and billing events. # Delete usage webhook subscription Source: https://docs.case.dev/api-reference/usage/delete-usage-webhook-subscription /openapi.json delete /usage/v1/subscriptions/{subscriptionId} Deactivates a usage webhook subscription. # Get usage snapshot Source: https://docs.case.dev/api-reference/usage/get-usage-snapshot /openapi.json get /usage/v1 Returns customer-facing usage metrics and costs for the requested period. Supports summary totals and daily buckets for timestamped usage sources. Vault storage is intentionally omitted from totals because it is not yet periodized for arbitrary windows. # List usage webhook subscriptions Source: https://docs.case.dev/api-reference/usage/list-usage-webhook-subscriptions /openapi.json get /usage/v1/subscriptions Lists webhook subscriptions configured for usage and billing events. # Send test usage webhook event Source: https://docs.case.dev/api-reference/usage/send-test-usage-webhook-event /openapi.json post /usage/v1/subscriptions/{subscriptionId}/test Delivers a test event to a single usage webhook subscription using the same payload shape and signing behavior as production delivery. # Update usage webhook subscription Source: https://docs.case.dev/api-reference/usage/update-usage-webhook-subscription /openapi.json patch /usage/v1/subscriptions/{subscriptionId} Updates callback URL, event filters, active state, or signing secret. # Create vault webhook subscription Source: https://docs.case.dev/api-reference/vault-events/create-vault-webhook-subscription /openapi.json post /vault/{id}/events/subscriptions Creates a webhook subscription for vault lifecycle events. Optional object filters can limit notifications to specific vault objects. # Delete vault webhook subscription Source: https://docs.case.dev/api-reference/vault-events/delete-vault-webhook-subscription /openapi.json delete /vault/{id}/events/subscriptions/{subscriptionId} Deactivates a vault webhook subscription. # List vault webhook subscriptions Source: https://docs.case.dev/api-reference/vault-events/list-vault-webhook-subscriptions /openapi.json get /vault/{id}/events/subscriptions Lists webhook subscriptions configured for a vault. # Send test webhook event Source: https://docs.case.dev/api-reference/vault-events/send-test-webhook-event /openapi.json post /vault/{id}/events/subscriptions/{subscriptionId}/test Delivers a test event to a single vault webhook subscription. Uses the same payload shape, signature, and retry behavior as production event delivery. # Update vault webhook subscription Source: https://docs.case.dev/api-reference/vault-events/update-vault-webhook-subscription /openapi.json patch /vault/{id}/events/subscriptions/{subscriptionId} Updates callback URL, filters, active state, or signing secret for a vault webhook subscription. # Create vault memory entry Source: https://docs.case.dev/api-reference/vault-memory/create-vault-memory-entry /openapi.json post /vault/{id}/memory Append a new file-backed memory entry to a vault. # Delete vault memory entry Source: https://docs.case.dev/api-reference/vault-memory/delete-vault-memory-entry /openapi.json delete /vault/{id}/memory/{entryId} Remove a file-backed memory entry from a vault. # List vault memory entries Source: https://docs.case.dev/api-reference/vault-memory/list-vault-memory-entries /openapi.json get /vault/{id}/memory Retrieve file-backed memory entries stored in a vault. # Search vault memory Source: https://docs.case.dev/api-reference/vault-memory/search-vault-memory /openapi.json post /vault/{id}/memory/search Search file-backed vault memory using simple full-text matching over content and tags. # Update vault memory entry Source: https://docs.case.dev/api-reference/vault-memory/update-vault-memory-entry /openapi.json patch /vault/{id}/memory/{entryId} Rewrite a file-backed vault memory entry with updated content, source, or tags. # Append PDF vault objects onto an existing PDF vault object Source: https://docs.case.dev/api-reference/vault-objects/append-pdf-vault-objects-onto-an-existing-pdf-vault-object /openapi.json post /vault/{id}/objects/{objectId}/append Merges one or more PDF vault objects onto the end of an existing PDF vault object. Sync mode is the default and overwrites the target in place before returning. Async mode returns 202 immediately and reports completion through vault.object.append webhooks. Optionally rewrites citation links in the original target into internal PDF jumps and adds back links on appended pages. The target object’s ingestion state is not affected; appended pages are not searchable. # Assemble PDF volumes from vault objects Source: https://docs.case.dev/api-reference/vault-objects/assemble-pdf-volumes-from-vault-objects /openapi.json post /vault/{id}/assemblies Starts an asynchronous, deterministic PDF assembly. The manifest selects page ranges from source PDFs in output order, adds an outline and optional continuous Bates numbering, and splits the result into volumes. Each volume becomes a new vault object. Source bookmarks, form fields and page labels are not carried over. Outputs are not indexed automatically. Completion is reported through vault.assembly webhooks. # Create a searchable PDF from ordered vault objects Source: https://docs.case.dev/api-reference/vault-objects/create-a-searchable-pdf-from-ordered-vault-objects /openapi.json post /vault/{id}/objects/merge Starts an asynchronous merge that creates a new PDF vault object. Source objects are unchanged. Missing searchable PDF renditions are generated on demand before combining. Completion is reported through vault.object.merge webhooks. # Delete vault object Source: https://docs.case.dev/api-reference/vault-objects/delete-vault-object /openapi.json delete /vault/{id}/objects/{objectId} Permanently deletes a document from the vault including all associated vectors, chunks, graph data, and the original file. This operation cannot be undone. # Download vault object Source: https://docs.case.dev/api-reference/vault-objects/download-vault-object /openapi.json get /vault/{id}/objects/{objectId}/download Downloads a file from a vault by redirecting to a short-lived presigned S3 URL. Useful for retrieving contracts, depositions, case files, and other legal documents stored in your vault. # Generate presigned URL for object operations Source: https://docs.case.dev/api-reference/vault-objects/generate-presigned-url-for-object-operations /openapi.json post /vault/{id}/objects/{objectId}/presigned-url Generate presigned URLs for direct S3 operations (GET, PUT, DELETE, HEAD) on vault objects. This allows secure, time-limited access to files without proxying through the API. Essential for large document uploads/downloads in legal workflows. # Get a PDF assembly Source: https://docs.case.dev/api-reference/vault-objects/get-a-pdf-assembly /openapi.json get /vault/{id}/assemblies/{assemblyId} Returns the status of a PDF assembly. Completed volumes include their page count, size, SHA-256 and Bates range. # Get full object chunks Source: https://docs.case.dev/api-reference/vault-objects/get-full-object-chunks /openapi.json get /vault/{id}/objects/{objectId}/chunks Retrieves full extracted chunk text for a processed vault object. Use this after search when a truncated preview is not enough and you need the exact chunk text or adjacent chunks for surrounding context such as tables, exhibit lists, or multi-part passages. # Get object pages Source: https://docs.case.dev/api-reference/vault-objects/get-object-pages /openapi.json get /vault/{id}/objects/{objectId}/pages Retrieves the raw text of a processed vault object split by page. The object must have completed ingestion before pages can be retrieved — for PDFs this requires the OCR pipeline to have finished writing the per-page sidecar, so freshly uploaded PDFs return 400 with the current `ingestionStatus` until processing completes. For PDFs this returns the per-page OCR text. For plain text files (txt, md, source code, court reporter transcripts) the text is split using right-aligned page-number markers when present (preserving the original document numbering, including continuations like Volume 2 starting at page 234), falling back to form-feed (\f) page-break characters, and finally a single page if neither signal is present. Use the optional `start` and `end` query parameters to fetch a specific inclusive page range. Pages with no text are omitted. # Get object text Source: https://docs.case.dev/api-reference/vault-objects/get-object-text /openapi.json get /vault/{id}/objects/{objectId}/text Retrieves the full extracted text content from a processed vault object, page-numbered (--- Page N --- markers) when the source document is paginated. Useful for document review, analysis, or export. The object must have completed processing before text can be retrieved. # Get OCR word bounding boxes Source: https://docs.case.dev/api-reference/vault-objects/get-ocr-word-bounding-boxes /openapi.json get /vault/{id}/objects/{objectId}/ocr-words Retrieves word-level OCR bounding box data for a processed PDF document. Each word includes its text, normalized bounding box coordinates (0-1 range), confidence score, and global word index. Use this data to highlight specific text ranges in a PDF viewer based on word indices from search results. # Get vault object with download URL Source: https://docs.case.dev/api-reference/vault-objects/get-vault-object-with-download-url /openapi.json get /vault/{id}/objects/{objectId} Retrieves metadata for a specific document in a vault and generates a temporary download URL. The download URL expires after 1 hour for security. This endpoint also updates the file size if it wasn't previously calculated. # List vault objects Source: https://docs.case.dev/api-reference/vault-objects/list-vault-objects /openapi.json get /vault/{id}/objects Retrieve the objects stored in a specific vault, oldest first, including document metadata, ingestion status, and processing statistics. Pass `limit` to page through large vaults: when `pagination.has_more` is true, the response is incomplete and `pagination.next_cursor` fetches the rest. # Move files to a folder Source: https://docs.case.dev/api-reference/vault-objects/move-files-to-a-folder /openapi.json post /vault/{id}/objects/organize Atomically moves up to 500 files to a folder. Authoritative transcription results follow source media. Selecting a transcription result requires selecting its source media too. Source and destination folders remain durable even when empty. Metadata only; requires vault-wide write access and vault ownership. # Move or copy objects between accessible vaults Source: https://docs.case.dev/api-reference/vault-objects/move-or-copy-objects-between-accessible-vaults /openapi.json post /vault/{id}/objects/move Copies storage and search data without downloading the file through the client. Moves preserve object IDs; copies return new IDs. Extracted ZIP children travel with their parent. Retry failed objects with the same Idempotency-Key; successful objects are replayed without transfer. Object ID order does not affect the key. # Update vault object Source: https://docs.case.dev/api-reference/vault-objects/update-vault-object /openapi.json patch /vault/{id}/objects/{objectId} Update a document's filename, folder path, or metadata. Use this to rename files or organize them into virtual folders. The path is a folder, not a complete file path, and is stored separately from the filename. # Abort multipart upload Source: https://docs.case.dev/api-reference/vaults/abort-multipart-upload /openapi.json post /vault/{id}/multipart/abort Abort a multipart upload and discard uploaded parts (live). # Complete multipart upload Source: https://docs.case.dev/api-reference/vaults/complete-multipart-upload /openapi.json post /vault/{id}/multipart/complete Complete a multipart upload by providing the list of part numbers and ETags (live). Single PUT uploads are capped at 5GB; multipart default max is 16GB (configurable). # Confirm vault upload result Source: https://docs.case.dev/api-reference/vaults/confirm-vault-upload-result /openapi.json post /vault/{id}/upload/{objectId}/confirm Confirm whether a direct-to-S3 vault upload succeeded or failed. This endpoint emits vault.upload.completed or vault.upload.failed events and is idempotent for repeated confirmations. Conditional fields: when success=true, sizeBytes is required; when success=false, errorCode and errorMessage are required. These rules are enforced server-side with specific 400 responses. # Create a new vault Source: https://docs.case.dev/api-reference/vaults/create-a-new-vault /openapi.json post /vault Creates a new secure vault with dedicated S3 storage and vector search capabilities. Each vault provides isolated document storage with semantic search and OCR processing for legal document analysis and discovery. # Create a persistent folder Source: https://docs.case.dev/api-reference/vaults/create-a-persistent-folder /openapi.json post /vault/{id}/folders Creates a durable empty folder and missing parents. Metadata only; no S3 objects are created. Requires vault-wide write access and vault ownership. # Create a vault share Source: https://docs.case.dev/api-reference/vaults/create-a-vault-share /openapi.json post /vault/{id}/shares Grant another organization read-only access to this vault. Only the vault owner can create shares. Idempotent: re-sharing to the same org updates the existing share. # Create vault group Source: https://docs.case.dev/api-reference/vaults/create-vault-group /openapi.json post /vault/groups Creates a vault group for organizing vaults and applying group-scoped access controls. Group-scoped API keys cannot create or manage vault groups. # Delete vault Source: https://docs.case.dev/api-reference/vaults/delete-vault /openapi.json delete /vault/{id} Permanently deletes a vault and all its contents including documents, vectors, graph data, and S3 buckets. This operation cannot be undone. For large vaults, use the async=true query parameter to queue deletion in the background. # Delete vault group Source: https://docs.case.dev/api-reference/vaults/delete-vault-group /openapi.json delete /vault/groups/{groupId} Soft-deletes a vault group that no longer has any active vaults assigned. This operation is blocked when the group still contains vaults. # Generate presigned upload URL for vault file Source: https://docs.case.dev/api-reference/vaults/generate-presigned-upload-url-for-vault-file /openapi.json post /vault/{id}/upload Generate a presigned URL for uploading files directly to a vault's S3 storage. After uploading to S3, confirm the upload result via POST /vault/:vaultId/upload/:objectId/confirm before triggering ingestion. # Get presigned URLs for multipart upload parts Source: https://docs.case.dev/api-reference/vaults/get-presigned-urls-for-multipart-upload-parts /openapi.json post /vault/{id}/multipart/part-urls Generate presigned URLs for individual multipart upload parts (live). # Get vault information Source: https://docs.case.dev/api-reference/vaults/get-vault-information /openapi.json get /vault/{id} Retrieve detailed information about a specific vault, including storage configuration, chunking strategy, and usage statistics. Returns vault metadata, bucket information, and vector storage details. # Health check Source: https://docs.case.dev/api-reference/vaults/health-check /openapi.json get /vault/health Unauthenticated health check for the Vault service. # Ingest vault object Source: https://docs.case.dev/api-reference/vaults/ingest-vault-object /openapi.json post /vault/{id}/ingest/{objectId} Triggers ingestion workflow for a vault object to extract text, generate chunks, and create embeddings. For supported file types (PDF, DOCX, PPTX, XLSX, TXT, RTF, XML, HTML, Markdown, CSV/TSV, JSON/YAML/TOML, common source code files, ZIP, audio, video), processing happens asynchronously. ZIP archives always return a processing response, are unpacked recursively up to 5 levels, and each extracted file is created as an independent vault object and ingested via the normal pipeline. For unsupported types (images, etc.), the file is marked as completed immediately without text extraction. # Initiate multipart upload for vault file Source: https://docs.case.dev/api-reference/vaults/initiate-multipart-upload-for-vault-file /openapi.json post /vault/{id}/multipart/init Initiate a multipart upload for large files (>5GB). Single PUT uploads are capped at 5GB; multipart default max is 16GB (configurable). Multipart uploads are supported in production. Returns an uploadId and object metadata. Use part URLs endpoint to upload parts and complete endpoint to finalize. # List all vaults Source: https://docs.case.dev/api-reference/vaults/list-all-vaults /openapi.json get /vault List all vaults for the authenticated organization. Returns vault metadata including name, description, storage configuration, and usage statistics. Pagination is opt-in: pass `limit` (1-200) to receive a bounded page, then replay `pagination.next_cursor` as `?cursor=` while `pagination.has_more` is true. A request with neither `limit` nor `cursor` still returns every vault, and `pagination.limit` is null. That default will become a bounded page in a future release — paginate now to avoid the change. # List persistent folders Source: https://docs.case.dev/api-reference/vaults/list-persistent-folders /openapi.json get /vault/{id}/folders Lists durable folder paths, including empty folders. Combine with paginated object paths to display imported folders. Requires vault-wide read access; shared vault reads are supported. # List vault groups Source: https://docs.case.dev/api-reference/vaults/list-vault-groups /openapi.json get /vault/groups Lists vault groups visible to the authenticated organization. Group-scoped API keys only receive groups within their allowed scope. # List vault shares Source: https://docs.case.dev/api-reference/vaults/list-vault-shares /openapi.json get /vault/{id}/shares List all cross-org shares for a vault. Only the vault owner can list shares. # Receive OCR callback relay events Source: https://docs.case.dev/api-reference/vaults/receive-ocr-callback-relay-events /openapi.json post /vault/ocr/callback Public relay endpoint for OCR completion callbacks. Validates a signed callback target and forwards the payload to the suspended workflow webhook. # Rename or move a folder Source: https://docs.case.dev/api-reference/vaults/rename-or-move-a-folder /openapi.json patch /vault/{id}/folders Atomically renames or moves a folder, its empty descendants and all descendant object paths. Rejects an existing destination, root and self-descendant moves, and busy objects. Supports vaults with at most 25000 objects. Uses a 5-second lock timeout and 30-second statement timeout. Does not transfer file bytes. Requires vault-wide write access and vault ownership. # Revoke a vault share Source: https://docs.case.dev/api-reference/vaults/revoke-a-vault-share /openapi.json delete /vault/{id}/shares/{shareId} Revoke cross-org access to a vault. Only the vault owner can revoke shares. # Search vault documents Source: https://docs.case.dev/api-reference/vaults/search-vault-documents /openapi.json post /vault/{id}/search Search across vault documents using hybrid vector + BM25 search (default), fast vector similarity search, or a simple vector fallback. Returns matching chunks and their source documents. # Update vault group Source: https://docs.case.dev/api-reference/vaults/update-vault-group /openapi.json patch /vault/groups/{groupId} Updates a vault group for the authenticated organization. Only provided fields are changed, and setting description to null removes the current description. # Update vault settings Source: https://docs.case.dev/api-reference/vaults/update-vault-settings /openapi.json patch /vault/{id} Update vault settings including name, description, and group membership. # Create transcription job Source: https://docs.case.dev/api-reference/voice/create-transcription-job /openapi.json post /voice/transcription Creates an asynchronous transcription job for audio or video files. Supports two modes: **Vault-based (recommended)**: Pass `vault_id` and `object_id` to transcribe media from your vault. Large videos are converted to an internal MP3 derivative before transcription while the original video remains the transcript source. The transcript is automatically saved back to the vault when complete. **Direct URL (legacy)**: Pass `audio_url` for direct transcription without automatic storage. # Delete transcription Source: https://docs.case.dev/api-reference/voice/delete-transcription /openapi.json delete /voice/transcription/{id} Deletes a transcription job. For managed vault jobs (tr_*), also removes local job records and managed transcript result objects. Idempotent: returns success if already deleted. # Extract boost list from documents Source: https://docs.case.dev/api-reference/voice/extract-boost-list-from-documents /openapi.json post /voice/boost-list/extract Extracts a categorized word boost list from vault documents or raw text using LLM entity extraction. The resulting words can be passed as `keyterms_prompt` (or the legacy `word_boost` alias) to the transcription endpoint for improved accuracy. # Generate boost list from transcript Source: https://docs.case.dev/api-reference/voice/generate-boost-list-from-transcript /openapi.json post /voice/boost-list/generate Generates a categorized word boost list from a completed transcription job. Extracts entities from the pass-1 transcript for use as `keyterms_prompt` (or the legacy `word_boost` alias) in a second transcription pass. # Get streaming transcription WebSocket URL Source: https://docs.case.dev/api-reference/voice/get-streaming-transcription-websocket-url /openapi.json get /voice/streaming/url Returns the WebSocket URL and connection details for real-time audio transcription. The returned URL can be used to establish a WebSocket connection for streaming audio data and receiving transcribed text in real-time. **Audio Requirements:** - Sample Rate: 16kHz - Encoding: PCM 16-bit little-endian - Channels: Mono (1 channel) **Pricing:** $0.01 per minute ($0.60 per hour) # Get transcription status Source: https://docs.case.dev/api-reference/voice/get-transcription-status /openapi.json get /voice/transcription/{id} Retrieve the status and result of an audio transcription job. For vault-based jobs, returns status and result_object_id when complete. For legacy direct URL jobs, returns the full transcription data. # Health check Source: https://docs.case.dev/api-reference/voice/health-check /openapi.json get /voice/health Unauthenticated health check for the Voice service. # List available voices Source: https://docs.case.dev/api-reference/voice/list-available-voices /openapi.json get /voice/v1/voices Retrieve a list of available voices for text-to-speech synthesis. This endpoint provides access to a comprehensive catalog of voices with various characteristics, languages, and styles suitable for legal document narration, client presentations, and accessibility purposes. # Stream text-to-speech audio Source: https://docs.case.dev/api-reference/voice/stream-text-to-speech-audio /openapi.json post /voice/v1/speak/stream Convert text to speech using ElevenLabs AI voices with streaming for real-time playback. Returns audio data as an MP3 stream for immediate playback with minimal latency. Perfect for legal document narration, client presentations, or accessibility features. # Text-to-speech synthesis Source: https://docs.case.dev/api-reference/voice/text-to-speech-synthesis /openapi.json post /voice/v1/speak Convert text to natural-sounding audio using ElevenLabs voices. Ideal for creating audio summaries of legal documents, client presentations, or accessibility features. Supports multiple languages and voice customization. # Create webhook endpoint Source: https://docs.case.dev/api-reference/webhooks/create-webhook-endpoint /openapi.json post /webhooks/v1/endpoints Creates a webhook endpoint that receives platform events matching the supplied event-type filters. Returns the generated signing secret ONCE — the response is the only time it is shown in plaintext. # Delete webhook endpoint Source: https://docs.case.dev/api-reference/webhooks/delete-webhook-endpoint /openapi.json delete /webhooks/v1/endpoints/{id} Soft-deletes a webhook endpoint. Delivery stops immediately and the endpoint no longer appears in list results. Delivery history is preserved (and can be fetched via GET /deliveries with the endpoint_id filter) so audit trails and post-mortem debugging remain possible. # Get webhook delivery Source: https://docs.case.dev/api-reference/webhooks/get-webhook-delivery /openapi.json get /webhooks/v1/deliveries/{id} # Get webhook endpoint Source: https://docs.case.dev/api-reference/webhooks/get-webhook-endpoint /openapi.json get /webhooks/v1/endpoints/{id} # List subscribable event types Source: https://docs.case.dev/api-reference/webhooks/list-subscribable-event-types /openapi.json get /webhooks/v1/event_types Returns the catalog of event types that can be subscribed to via webhook endpoints. Each entry lists the required service scope the API key must carry to subscribe, plus the stability level. # List webhook deliveries Source: https://docs.case.dev/api-reference/webhooks/list-webhook-deliveries /openapi.json get /webhooks/v1/deliveries Returns delivery attempts for the organization, newest first. Filter by endpoint_id or status to narrow results. # List webhook endpoints Source: https://docs.case.dev/api-reference/webhooks/list-webhook-endpoints /openapi.json get /webhooks/v1/endpoints Returns the organization's webhook endpoints, newest first. Signing secrets are never included. # Replay a webhook delivery Source: https://docs.case.dev/api-reference/webhooks/replay-a-webhook-delivery /openapi.json post /webhooks/v1/deliveries/{id}/replay Re-sends the original event to its endpoint. The payload is reconstructed from the delivery record (same eventId, eventType, and occurred_at). Replay deliveries include a Case.dev replay marker header so receivers can distinguish replays from first-time deliveries. Uses the endpoint's current signing secret — not the one in force at the original delivery time. # Rotate webhook signing secret Source: https://docs.case.dev/api-reference/webhooks/rotate-webhook-signing-secret /openapi.json post /webhooks/v1/endpoints/{id}/rotate_secret Generates a new signing secret for the endpoint. The previous secret remains valid until `previousSecretExpiresInSec` elapses (default 24h, max 30 days). During the grace window deliveries are signed with both secrets so receivers can migrate without downtime. Returns the new secret — this is the only time it is shown in plaintext. # Send a test event to a webhook endpoint Source: https://docs.case.dev/api-reference/webhooks/send-a-test-event-to-a-webhook-endpoint /openapi.json post /webhooks/v1/endpoints/{id}/test Synchronously delivers a synthetic `webhook.test` event to the endpoint and returns the HTTP result. No retries. Useful for validating that a new endpoint is reachable and its signature verifier works. The delivery is not persisted in the delivery history. # Update webhook endpoint Source: https://docs.case.dev/api-reference/webhooks/update-webhook-endpoint /openapi.json patch /webhooks/v1/endpoints/{id} Partially updates a webhook endpoint. Any omitted field is left unchanged. Signing secrets are rotated via the separate /rotate_secret endpoint. # CLI Source: https://docs.case.dev/cli Manage Case.dev resources from the command line The Case.dev CLI (`casedev`) gives you full access to the Case.dev API from your terminal. Every API operation is exposed as a CLI command, making it easy to script workflows, test integrations, and manage resources without writing code. ## Installation ```bash title="Homebrew (recommended)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} brew install CaseMark/casedev/casedev ``` ```bash title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} go install github.com/CaseMark/casedev-cli/cmd/casedev@latest ``` Pre-built binaries for macOS, Linux, and Windows are available on [GitHub Releases](https://github.com/CaseMark/casedev-cli/releases). ### Verify installation ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev --version ``` ## Authentication The CLI reads your API key from the `CASEDEV_API_KEY` environment variable. Get your key from the [Case.dev dashboard](https://app.case.dev). ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} export CASEDEV_API_KEY=sk_case_YOUR_API_KEY ``` > [!TIP] > > Add the export to your shell profile (`~/.bashrc`, `~/.zshrc`, etc.) so it persists across > sessions. API keys starting with `sk_case_` are production keys. Development keys are available for testing. ## Quick Start ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Chat with an LLM casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{"role":"user","content":"Summarize this contract..."}' # Search a vault casedev vault search \ --id vault_abc123 \ --query "termination clauses" # List available models casedev llm:v1 list-models # Run OCR on a document already accessible by URL casedev ocr:v1 process --document-url https://example.com/contract.pdf # Transcribe audio already accessible by URL casedev voice:transcription create --audio-url https://example.com/deposition.mp3 ``` > [!NOTE] > > OCR and voice transcription accept URLs, not local file paths. To process a local file, upload it > to a vault first (see [File uploads](#file-uploads) below), then pass the vault-generated > presigned URL — or the `--vault-id` / `--object-id` pair, where supported — into the processing > command. ## Command Structure Commands follow a `resource[:version][:sub] action` pattern that mirrors the API. Resource names use colons, not slashes: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion # LLM chat casedev vault search # Vault search casedev ocr:v1 process # OCR processing casedev voice:transcription create # Voice transcription casedev legal:v1 find # Legal research casedev search:v1 answer # Web search AI answer ``` List all available resources with `casedev --help`, and inspect a resource's subcommands with `casedev --help`: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev --help casedev vault --help casedev llm:v1:chat create-completion --help ``` ## Output Formats Control how results are displayed with the `--format` global flag (`auto`, `explore`, `json`, `jsonl`, `pretty`, `raw`, `yaml`): ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # JSON output (pipe-friendly) casedev llm:v1 list-models --format json # YAML output casedev llm:v1 list-models --format yaml # Interactive explorer casedev llm:v1 list-models --format explore ``` JSON output works well with tools like `jq`: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 list-models --format json | jq '.data[].id' ``` You can also reshape output with the `--transform` flag, which accepts a [GJSON](https://github.com/tidwall/gjson) path: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 list-models --transform 'data.#.id' ``` ## File uploads The CLI does **not** accept local file paths as a `--file` argument. Uploads happen directly to S3 via a short-lived presigned URL. The flow is always: 1. Request a presigned upload URL from the vault (`casedev vault upload ...`). 2. `PUT` the file bytes to that URL (e.g. with `curl`). 3. Confirm the upload to record the final size and ETag (`casedev vault confirm-upload ...`). 4. Trigger ingestion if your vault has indexing enabled (`casedev vault ingest ...`). ```bash title="Upload a local PDF to a vault" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} VAULT_ID=vault_abc123 FILE=./contract.pdf SIZE=$(wc -c < "$FILE" | tr -d ' ') # 1. Request a presigned upload URL UPLOAD=$(casedev vault upload \ --id "$VAULT_ID" \ --filename "contract.pdf" \ --content-type "application/pdf" \ --size-bytes "$SIZE" \ --auto-index \ --format json) OBJECT_ID=$(echo "$UPLOAD" | jq -r '.objectId') UPLOAD_URL=$(echo "$UPLOAD" | jq -r '.uploadUrl') # 2. Upload the bytes directly to S3 curl -X PUT \ -H "Content-Type: application/pdf" \ --data-binary "@$FILE" \ "$UPLOAD_URL" # 3. Confirm the upload casedev vault confirm-upload \ --id "$VAULT_ID" \ --object-id "$OBJECT_ID" \ --success \ --size-bytes "$SIZE" # 4. Trigger ingestion (skip if --auto-index was not set or the vault is storage-only) casedev vault ingest --id "$VAULT_ID" --object-id "$OBJECT_ID" ``` For files larger than 5 GB, use `casedev vault:multipart get-part-urls` to obtain per-part presigned URLs and upload each part separately. See [Vault uploads](/vault/upload) for the complete reference, including multipart uploads and error handling. ### OCR and voice transcription with local files Neither `ocr:v1 process` nor `voice:transcription create` accept local file paths. Two paths work: * **Already-hosted file**: pass `--document-url` (OCR) or `--audio-url` (voice) pointing to a publicly reachable HTTPS URL or a presigned S3 URL. * **Local file**: upload it to a vault first (flow above), then either pass the vault's presigned download URL or — for voice transcription — the `--vault-id` + `--object-id` pair directly. ```bash title="OCR a local PDF via vault" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # After the upload flow above: PRESIGNED=$(casedev vault:objects create-presigned-url \ --id "$VAULT_ID" \ --object-id "$OBJECT_ID" \ --operation GET \ --expires-in 3600 \ --transform 'presignedUrl') casedev ocr:v1 process --document-url "$PRESIGNED" ``` ```bash title="Transcribe a local audio file via vault" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Voice transcription can read directly from the vault without a presigned URL. casedev voice:transcription create \ --vault-id "$VAULT_ID" \ --object-id "$OBJECT_ID" \ --speaker-labels \ --punctuate ``` ## Piping and stdin Most commands accept a JSON (or YAML) body on stdin. Any unset flag is filled from the stdin object, so you can compose commands without building long flag lists: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Pipe a full JSON payload echo '{"model":"openai/gpt-6-sol","messages":[{"role":"user","content":"Hello"}]}' \ | casedev llm:v1:chat create-completion # Chain commands: summarize vault search results casedev vault search --id vault_abc123 --query "liability" --format json \ | jq '{model:"openai/gpt-6-sol", messages:[{role:"user", content:(.results[0].content // "no results")}]}' \ | casedev llm:v1:chat create-completion ``` ## Shell completions Enable tab completions for your shell: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Bash casedev completion bash > /etc/bash_completion.d/casedev # Zsh casedev completion zsh > "${fpath[1]}/_casedev" # Fish casedev completion fish > ~/.config/fish/completions/casedev.fish ``` Restart your shell or source the completion file to activate. ## Debugging Use `--debug` to see full HTTP request and response details: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search --id vault_abc123 --query "test" --debug ``` This prints request headers, body, response status, and timing information to stderr. > [!WARNING] > > Debug output may contain your API key and sensitive request payloads. Redact credentials and > confidential data before sharing logs externally. ## Upgrading ```bash title="Homebrew" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} brew upgrade casedev ``` ```bash title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} go install github.com/CaseMark/casedev-cli/cmd/casedev@latest ``` ## Repositories * **CLI source:** [github.com/CaseMark/casedev-cli](https://github.com/CaseMark/casedev-cli) * **Homebrew tap:** [github.com/CaseMark/homebrew-casedev](https://github.com/CaseMark/homebrew-casedev) ## Next Steps > [card] [SDKs](/sdks) > > Official client libraries for TypeScript, Python, and Go > [card] [API Reference](/api-reference) > > Complete API documentation with interactive examples > [card] [Getting Started](/getting-started) > > Integration tutorials with step-by-step examples # Compute Overview Source: https://docs.case.dev/compute/index On-demand GPU instances with your vaults mounted as a filesystem Provision a GPU instance for batch OCR, training, inference, or any workload that needs dedicated hardware. Attach one or more [vaults](/vault/index) at launch and they mount at `/mnt/vault/{name}/` — no manual uploads, no long-lived AWS keys. Pricing is per-second with a 1-minute minimum. The `pricePerHour` on every response already includes the 20% platform fee. Query `GET /compute/v1/instance-types` for live availability and `GET /compute/v1/pricing` for a sorted rate sheet. ## Launch an instance ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/compute/v1/instances \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "ocr-batch", "instanceType": "gpu_1x_a10", "region": "us-west-1", "autoShutdownMinutes": 60, "vaultIds": [""] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev compute:v1:instances create \ --name ocr-batch \ --instance-type gpu_1x_a10 \ --region us-west-1 \ --auto-shutdown-minutes 60 \ --vault-ids '[""]' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const instance = await client.compute.v1.instances.create({ name: 'ocr-batch', instanceType: 'gpu_1x_a10', region: 'us-west-1', autoShutdownMinutes: 60, vaultIds: [''], }); console.log(instance.id, instance.status); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev, os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) instance = client.compute.v1.instances.create( name='ocr-batch', instance_type='gpu_1x_a10', region='us-west-1', auto_shutdown_minutes=60, vault_ids=[''], ) print(instance.id, instance.status) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} instance, _ := client.Compute.V1.Instances.New(ctx, casedev.ComputeV1InstanceNewParams{ Name: casedev.F("ocr-batch"), InstanceType: casedev.F("gpu_1x_a10"), Region: casedev.F("us-west-1"), AutoShutdownMinutes: casedev.F(int64(60)), VaultIds: casedev.F([]string{""}), }) fmt.Println(instance.ID, instance.Status) ``` The response includes the instance `id`, initial `status: "booting"`, and the generated SSH key name. Poll `instances.retrieve(id)` (any language) until `status === "running"` and the response includes `ssh.privateKey` + `vaultMounts.setupScript`. > [!WARNING] > > Always set `autoShutdownMinutes`. Instances bill per-second until terminated — auto-shutdown is what saves you from a stalled workload. ## After the launch Boot takes 2–5 minutes. Poll until `status === "running"`, then pull the SSH key and the generated vault-mount script: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} RESP=$(curl -s -H "Authorization: Bearer $CASEDEV_API_KEY" \ https://api.case.dev/compute/v1/instances/) echo "$RESP" | jq -r '.ssh.privateKey' > ~/.ssh/case_gpu_key && chmod 600 ~/.ssh/case_gpu_key echo "$RESP" | jq -r '.vaultMounts.setupScript' > /tmp/setup-vaults.sh && chmod +x /tmp/setup-vaults.sh IP=$(echo "$RESP" | jq -r '.ip') ``` SSH in, run the setup script, and your attached vaults mount at `/mnt/vault/{vault-name}/`: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} scp -i ~/.ssh/case_gpu_key /tmp/setup-vaults.sh ubuntu@$IP:~/ ssh -i ~/.ssh/case_gpu_key ubuntu@$IP # On the VM ./setup-vaults.sh ls /mnt/vault/ ``` Reads and writes under `/mnt/vault/` go through rclone using short-lived, vault-scoped STS credentials — the setup script configures all of that. When you're done: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X DELETE https://api.case.dev/compute/v1/instances/ \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ## Credential lifecycle The setup script contains **short-lived AWS STS credentials**, not static keys. They're minted fresh on every `GET` of the instance via `sts:AssumeRoleWithWebIdentity` with a SessionPolicy scoped to just your attached vault buckets. * **12-hour TTL.** After expiry, rclone fails with `ExpiredToken`. Re-GET the instance for a fresh script and restart the mount. * **Per-instance scope.** Leaked creds can't reach another instance's vaults, other S3 buckets, or any non-S3 AWS service. * **`compute:write` required** to receive the SSH private key and setup script. `compute:read` keys see instance metadata without that material. > [!NOTE] > > For workloads that run longer than 12 hours, keep `autoShutdownMinutes ≤ 720`, or script the credential refresh in step 3 against a cron on the VM. ## Permissions | Scope | What it allows | | - | - | | `compute:read` | List instance types, list your instances, view instance metadata | | `compute:write` | Launch, terminate, retrieve SSH key + vault setup script | ## Related * [API Reference → Compute](/api-reference/compute) — full schemas for every `/compute/v1/*` endpoint * [Vaults](/vault/index) — the storage that mounts into your instances * [Sovereign Legal AI](/compute/sovereign-ai) — dedicated model hosting for compliance-bound clients # Sovereign Legal AI Source: https://docs.case.dev/compute/sovereign-ai Dedicated model deployments for clients with specific requirements Everything on Case.dev runs in SOC 2 Type II and HIPAA-compliant infrastructure. For clients with specific regulatory, contractual, or policy requirements, we offer dedicated deployment options. *** ## When you need Sovereign Legal AI Most Case.dev customers are well-served by our standard services. Sovereign AI is for situations like: * **Client contracts require dedicated infrastructure** — Some enterprise clients mandate that their data never touch shared resources * **Regulatory requirements specify data residency** — Certain jurisdictions require data to stay in specific regions or environments * **Internal policies require your own cloud** — Some organizations can only use AI services deployed within their own AWS, Azure, or GCP accounts If none of these apply to you, our standard services are already compliant and secure. Sovereign AI exists for specific requirements, not as a "more secure" tier. *** ## Deployment options ### Dedicated Model Hosting We run CaseMark Core — our legal-optimized model — on a dedicated GPU cluster exclusively for your organization. **What you get:** * Dedicated GPU infrastructure (no shared inference) * Complete data isolation * We manage everything: updates, scaling, monitoring * API access identical to our standard LLM endpoints **Best for:** * Organizations processing high volumes of privileged documents * Clients who require contractual guarantees about dedicated resources * Teams who want the simplicity of an API with the assurance of dedicated infrastructure > [!NOTE] > > CaseMark Core is optimized for legal workflows: document analysis, contract review, deposition summarization, and legal research. *** ### Dedicated Frontier Models Run the latest versions of GPT, Claude, and Gemini on dedicated instances in Case.dev's secure cloud. **What you get:** * Dedicated capacity for frontier models * No shared inference queues * Same compliance guarantees as all Case.dev services * We manage the deployment and handle provider relationships **Best for:** * Clients whose contracts require dedicated model instances * High-volume inference workloads where shared capacity isn't acceptable * Organizations that need to demonstrate dedicated resources to their clients **Available models:** * GPT-5.2 (dedicated) * Claude 4.5 (dedicated) * Gemini 3 (dedicated) *** ### Your Cloud Deployment We deploy and manage Case.dev services directly in your AWS, Azure, or GCP account. **What you get:** * Full sovereignty: data never leaves your cloud environment * Your security controls, your audit logs, your compliance perimeter * Case.dev manages the deployment: setup, updates, monitoring * Professional services engagement to get you running **Best for:** * Organizations with strict data residency requirements * Enterprises whose policies mandate their own cloud infrastructure * Government and regulated industries with specific compliance needs **Deployment includes:** * CaseMark Core or frontier models (your choice) * All supporting infrastructure (vector databases, queues, etc.) * Integration with your existing identity and access management * Ongoing support and maintenance > [!NOTE] > > Your Cloud deployments are professional services engagements. [Contact us](mailto:sales@case.dev) to discuss your requirements. *** ## Choosing the right option | Requirement | Recommended Option | | - | - | | Need dedicated resources, happy with Case.dev's cloud | **Dedicated Model Hosting** or **Dedicated Frontier Models** | | Must use a specific model provider | **Dedicated Frontier Models** | | Data must stay in your cloud account | **Your Cloud Deployment** | | Just need compliant AI services | Our standard services are already SOC 2 / HIPAA compliant | *** ## Getting started **Dedicated Model Hosting** and **Dedicated Frontier Models** can often be provisioned within a few days. [Contact us](mailto:sales@case.dev) with your requirements. **Your Cloud Deployment** requires a scoping conversation to understand your environment. [Schedule a call](mailto:sales@case.dev) to discuss. *** ## FAQ **Are your standard services not secure?**\ They are. Everything on Case.dev is SOC 2 Type II and HIPAA compliant. Sovereign AI exists for clients with specific contractual or regulatory requirements that mandate dedicated or on-premises deployment — not because it's inherently more secure. **What's the pricing model?**\ Dedicated deployments are priced based on committed capacity. Contact us for a quote based on your expected usage. **Can I switch between options later?**\ Yes. You can start with Dedicated Model Hosting and move to Your Cloud Deployment if your requirements change. We'll help with the migration. **Do I need to manage anything?**\ No. We handle all infrastructure management, updates, and monitoring regardless of deployment option. You just use the API. **What about fine-tuning?**\ CaseMark Core can be further customized for your specific use cases. Contact us to discuss fine-tuning options. # Errors & Recovery Source: https://docs.case.dev/connectors/errors What each failure means and which ones to retry Connector failures fall into two groups: **request errors**, returned immediately from the call you made, and **provider failures**, which happen mid-run and are reported per file. > [!NOTE] > > Raw provider error messages and response bodies are never persisted or returned. What you receive is a fixed set of codes. This keeps another system's internal detail—file names, user identities, tenant structure—out of your logs and your users' screens. *** ## Request errors These come back from the call you just made. | Code | Status | Cause | Fix | | - | - | - | - | | `connector_scope_not_enabled` | 403 | The provider or scope tier is not enabled for your organization | Contact support to have it enabled | | `provider_scope_insufficient` | 403 | The connection's consent is too narrow to browse server-side. Rare; typically an older connection authorized at a reduced tier. | Reconnect | | `installation_required` | 403 | Your organization hosts an application and `X-Case-Installation-Id` was missing | Send the header—there is no fallback | | `installation_invalid` | 403 | Unknown installation, or one belonging to another organization | Check the id you cached | | `installation_disabled` | 403 | The installation is not `active` | Re-enable it before retrying | | `connector_subject_invalid` | 400 | `X-Case-Connector-Subject` does not match `^[A-Za-z0-9_-]{1,255}$` | Fix the value you derive server-side | A `connect_url` that has expired returns `410`; one that has already been used returns `404`. Either way, generate a fresh one. ## Provider failures Every provider error is classified before it touches your data. The classification decides whether the run retries, fails the file, or stops. | Code | Class | Retried? | What it means | | - | - | - | - | | `provider_reauthorization_required` | reauth | No | Authorization lapsed beyond refresh | | `provider_access_lost` | access\_lost | No | The linked folder is no longer reachable with this account | | `provider_item_not_found` | not\_found | No | The item is gone | | `provider_rate_limited` | throttled | Yes, with backoff | The provider is throttling | | `provider_temporarily_unavailable` | transient | Yes | Provider-side outage or 5xx | | `provider_request_timed_out` | transient | Yes | The provider answers other calls, but this request exceeded the connector's per-attempt timeout on every retry (a slow listing, not an outage) | | `provider_operation_rejected` | permanent | No | The provider refused the operation | Two more are specific rather than classified: | Code | Meaning | Fix | | - | - | - | | `connector_selection_too_large` | The selected folder exceeds the safe scan bounds—too many items, too deep, or too large to checkpoint | Import a smaller folder | | `connector_file_too_large` | A file turned out larger than `filters.max_size_bytes` once its bytes were read | Raise the limit, or exclude the file | ## Recovering from each ### Reauthorization required The most common one. Refresh tokens get revoked when a user changes their password, an admin removes an app, or a provider expires a grant. The connection moves to `reauth_required` and a [`connection.reauth_required`](/events/event-types) event fires. Links stop; nothing is lost. Send the user through the [connect flow](/connectors/oauth#reconnecting) again. Because reconnection merges into the existing connection, links resume with their ledgers and cursors intact and nothing re-imports. ### Access lost The account still works, but the linked folder does not. Someone moved it, deleted it, or removed this user's access. The link becomes `orphaned` with an `orphan_reason`: | Reason | Meaning | | - | - | | `provider_folder_gone` | The folder no longer exists | | `provider_access_lost` | It exists, but this account can no longer reach it | | `vault_deleted` | The destination vault was deleted | An orphaned link will not run again. Point the user at a new folder with a fresh transfer, or delete the link. ### Throttling Backoff is automatic. The run slows down and keeps going; you do not need to do anything. For interactive browse calls, a `429` may carry `Retry-After` when a retry deadline is known—honor it rather than looping. > [!NOTE] > > Interactive browsing and background runs share one request budget per provider account. A large sync in progress can make browsing feel slow for the same user. This is most noticeable on providers with tight rate limits—see the [provider guides](/connectors/providers). ### Transient failures Retried automatically within the run. If a run ends `completed_with_errors`, the files that failed are in the ledger with `state=failed`. Re-post the same transfer to retry only those—the ledger means settled files are not touched again. ### Permanent failures The file failed and will not be retried. Read the row from `GET /connectors/v1/links/{id}/objects?state=failed` and surface it to the user. ## What a crash does not do Transfers are built so that an interrupted run is safe to resume: * Every external side effect is preceded by a persisted ledger intent, so a retry lands on the same identity instead of creating a duplicate * Files stream end to end and nothing buffers whole, so a large file cannot exhaust memory mid-run * Deleting a link soft-deletes it before cancelling its run, so an in-flight executor cannot resurrect it You do not need to build deduplication on top of this. Re-posting a transfer is always safe. ## A practical error-handling loop 1. On `run.failed`, read `error` from the run and decide whether it is reauth, access loss, or something else 2. On `run.completed` with `status: "completed_with_errors"`, pull `?state=failed` from the ledger and show the affected files 3. On `connection.reauth_required`, prompt the user to reconnect—do not delete anything 4. On `link.orphaned`, ask the user to reselect a folder 5. Treat `403 installation_required` as a bug in your request path, not a permissions problem ## Next steps > [card] [Import & Export](/connectors/transfers) > > Run mechanics, ledger states, and progress > [card] [Events](/events/event-types) > > Full payloads for connector lifecycle events > [card] [Providers](/connectors/providers) > > Rate budgets and capability differences per provider # Connectors Overview Source: https://docs.case.dev/connectors/index Move documents between provider folders and vaults ## The problem The documents you need are already somewhere else. They sit in a Google Drive folder or a Clio matter—and they keep changing. Asking people to download them and re-upload them turns a living folder into a stale copy, and it puts you in the business of storing someone else's credentials. ## The solution A connector links a **provider folder** to a **vault**. Case.dev moves the files, records what it moved, and can keep the two sides current as the provider folder changes. Your application never handles provider credentials. It holds a connection id; the OAuth tokens stay inside the connectors service, encrypted under a per-connection key that is itself wrapped by AWS KMS. ## The object model Four objects carry the whole system. | Object | What it is | | - | - | | **Connection** | One authorized provider account. Created pending, becomes `healthy` after consent. Holds the tokens you never see. | | **Link** | A standing relationship between one provider folder and one vault, in one direction. Identity is `(connection_id, direction, remote, vault_id)`. | | **Run** | One execution of a link—a backfill, an incremental diff, or a full reconcile. | | **Ledger entry** | One row per file, per link. Records the provider item, the vault object, the content version, and the outcome. | The ledger is what makes transfers safe to repeat. Re-running a link diffs against the ledger instead of re-importing everything, so the "Re-import" button in your UI is just another `POST /connectors/v1/transfer`. ## Directions A link moves files one way. Ask for `both` and you get a *pair* of one-way links, not a single bidirectional one. | Direction | What moves | | - | - | | `import` | Provider folder → vault | | `export` | Vault → provider folder | | `both` | Creates paired import and export links. Export defaults to a `CaseMark Output` subfolder under the import root. | ## Modes | Mode | Behavior | How to get it | | - | - | - | | `once` | Runs when you ask it to. `automation_status` is `manual_only`. | `POST /connectors/v1/transfer` | | `synced` | Backfills now, then stays current. A sweeper re-runs synced links on a schedule. `automation_status` is `scheduled`. | `POST /connectors/v1/sync-link` | Re-posting to `/transfer` never downgrades a synced link. To step a link back down, `PATCH /connectors/v1/links/{id}` with `mode: "once"`. > [!NOTE] > > Synced links are kept current by polling on a roughly 15-minute cycle, not by provider push notifications. Treat it as "current within the hour," not real time. ## Policies Each link carries a policy that governs what it moves and what happens to the far side. | Setting | Values | Default behavior | | - | - | - | | `deletes` | `mirror`, `preserve` | On imports, `mirror` removes the vault copy when the provider file disappears; `preserve` keeps it. Exports never delete on the provider side. | | `collisions` | `version`, `overwrite`, `skip` | How an export resolves a name that already exists at the destination. | | `filters.max_size_bytes` | integer | Files the provider reports as over the limit are skipped. A file that turns out larger mid-transfer fails with `connector_file_too_large`. | | `filters.exclude_mime` | array of strings | MIME types to leave behind. | ## What transfers cost Two separate things happen, and they bill separately: * **The transfer itself** streams bytes from the provider into vault storage. Nothing buffers the whole file, so a large folder costs time and storage, not memory. * **Downstream vault processing**—OCR, text extraction, chunking, and vectorization—is ordinary vault ingestion and is billed as such. See [Usage](/usage) for how it appears on your bill. ## Security model * **Tokens never leave the service.** Your application holds a `connection_id`. Provider access and refresh tokens are envelope-encrypted—AES-256-GCM under a per-connection key wrapped by AWS KMS—and decrypted only for the provider call that needs them. * **Browse references are opaque.** The `browse_ref` and `import_ref` values you get back are the only identifiers the API accepts. Never build one from a provider id supplied by a browser. * **Connector calls are server-to-server.** Tenant context is derived from your API key and headers you set server-side. See [Installations](/connectors/installations). * **Provider errors are sanitized.** Raw provider messages stay ephemeral; what you receive is a fixed set of safe codes. See [Errors & Recovery](/connectors/errors). ## Availability | Provider | `provider` value | Availability | | - | - | - | | Clio Manage | `clio` | Generally available | | Google Drive | `gdrive` | Generally available | | Box | `box` | Generally available | | Dropbox | `dropbox` | Generally available | | Smokeball | `smokeball` | Generally available (import) | | Microsoft OneDrive / SharePoint | `microsoft` | In development | | Outlook, NetDocuments | — | In development | | Gmail, Google Calendar | — | Deprecated | To see what is live for your organization, read the `providers` array returned by `GET /connectors/v1/connections`. A provider that is not available returns `403 connector_scope_not_enabled` when you try to connect. ## Next steps > [card] [Connect an Account](/connectors/oauth) > > Take a user through hosted OAuth and handle the return safely > [card] [Import & Export](/connectors/transfers) > > Browse a provider, create a link, and follow its progress > [card] [Installations](/connectors/installations) > > Scope connectors per customer tenant in a multi-tenant application > [card] [Errors & Recovery](/connectors/errors) > > Reauthorization, access loss, throttling, and what to retry > [card] [Providers](/connectors/providers) > > Capability differences between Clio Manage and Google Drive ## Related services > [card] [Vaults](/vault) > > Where imported documents land and become searchable > [card] [Events](/events) > > Subscribe to run and connection lifecycle events instead of polling > [card] [Matters](/matters) > > Associate a link with a matter for case-level organization # Installations Source: https://docs.case.dev/connectors/installations Scope connectors per customer tenant in a multi-tenant application ## When you need this If you are building for one organization—your own—you can skip this page. Your API key is already the tenant boundary, and connector requests without extra headers operate in that organization's own namespace. You need installations when **one Case.dev organization serves many customer organizations**. A practice-management product with hundreds of firms behind a single Case.dev account is the case this exists for. Without installations, every firm's connections and links would share one namespace. An **installation** is one customer tenant inside your Case.dev organization. ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart TD A["Your Case.dev organization
One API key, one billing relationship"] --> B["Installation: Firm A
Its connections, links, and vault grants"] A --> C["Installation: Firm B
Isolated from Firm A"] A --> D["Installation: Firm C
Isolated from Firm A and B"] ``` ## Ensure an installation Installations are created just in time and idempotently. Call this on a tenant's first connector use; calling it again returns the same installation. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /connectors/v1/installations ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/installations \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "application": "p3", "external_tenant_id": "firm_8842" }' ``` | Field | Description | | - | - | | `application` | Your application key: lowercase, starting with a letter, 2–32 characters (`^[a-z][a-z0-9_-]{1,31}$`) | | `external_tenant_id` | Your own identifier for the customer—whatever your system already calls them | Returns `201` when created, `200` when it already existed. Either way you get the installation id. > [!NOTE] > > Application keys are **unique within your organization**. Different organizations can use the same key (for example, `para` or `p3`) without sharing installations, connections, or vault grants. Ensuring the same `(application, external_tenant_id)` in your organization returns the same installation. ## Send the installation on every request ```bash title="Header" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} X-Case-Installation-Id: inst_7f21ab ``` With this header, the caller sees only that installation's connections and links. Without it, the caller sees only organization-scoped rows. > [!WARNING] > > Once your organization has registered an application, there is **no organization-scoped fallback**. Connector requests that omit `X-Case-Installation-Id` are rejected with `403 installation_required`. > > This is deliberate. A bug that drops the header produces a refused request rather than one customer's documents appearing in another customer's vault. | Code | Status | Meaning | | - | - | - | | `installation_required` | 403 | Your organization hosts an application and the header is missing | | `installation_invalid` | 403 | The id is unknown, or belongs to another organization | | `installation_disabled` | 403 | The installation exists but its status is not `active` | An unknown id and another organization's id return the same error, so the API cannot be used to probe for which installations exist. ## Grant vaults to an installation An installation cannot touch a vault until you grant it. Grants are explicit and checked twice: when a link is created, and again every time a run executes. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} PUT /connectors/v1/installations/{id}/vaults/{vaultId} ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X PUT https://api.case.dev/connectors/v1/installations/inst_7f21ab/vaults/vault_abc123 \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "relationship": "owned", "can_read": true, "can_write": true, "can_manage": false, "source": "provisioning" }' ``` ### Which capability does what | Capability | Needed for | | - | - | | `can_write` | Import links—writing provider files into the vault | | `can_read` | Export links—reading vault documents to send to the provider | | `can_manage` | Mirror deletion and purge—removing vault documents | Grant the narrowest set that supports the flows you actually offer. An import-only integration does not need `can_manage`. | Field | Values | Notes | | - | - | - | | `relationship` | `owned`, `shared` | Whether the installation owns the vault or was given access to it | | `source` | `provisioning`, `lazy_reconcile`, `explicit_share` | How the grant came about. Useful in your own audits. | ### Reconciliation never revokes `PUT` only ever adds or updates. If your reconcile pass omits a vault it granted last time, **nothing is revoked**—a transient glitch in your provisioning job cannot silently cut off access. Revocation is always the explicit call: ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} DELETE /connectors/v1/installations/{id}/vaults/{vaultId} ``` Re-granting a revoked vault reactivates it. ## What happens when access goes away Disabling an installation or revoking a grant **pauses** the affected links. Nothing is deleted, no documents move, and no ledger state is lost. Restore the grant and resume the link, and it picks up from its cursor. ## Scoping to a user within a tenant The installation is the tenant boundary. If you also need to keep one user's provider credentials from being used by another user in the same tenant, send a subject assertion: ```bash title="Header" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} X-Case-Connector-Subject: user_5512 ``` Values match `^[A-Za-z0-9_-]{1,255}$`; anything else returns `400 connector_subject_invalid`. Scoping is exact—a request carrying a subject can never fall through to an organization-scoped connection, and omitting the header cannot reach a subject-scoped one. > [!WARNING] > > This is a **server-to-server assertion**, not an end-user credential. Derive it from your own authenticated session server-side. > > Never copy it from a browser field, query parameter, or anything a client can set. A caller holding your API key is already trusted to act for the tenant; this header only partitions users inside it, so a forged value crosses a real privilege boundary. ## Checklist for a multi-tenant integration * Ensure the installation on first use, and cache the id against your own tenant record * Send `X-Case-Installation-Id` on every connector request—there is no fallback * Grant each vault explicitly, with the narrowest capabilities * Derive `return_url` and any subject assertion server-side, never from client input * Treat `403 installation_required` as a bug in your request path, not a permissions problem to work around ## Next steps > [card] [Connect an Account](/connectors/oauth) > > Hosted OAuth, scoped to an installation > [card] [Import & Export](/connectors/transfers) > > Create links against a granted vault > [card] [Errors & Recovery](/connectors/errors) > > Grant failures, access loss, and paused links # Connect an Account Source: https://docs.case.dev/connectors/oauth Take a user through hosted OAuth and handle the return safely Connecting a provider account takes three steps: 1. **Create a pending connection** and get a one-time `connect_url` 2. **Send the user to it**—they consent at the provider 3. **Handle the return** at your own URL, which now carries the connection id Your server never sees an authorization code, an access token, or a refresh token. *** ## Step 1: Create the connection ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /connectors/v1/connections ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/connections \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "provider": "clio", "return_url": "https://app.example.com/integrations/callback" }' ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "connection_id": "conn_abc123", "connect_url": "https://api.case.dev/connectors/v1/connect/QTd2…", "expires_at": "2026-01-15T10:40:00Z" } ``` | Field | Required | Description | | - | - | - | | `provider` | yes | `clio` or `gdrive` | | `return_url` | yes | Where the user lands after consent | | `scope_tier` | no | Provider permission tier. Omit to use the provider's default. | The connection exists immediately with status `pending`. It becomes `healthy` only after the user finishes consent. ### return\_url rules The URL is validated when you create the connection, not when the user comes back. A URL that fails these checks returns `400`. * It must be **absolute**. * It must use **https**. `localhost` and `127.0.0.1` over http are accepted outside production. * It must not embed **credentials** (no `user:password@host`). Case.dev appends a query parameter to whatever you supply, preserving your existing ones. > [!WARNING] > > Treat `return_url` as a redirect target you own. Do not build it from unvalidated user input, and do not point it at a URL that forwards onward using a parameter an attacker controls. ### Scope tiers `scope_tier` selects a provider permission level. Both current providers expose a single tier (`clio.us`, `drive`), so omit the field and you get it by default. The tier is signed into the `connect_url`, so a user cannot broaden their own consent by editing the query string before they click through. ## Step 2: Send the user to connect\_url Redirect the browser to `connect_url`. Case.dev builds the provider authorization URL, attaches HMAC-signed state and a PKCE challenge, and forwards the user to the provider's consent screen. > [!NOTE] > > `connect_url` is **one-time and expires in 10 minutes**. An expired link returns `410`; a link that has already been used returns `404`. Generate it when the user is about to click, not when the page loads. ## Step 3: Handle the return After consent, the provider redirects to Case.dev, which exchanges the code, stores the encrypted tokens, and sends the user to your `return_url`. ```text title="Success" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} https://app.example.com/integrations/callback?connection_id=conn_abc123 ``` ```text title="Failure" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} https://app.example.com/integrations/callback?error=connector_scope_not_enabled ``` Branch on which parameter is present. | `error` value | Meaning | What to do | | - | - | - | | `access_denied` | The user declined consent at the provider | Offer to try again | | `provider_error` | The provider returned an error before issuing a code | Retry; escalate if it persists | | `missing_code` | The provider redirected without an authorization code | Retry | | `connector_scope_not_enabled` | The provider is not enabled for your organization, or the user granted fewer scopes than required | Contact support, or ask the user to reconnect and accept the full consent | | `oauth_flow_inactive` | The pending connection was disconnected, superseded, or did not match the initiating session | Start a fresh connection | | `oauth_exchange_failed` | The code exchange with the provider failed | Retry; escalate if it persists | On success, confirm the connection is usable before you show it as connected: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/connectors/v1/connections/conn_abc123 \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "conn_abc123", "provider": "clio", "status": "healthy", "enabled": true, "scope_tier": "clio.us", "account": { "external_id": "3915522", "email": "casey@example.com", "display_name": "Casey Rivera" }, "created_at": "2026-01-15T10:30:00Z", "updated_at": "2026-01-15T10:31:04Z" } ``` > [!WARNING] > > Do not trust `connection_id` from the query string on its own. Anyone can type it. Fetch the connection server-side with your API key and confirm it belongs to the tenant whose session you are serving. ## Connection statuses | Status | Meaning | What to do | | - | - | - | | `pending` | Created, consent not finished | Nothing. Once `connect_url` expires it cannot be completed. | | `healthy` | Usable | Proceed. | | `reauth_required` | Provider authorization lapsed beyond refresh | Run the connect flow again. | | `revoked` | Unlinked, tokens deleted | Create a new connection. | | `throttled` | Provider is rate limiting this account | Back off. It clears on its own. | Subscribe to [`connection.reauth_required` and `connection.revoked`](/events/event-types) instead of polling. ## Reconnecting Reconnection is the same flow. Create a new connection for the same provider and account, and send the user through `connect_url` again. When the account matches an existing connection, the callback returns you to `return_url` carrying that **existing** `connection_id`—so links built on it keep working, with their ledgers and cursors intact. This is what you should offer when a connection goes `reauth_required`. Nothing re-imports. ## Disconnecting ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} DELETE /connectors/v1/connections/{id} ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X DELETE https://api.case.dev/connectors/v1/connections/conn_abc123 \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` Tokens are revoked at the provider and deleted. Documents already imported into vaults stay where they are. To remove those documents too, add `?purge=true`. The purge runs as a durable background workflow and returns `202` rather than `204`. > [!WARNING] > > `purge=true` deletes vault documents that this connection's import links brought in. It is not reversible—confirm with the user before you call it. ## Turning a provider off without disconnecting ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} PATCH /connectors/v1/connections ``` This stops new runs and scheduled syncs for one provider across the whole organization or installation. Credentials, links, and imported files are preserved, and runs already in flight are not interrupted. Because it is organization-wide, the body must include `confirm_organization_wide: true`. ## Next steps > [card] [Import & Export](/connectors/transfers) > > Browse the connected account and move files into a vault > [card] [Installations](/connectors/installations) > > Scope connections per customer tenant > [card] [Errors & Recovery](/connectors/errors) > > What each failure code means and which ones to retry # Box Source: https://docs.case.dev/connectors/providers/box Folder import, export, and scheduled two-way synchronization `provider: "box"` · Import and export · Generally available Connect a user's existing Box account, browse folders they can access, and import a selected folder into a vault. Box uses the same connection, transfer, sync, activity, reconnection, and disconnect APIs as Clio. > [!NOTE] > > Discover availability from `GET /connectors/v1/connections`; do not hardcode a connect button. > The only supported scope tier is `box.readwrite` (`root_readwrite` at Box). ## Browsing A browse request without parameters returns **All Files**, with folder id `0` and the authenticated Box user id as `container_id`. Choose that root or descend into owned, shared, and collaborated folders visible to the account. Stable ids survive renames and moves. ```json title="Root browse response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "0", "name": "All Files", "kind": "my_drive", "container_id": "123456", "browse_ref": { "kind": "folder", "folder_id": "0", "container_id": "123456" } } ] } ``` Page children with the returned cursor. Box uses marker pagination; callers treat cursors as opaque. ## Import, export, and two-way sync ```json title="One-time import request: POST /connectors/v1/transfer" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "direction": "import", "connection_id": "conn_abc123", "vault_id": "vault_abc123", "remote": { "container_id": "123456", "folder_id": "0", "path": "All Files" }, "policy": { "deletes": "preserve", "collisions": "version" } } ``` Use `POST /connectors/v1/sync-link` for scheduled synchronization. As with Clio, `direction: "both"` creates paired import and export links. Exports use a separate destination under the selected root unless an explicit destination is provided. Imported objects are excluded from export, and the export destination is excluded from import to prevent echoes. The console uses the shared **Import from…** flow: connect Box, select a folder, select or create a vault, and optionally enable document sync. Box exposes only the `documents` collection; Clio-specific communications and tasks are not Box resources. ## Change detection and recovery The initial scan captures Box's user-event position **before** walking the folder tree. Large scans save page progress and continue in another durable workflow step. Transfers resume from the saved snapshot rather than re-enumerating a changing folder. Subsequent runs consume the user changes feed, deduplicate events, and resolve each changed file's current ancestry. Structural folder changes, collaboration changes, inaccessible ancestry, and rejected or expired cursors trigger a complete reconciliation. The shared scheduled reconciliation remains the backstop. Rename and move changes update path metadata without downloading unchanged content. Content identity uses the Box SHA-1 and file-version id. ## Collision policies and crash recovery | Policy | Behavior | | - | - | | `skip` | Adopts the existing destination without writing | | `overwrite` | Adds a version to the existing Box file id with an etag fence | | `version` | Creates a deterministic sibling name because Box disallows same-name siblings | Export never deletes Box content. If an upload succeeds but its response is lost, retries inspect the bounded destination folder and stable file/version identities. An ambiguous result halts with `adoption_ambiguous` instead of uploading again, including when the Vault source changed during the retry. Small uploads stream directly. Known sizes above 50 MiB use chunked upload sessions with SHA-1 part digests. The user's maximum upload size is checked before uploading whenever the source size is known. Long download-readiness and pending-commit waits defer to the durable workflow. Chunked uploads persist their session, uploaded parts, digest, and commit result in the shared per-object recovery checkpoint. Retries commit the same session after Box's retry deadline. A lost commit response or changed source fails closed as ambiguous; it never starts another session to bypass an unresolved upload. ## Supported content Ordinary files are ingested. Box Notes and web links become typed skipped results; native content is never silently treated as a document. Folder-depth, page, item, byte, and stream-idle limits bound traversal and transfers. ## Reconnection and enterprise enablement Box uses standard server-side OAuth with explicit `root_readwrite` consent. The adapter does not perform an additional downscope exchange. Box refresh tokens are single-use and rotate after each refresh. The shared token service validates and checkpoints rotation under its fenced refresh lease before returning access tokens. Invalid or expired refresh tokens move the connection to `reauth_required`; reconnect through the same hosted OAuth flow used by Clio. > [!WARNING] > > Some enterprises block unpublished applications. Their administrator must enable the app using its > Client ID before users can authorize it. Marketplace publication is optional for direct OAuth > rollout. Reconnect after app scope changes. For an enterprise that blocks unpublished apps, an authorized Box administrator can add the environment's user-authentication app by **Client ID** in **Admin Console → Platform → Platform Apps → User Authentication Apps → Add +**, review the file read/write permissions, select the app's enabled state, and apply the change. The developer's **Enablement** tab is visible only when that enterprise policy requires it. Enabling an OAuth app is different from authorizing a JWT or Client Credentials app; do not change authentication models to work around a policy denial. Users still authorize their own accounts through the normal consent flow. See Box's [platform-app management guide](https://support.box.com/hc/en-us/articles/360044196653-Managing-platform-apps) and [sandbox/production enablement guide](https://support.box.com/hc/en-us/articles/360043697014-Authorizing-Platform-Applications-in-Sandbox-and-Production-Environments). The production consent app is named **Case.dev**; the isolated test app is **Case.dev Connectors Preview**. Use the corresponding environment's Client ID, never its client secret, for administrator enablement. Do not share Preview tokens or credentials with production. Box does not use service accounts, JWT, enterprise impersonation, or `as-user` access. ## Capabilities at a glance | | | | - | - | | Containers | User-visible Box folders; root `0` | | Change detection | User-event stream plus complete reconciliation | | Export / paired mode | Yes | | Collection | `documents` | | Scope tier | `box.readwrite` | | Transfer concurrency | 4 | | Refresh policy | Rotating, single-use | | Webhooks | Not supported | See [Import & Export](/connectors/transfers) for policies and activity, and [Errors & Recovery](/connectors/errors) for retry and reauthorization handling. # Clio Manage Source: https://docs.case.dev/connectors/providers/clio Matter and folder import, export, and selectable collections `provider: "clio"` · Import and export · Generally available The Clio connector browses matters and their document folders, mirrors a matter root or a nested folder into a vault, and can export vault work product back to Clio. > [!NOTE] > > US region only. Clio Grow and non-US regions are not supported, and the scope tier is always `clio.us`. ## Browsing Browse with no parameters to list the matters the connected user can reach. Each matter carries a folder reference containing both its matter id and root folder id, so you can import a whole matter or descend into a subfolder first. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/browse" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "987654", "name": "Smith v. Hospital", "kind": "matter", "browse_ref": { "kind": "folder", "folder_id": "987654", "container_id": "123456" } } ] } ``` Matter and folder ids are stable across renames and moves. Display names and paths never participate in link identity, so a user reorganizing their Clio folders does not break an existing link. > [!WARNING] > > Clio's shared request budget starts at **50 requests per minute per Clio user**. > Interactive browsing, document sync, communications and tasks share the same > budget across connections and Case.dev organizations, including after token refresh. > Sustained successful traffic gradually probes higher capacity, up to 400 requests > per minute; this ceiling is not a guarantee of provider capacity. A provider > `429` reduces the rate and establishes an exponential, jittered cooldown that > honors the later `Retry-After` or reset deadline. Long waits defer work rather > than holding a serverless request open. Other integrations using that Clio user > can still consume its provider quota. > > Page browse results rather than eagerly walking the tree, and expect `429` with `Retry-After` while a sync is running for the same account. Honor it instead of retrying immediately. ## Selectable collections Clio is the only provider that exposes more than one collection. Choose with `remote.resource_type`: | `resource_type` | Direction | Contents | | - | - | - | | `documents` | Import and export | Matter documents. The default when omitted. | | `communications` | Import only | Matter communications, imported as searchable vault content | | `tasks` | Import only | Matter tasks, imported as searchable vault content | Each link selects exactly one collection, so cursors and failures stay isolated. To bring documents and communications into the same vault, create two links. Asking for an export link on `communications` or `tasks` returns `400`. ## Importing a matter ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/transfer \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "direction": "import", "connection_id": "conn_abc123", "remote": { "container_id": "123456", "folder_id": "987654", "path": "Smith v. Hospital" }, "vault_id": "vault_abc123" }' ``` ## Change detection Clio reports changes by modification time rather than a native delta feed. * The first run captures a timestamp, then recursively lists the selected root * Later runs query documents updated since that timestamp, with a short overlap for safety * A scheduled daily full reconcile catches deletions, newly inaccessible documents, and files moved out of the selected subtree—things a timestamp filter cannot report Content identity is the document's latest version, not the document record. A rename or folder move updates path metadata **without re-downloading the file**. ## Export and two-way sync Clio supports `direction: "export"` and `direction: "both"`. With `both`, you get a paired import link and export link sharing a `pair_id`. Unless you pass `export_destination`, exports land in a `CaseMark Output` folder created under the selected Clio folder. ### Lane ownership Two-way sync could easily become a loop. It does not, because each side owns a lane: * **Clio-native documents** flow into the vault * **Vault-native documents** flow out to Clio Only vault-native objects are exported—documents that arrived *from* Clio are excluded, so nothing round-trips. Documents created by the export carry provenance markers, and Clio change discovery skips them, so an exported file is never re-imported as a duplicate. Edits made to a Case.dev-owned document inside `CaseMark Output` do not flow back into the vault. > [!NOTE] > > If both sides changed since the last successful export, the item **halts with a conflict** rather than silently overwriting either version. Surface these to the user; the connector will not guess. ### Collision policy | `policy.collisions` | Behavior on a name collision | | - | - | | `version` (default) | Creates a new sibling document | | `overwrite` | Adds a new version to the colliding document | | `skip` | Leaves the existing Clio document untouched | Export never deletes Clio documents, whatever the delete policy says. ## Reconnection Clio refresh tokens are long-lived, so reconnection is rare. > [!WARNING] > > One exception: Clio does not upgrade permissions on an existing OAuth grant when the application's permissions change. Accounts that authorized before export was enabled **must reconnect** before they can export. > > A write-side `403` moves the connection to `reauth_required`. Prompt the user to reconnect rather than treating it as a permanent failure. ## Capabilities at a glance | | | | - | - | | Containers | Matters | | Browse depth | Folder | | Change detection | Updated-since, with scheduled full reconcile | | Export | Yes | | Collections | `documents`, `communications`, `tasks` | | Scope tier | `clio.us` | | Rate budget | Adaptive per Clio user: starts at 50 requests/min, probes up to 400; 4 concurrent transfers | | Webhooks | Not supported | ## Next steps > [card] [Import & Export](/connectors/transfers) > > Link mechanics, policies, and progress > [card] [Errors & Recovery](/connectors/errors) > > Throttling, reauthorization, and conflicts > [card] [All providers](/connectors/providers) > > Compare against the other supported providers # Google Drive Source: https://docs.case.dev/connectors/providers/google-drive My Drive and shared drive import and export `provider: "gdrive"` · Import and export · Generally available The Google Drive connector links a folder in My Drive or a shared drive to a vault, in either direction. > [!NOTE] > > Check the `providers` array from `GET /connectors/v1/connections` before showing a Drive option in your UI. ## Browsing Browse with no parameters to list My Drive and any shared drives the connected user can reach, then descend by folder. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/browse" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "root", "name": "My Drive", "kind": "my_drive", "browse_ref": { "kind": "container", "container_id": "root" } }, { "id": "0AAbCdEf", "name": "Litigation", "kind": "shared_drive", "browse_ref": { "kind": "container", "container_id": "0AAbCdEf" } } ] } ``` Drive folder ids are globally unique, so a link's identity rests on `folder_id` alone. `container_id` is present only for shared drives; absent or `root` means My Drive. ## Importing a folder ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/transfer \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "direction": "import", "connection_id": "conn_abc123", "remote": { "container_id": "0AAbCdEf", "folder_id": "1XyZabc", "path": "Clients/Acme" }, "vault_id": "vault_abc123" }' ``` Everything under the selected folder is imported recursively. ## Change detection Drive has a native change feed, so incremental runs are cheap. On a backfill, the connector captures a change token **before** it walks the folder, so edits made during a long walk land in the next run rather than falling into a gap. Large folders checkpoint as they go and resume without restarting from the root. If a stored change token ages out, Drive reports `410` and the connector re-backfills automatically. The ledger deduplicates unchanged files by content version, so a re-backfill does not re-import anything. ## Content identity Version identity is the cheapest signal that changes only when content changes—a checksum for ordinary files, and version plus modification time for Google-native documents. A rename or a move therefore updates metadata **without re-downloading the file**. ## Export Drive supports `direction: "export"` and `direction: "both"`. With `both`, exports default to a `CaseMark Output` subfolder under the import root, and that subfolder is excluded from the import side so exported files are never re-imported. Export never deletes anything in Drive. ## Rate budget Drive allows 12,000 requests per minute with four concurrent transfers. In practice you are far more likely to be bounded by vault ingestion throughput than by Drive. A large folder does not start every ingestion at once: imports commit through a bounded preparation window and then queue into the shared ingestion dispatcher. ## Reconnection Google refresh tokens are long-lived, so reconnection is rare once a user has consented. ## Capabilities at a glance | | | | - | - | | Containers | My Drive, shared drives | | Browse depth | Container → folder | | Change detection | Native delta | | Export | Yes | | Collections | Not applicable | | Scope tier | `drive` | | Rate budget | 12,000 requests/min, 4 concurrent transfers | | Webhooks | Not used for sync | ## Next steps > [card] [Import & Export](/connectors/transfers) > > Link mechanics, policies, and progress > [card] [Errors & Recovery](/connectors/errors) > > Reauthorization, access loss, and throttling > [card] [All providers](/connectors/providers) > > Compare against the other supported providers # Providers Overview Source: https://docs.case.dev/connectors/providers/index Capability differences across the supported connector providers Every provider goes through the same adapter contract, so the API you write against does not change. What differs is what each provider can actually do—how its hierarchy is shaped, how it reports changes, and how hard you can push it. Build against the matrix, not against one provider's behavior. ## Capability matrix | | Clio Manage | Google Drive | Box | | - | - | - | - | | `provider` value | `clio` | `gdrive` | `box` | | Import | Yes | Yes | Yes | | Export | Yes | Yes | Yes | | Top-level containers | Matters | My Drive, shared drives | All Files | | Browse depth | Folder | Container → folder | Folder | | Search | Document names only, recursive within a matter folder | Names and contents; a folder searches its direct children | Names and contents, recursive | | Folder contents | — | Yes | Yes | | Folder search | No | Names | Names | | Folder links | — | Folder, shared-drive and `open?id=` links | Folder and shared links | | Change detection | Updated-since | Native delta | User events + reconciliation | | Selectable collections | Documents, communications, tasks | — | Documents | | Default scope tier | `clio.us` | `drive` | `box.readwrite` | | Availability | Generally available | Generally available | Generally available | ## Rate budgets Each provider has a request budget that interactive browsing and background runs **share**. A large sync in progress will make browsing feel slower for the same account. | Provider | Requests/min | Concurrent transfers | | - | - | - | | Google Drive | 12,000 | 4 | | Clio Manage | 45 | 4 | | Box | 900 | 4 | Clio's budget is tight. If you are building a Clio integration, read [its guide](/connectors/providers/clio) before designing your browse UI. ## Token refresh behavior You never handle tokens, but refresh behavior affects how often users are asked to reconnect. Clio and Google Drive issue long-lived refresh tokens. Box refresh tokens rotate after each use and expire after 60 days without use. Handle [`connection.reauth_required`](/connectors/errors#reauthorization-required) for every provider. ## Change detection and what it costs | Strategy | Provider | Behavior | | - | - | - | | Native delta | Google Drive | The provider reports what changed. Incremental runs are cheap. | | User events | Box | Current metadata and ancestry determine subtree membership; structural changes trigger reconciliation. | | Updated-since | Clio Manage | Queries by modification time. Efficient, but deletions are detected on the daily full reconcile. | > [!NOTE] > > No provider currently drives synced links through push notifications. Synced links are kept > current by a polling sweep—treat "synced" as current within the hour, not real time. ## Discovering availability at runtime Do not hardcode the provider list. `GET /connectors/v1/connections` returns a `providers` array describing what is live for the calling organization: ```json title="Response fragment" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "providers": [ { "id": "clio", "scope_tier": "clio.us", "supports_export": true, "resource_types": ["documents", "communications", "tasks"] }, { "id": "gdrive", "scope_tier": "drive", "supports_export": true, "resource_types": [] } ] } ``` Drive your UI from this. A provider gated for the organization returns `403 connector_scope_not_enabled` at connect time—better to not show the button. ## Guides > [card] [Box](/connectors/providers/box) > > Folder import, export, and scheduled two-way synchronization > [card] [Clio Manage](/connectors/providers/clio) > > Matter and folder import, export, and selectable collections > [card] [Google Drive](/connectors/providers/google-drive) > > My Drive and shared drives, import and export # Import & Export Source: https://docs.case.dev/connectors/transfers Browse a provider, create a link, and follow its progress Once an account is [connected](/connectors/oauth), moving files takes three calls: 1. **Browse** to let the user choose a folder 2. **Transfer** to create the link and start a run 3. **Poll or subscribe** to follow progress *** ## Step 1: Browse the provider Browse returns one level at a time. With no parameters you get the top-level containers—matters for Clio, My Drive and shared drives for Google Drive. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/connections/{id}/browse ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/browse?page_size=100" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "1a2b3c", "name": "Smith v. Hospital", "kind": "matter", "browse_ref": { "kind": "folder", "folder_id": "1a2b3c" }, "import_ref": { "folder_id": "1a2b3c" } } ], "cursor": null } ``` To descend, pass back the `browse_ref` fields from the item the user picked: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/browse?container=drv_99&parent=1a2b3c" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` | Parameter | Description | | - | - | | `container` | Container id—a shared drive or a matter | | `parent` | Folder id to list inside | | `query` | Provider-supported search text, scoped to the current level | | `cursor` | Continuation from a previous page | | `page_size` | Up to 1000 | Item `kind` is one of `my_drive`, `shared_drive`, `matter`, `folder`, or `file`. The enum also reserves `site` and `document_library` for providers that group drives under sites; neither current provider returns them, and the `site` query parameter is likewise unused. > [!WARNING] > > `browse_ref` and `import_ref` are **opaque references**. Pass them back exactly as received. > > Never construct one from a provider id supplied by a browser, and never accept one as user input in your own API. These values are how the service decides what a caller is allowed to reach. Some items are browsable but not importable, and some are the reverse. When an item carries an `import_ref` that differs from its `browse_ref`, use `import_ref` as the link's `remote`. > [!NOTE] > > Browsing needs a connection scope that permits server-side listing. If it does not, you get `403 provider_scope_insufficient`—the user consented at a narrower tier than browsing requires. ### Search instead of browsing When the user knows what they want but not where it is, search the connection. Search uses the provider's own search, returns files by default, and works across the whole account or inside one folder. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/connections/{id}/search ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/search?query=engagement%20letter&page_size=25" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "1180529", "name": "Engagement letter.pdf", "kind": "file", "mime_type": null, "size_bytes": 48211, "modified_at": "2026-10-02T15:04:11Z", "path": "Smith v. Hospital/Engagement letter.pdf", "container_id": "42", "parent_ids": ["90012"], "browse_ref": null, "unsupported_reason": null, "open_ref": "or1.…" } ], "cursor": "25", "scope": "account", "scope_ref": null, "full_text": true, "folder_scope_recursive": true } ``` | Parameter | Description | | - | - | | `query` | Required search text, up to 256 characters | | `kind` | `file` (default) or `folder` | | `container`, `parent` | `browse_ref` fields of the folder or container to search inside | | `cursor` | Continuation from a previous page | | `page_size` | Capped at the provider's `max_page_size` | Each provider in `GET /connectors/v1/connections` lists its `search` capability, and each connection reports `search_supported`. Read them before showing a search box: * `full_text` is `false` when the provider may match file names only. * `folder_scope_recursive` is `false` when a folder scope covers that folder's direct children only (Google Drive). A shared drive's container scope still searches the whole drive. * `kinds` lists what the provider can search for. A provider without search answers `422 search_not_supported`; a kind it cannot search answers `422 search_kind_not_supported`; a scope it cannot honor answers `422 search_scope_not_supported`. Search shares the connection's request budget with browsing and background runs, and throttles the same way: `429` with `Retry-After` when known. #### Find a folder anywhere Pass `kind=folder` to find folders by name, however deep they sit. Each result carries a `browse_ref` to open it with browse, and a display `path` from the top of the account. Google Drive, Box and Dropbox search folders; Clio does not. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/search?query=exhibits&kind=folder" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "90013", "name": "Exhibits", "kind": "folder", "mime_type": null, "size_bytes": null, "modified_at": null, "path": "Smith v. Hospital/Discovery/Exhibits", "container_id": "42", "parent_ids": ["90012"], "browse_ref": { "kind": "folder", "folder_id": "90013", "container_id": "42" }, "unsupported_reason": null, "open_ref": null } ], "cursor": null, "scope": "account", "scope_ref": null, "full_text": false, "folder_scope_recursive": true } ``` Folders match by name only, so `full_text` is always `false`. Box paths start below All Files, Dropbox paths at the account root (`/Smith/Discovery/Exhibits`), and Google Drive paths at My Drive or the shared drive's name. A Google Drive folder shared with the user starts at the highest folder they can see. Google Drive reports parents rather than paths, so each folder search there also looks up the results' ancestors and spends more of the request budget. ### Open a pasted folder link When the user already has the folder open in the provider, let them paste its link. Resolve returns the folder as a browse item: pass its `browse_ref` fields to browse to open it, or use it as the transfer root. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/connections/{id}/resolve ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -G "https://api.case.dev/connectors/v1/connections/conn_abc123/resolve" \ --data-urlencode "url=https://www.dropbox.com/scl/fo/abc123/AAbbCC?rlkey=xyz&dl=0" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "id:a4ayc_80_OEAAAAAAAAAXw", "name": "Smith v. Hospital", "description": null, "kind": "folder", "mime_type": null, "size_bytes": null, "modified_at": null, "path": "/Matters/Smith v. Hospital", "container_id": "3235641", "parent_ids": [], "browse_ref": { "kind": "folder", "folder_id": "id:a4ayc_80_OEAAAAAAAAAXw", "container_id": "3235641" }, "import_ref": null, "open_ref": null } ``` | Provider | Links it resolves | | - | - | | Google Drive | `drive.google.com/drive/folders/{id}` (also `/drive/u/{n}/folders/{id}` and shared-drive roots) and `open?id={id}` | | Box | `app.box.com/folder/{id}` (also enterprise subdomains) and shared links `app.box.com/s/{name}` | | Dropbox | Shared links (`/scl/fo/…`, legacy `/sh/…`) for folders in the connected account | | Microsoft | OneDrive and SharePoint sharing links (`1drv.ms`, `onedrive.live.com`, `*.sharepoint.com`) | `path` is set when the provider reports it in the same lookup (Box, Dropbox, and Microsoft when Graph includes the parent path). Resolving reads the link; it never accepts a share or adds the folder to the account. | Code | Status | Meaning | | - | - | - | | `invalid_url` | 400 | `url` is missing, not an http(s) link, or over 2,048 characters | | `link_not_recognized` | 400 | Not a folder link of this connection's provider | | `link_not_folder` | 422 | The link points to a file | | `link_not_in_account` | 422 | A Dropbox or Box shared folder the connected account has not added (Dropbox) or does not collaborate on (Box). Add it in the provider, then retry | | `link_not_accessible` | 404 | The folder does not exist, or the connected account cannot see it | | `link_resolve_not_supported` | 422 | The provider has no folder links (Clio, Smokeball) | ### Fetch one file instead of importing a folder When the user needs one file now, not a folder kept in sync, fetch it. Each `file` item from browse or search carries an `open_ref`: a signed reference bound to your organization, installation, subject and connection. Pass it back exactly as received. It is `null` for folders and for providers without single-file fetch (Box, Dropbox, Google Drive and Clio support it). ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /connectors/v1/fetch ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/fetch \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "open_ref": "or1.…", "vault_id": "vault_abc123" }' ``` ```json title="Response (201)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "fetch_id": "cfe_9k2x", "reused": false, "vault_id": "vault_abc123", "vault_object_id": "obj_7h3m", "filename": "Engagement letter.pdf", "content_type": "application/pdf", "size_bytes": 48211, "checksum": "9f86d0…", "provider_version": { "sha1": "…" }, "modified_at": "2026-10-02T15:04:11Z" } ``` * **Destination:** exactly one of `vault_id`, or `upload_url`, a presigned HTTPS Amazon S3 PUT URL. Leave `Content-Type` out of the URL's signed headers; the file's type is sent as an unsigned header. * **Size:** up to 100 MB, copied within the request. Larger files return `413 fetch_too_large`; import their folder with a transfer instead. * **Repeats:** fetching the same provider version to the same destination returns the first copy with `200` and `reused: true`, without downloading again. A concurrent identical request gets `409 fetch_in_progress` with `Retry-After`. * **Indexing:** a Vault copy is stored like a finished upload. Call `POST /vault/{id}/ingest/{object_id}` to index it. * **Exports:** links never export a fetched copy, just as they never export an imported one. * **Errors:** an unknown or out-of-scope reference returns `404`. Items the import engine would skip (a Box note, a Google Form) return `422 fetch_unsupported_item`. ### Preview what a folder will import Before the user starts an import, show what it will bring in. Contents lists every file under one folder, at any depth, as a flat paginated list, so you can show a file count and list without walking subfolders yourself. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/connections/{id}/contents ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/connections/conn_abc123/contents?parent=1Fz9q&page_size=1000" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "items": [ { "id": "1Hc2w", "name": "Production 1.pdf", "kind": "file", "mime_type": "application/pdf", "size_bytes": 48211, "modified_at": "2026-10-02T15:04:11Z", "path": "Discovery/Production 1.pdf", "container_id": null, "parent_ids": ["1Kd7r"], "unsupported_reason": null, "open_ref": "or1.…" } ], "cursor": "1000.eJx…", "truncated": false, "scope_ref": { "kind": "folder", "folder_id": "1Fz9q" } } ``` | Parameter | Description | | - | - | | `container`, `parent` | `browse_ref` fields of the folder or container to list. One is required | | `cursor` | Continuation from a previous page | | `page_size` | Most files per page, up to 1,000 (the default) | * **Paths:** each `path` is relative to the folder you listed and ends in the file's name. * **Pages:** a page comes back as soon as it holds files, so it can be shorter than `page_size` while `cursor` is still set. Show each page as it arrives and keep requesting until `cursor` is `null`. * **Limit:** a listing stops after 10,000 files with `truncated: true`. A very wide Google Drive or Box tree can also end early with `truncated: true`. Show the count as a minimum ("10,000+ files"). * **Skipped files:** `unsupported_reason` marks files an import would skip, such as a Box note or a Google Form. * **Providers:** Google Drive, Box, Dropbox and Microsoft OneDrive and SharePoint. Others answer `422 contents_not_supported`; fall back to browsing. Contents runs only when you call it, for the folder you name. It shares the connection's request budget with browsing and background runs and throttles the same way: `429` with `Retry-After` when known. ## Step 2: Create the link and run it ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /connectors/v1/transfer ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/connectors/v1/transfer \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "direction": "import", "connection_id": "conn_abc123", "remote": { "folder_id": "1a2b3c", "path": "Smith v. Hospital" }, "vault_id": "vault_abc123", "policy": { "deletes": "preserve", "filters": { "max_size_bytes": 209715200 } } }' ``` ```json title="Response (202)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "links": [{ "id": "link_55aa", "direction": "import", "mode": "once", "state": "running" }], "run": { "started": true } } ``` A link's identity is `(connection_id, direction, remote, vault_id)`. The first call creates it and runs a full backfill. Every later call with the same four values runs an **incremental diff** against the ledger—so "Re-import" in your UI is this exact request again. If a run is already active, the existing run is returned instead of an error. Double-clicking is safe. ### Exclude folders or files For Clio and Google Drive document imports, include `policy.filters.exclude_folder_ids` and `policy.filters.exclude_file_ids` with stable provider IDs from browsing. Excluding a folder excludes its entire subtree. New files in included folders continue importing, while these exclusions apply to subsequent runs and full reconciliations. Existing vault copies are preserved. Exclusions require `policy.deletes: "preserve"` (the default); combining exclusions with `deletes: "mirror"` returns `400`. For `direction: "both"`, exclusions are stored on the import half only; the export half retains other policy settings. Each list accepts up to 1,000 IDs. The import root cannot be excluded. These filters do not apply to exports, Clio tasks, or Clio communications. Connections advertise support through `import_exclusions_supported: true`. An existing source link keeps its selection. Repeating a transfer with a different selection returns `409 import_selection_conflict`; use the link policy update endpoint to deliberately change an existing link's filters. `PATCH /connectors/v1/links/{id}` replaces the entire stored policy. Include every policy field you want to retain, including `deletes`, `collisions`, and existing size/MIME filters. Omitted fields return to their defaults; PATCH does not merge policy objects. | Field | Description | | - | - | | `direction` | `import`, `export`, or `both` | | `remote.folder_id` | Required. From the browse `import_ref` or `browse_ref`. | | `remote.resource_type` | Provider-declared collection. Omit for the provider default. | | `vault_id` | Destination vault. Must be granted if you use [installations](/connectors/installations). | | `matter_id` | Optional association with a [matter](/matters) | | `run_mode` | `auto` (default) or `full_reconcile` to force a complete re-scan | | `export_destination` | For `direction: "both"`. Defaults to a `CaseMark Output` subfolder under `remote`. | ### When a run does not start `run.started` can be `false` with a `reason`. This is not an error: | Reason | Meaning | | - | - | | `already_running` | A run for this link is in flight | | `stale_run_recovery` | A previous run is being reconciled first | | `ingestion_backlog` | The vault ingestion queue is saturated; `backlog` gives the depth | The link is created either way. Poll it and the run will begin. ## Keeping a folder current For a standing promise instead of a one-shot, use `/sync-link`. Same body, minus `run_mode`. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /connectors/v1/sync-link ``` It backfills now, then stays current on a sweep cycle. Due links run incrementally about every 15 minutes. Once a day the sweep runs a full reconcile instead, which catches deletions and moved folders that per-file change feeds cannot report. An existing `once` link is upgraded in place, keeping its ledger and cursor. Nothing re-imports. To step back down or pause: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X PATCH https://api.case.dev/connectors/v1/links/link_55aa \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "mode": "once" }' ``` `PATCH` also accepts `state` (`paused` or `ready`) and a replacement `policy`. ## Step 3: Follow progress ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/links/{id} ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "link_55aa", "direction": "import", "mode": "once", "automation_status": "manual_only", "state": "running", "vault_id": "vault_abc123", "counts": { "synced": 118, "pending": 12, "queued": 9, "processing": 3, "failed": 1, "skipped": 4, "tombstoned": 0 }, "active_run": { "id": "run_77cd", "trigger": "manual", "mode": "backfill", "status": "running", "stats": { "listed": 135, "added": 118, "updated": 0, "deleted": 0, "skipped": 4, "failed": 1, "bytes": 884213504 }, "started_at": "2026-01-15T10:32:00Z", "finished_at": null, "error": null }, "last_run": null } ``` ### Link states | State | Meaning | | - | - | | `ready` | Idle, will run when asked or swept | | `running` | A run is executing | | `active` | Synced and current | | `paused` | Suspended—by you, or by a lost grant | | `orphaned` | Its provider folder or vault is gone. `orphan_reason` says which. | | `error` | The last run failed in a way that needs attention | A run that fails because the provider was rate-limiting or temporarily unavailable does not need attention: the link returns to `ready` and the sweep retries it on its own, waiting 15 minutes after the first failure and doubling after each consecutive one, up to a day. `retry_at` shows the earliest retry; a manual sync does not wait for it. Only a permanent failure, or ten consecutive failures in a row, lands in `error`. ### Run statuses `running`, `completed`, `completed_with_errors`, or `failed`. `completed_with_errors` means the run finished and some files failed—check the ledger for which. > [!NOTE] > > `counts.pending` is the umbrella for everything not yet settled. `queued` and `processing` are subsets of it, so do not add them together. ## Per-file results Run stats tell you how many. The ledger tells you which. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /connectors/v1/links/{id}/objects ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/connectors/v1/links/link_55aa/objects?state=failed" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` Each row carries the provider item, the vault object it became, its path, its content version, its state, and an error when one applies. | State | Meaning | | - | - | | `pending` | Recorded, not started | | `transferring` | Bytes in flight | | `ingesting` | In the vault, being OCR'd and indexed | | `synced` | Done | | `skipped` | Excluded by policy—size or MIME filter | | `failed` | Did not transfer. The row carries the reason. | | `tombstoned` | Source file is gone and the delete policy was applied | Filter by `state` and page with `cursor`. ## Events instead of polling For anything longer than a few seconds, subscribe rather than poll. These [events](/events/event-types) carry connector progress: | Event | Fires when | | - | - | | `run.progress` | An import is running: its stage, counts so far, and the files copied since the last event. Sent at most every 5 seconds, and whenever the stage changes | | `run.completed` | A run finished, with full stats—possibly with per-file errors | | `run.failed` | A run failed before completing | | `link.objects_changed` | A run changed the set of synced objects | | `link.orphaned` | The provider folder, provider access, or vault went away | | `connection.reauth_required` | The account needs reconnecting | All connector events require the `connectors` scope on your webhook endpoint. `run.progress` moves through two stages. `discovering` means the provider folder is still being listed, and `found` counts the files seen so far. `copying` means files are being transferred, and `stats` counts what has been added, updated, skipped and failed. `recentPaths` holds up to 20 paths of files copied since the previous event. Events can arrive out of order, so ignore one whose `sequence` is lower than the last you saw for that run. The run ends with `run.completed` or `run.failed`. ## Deleting a link ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} DELETE /connectors/v1/links/{id} ``` Deletes the link and its ledger. Vault documents are kept by default. Add `?vault_docs=delete` to remove the documents an import link brought in. That cleanup runs as a durable background workflow and returns `202`. > [!WARNING] > > `vault_docs=delete` is not reversible. Confirm with the user before calling it. ## Next steps > [card] [Errors & Recovery](/connectors/errors) > > What each failure means and which ones to retry > [card] [Providers](/connectors/providers) > > How Clio and Google Drive differ in hierarchy, change detection, and rate budget > [card] [Vault Search](/vault/search) > > Search the documents once they have been ingested # Contract Analysis Source: https://docs.case.dev/cookbooks/contract-analysis Extract key terms, identify risks, and compare clauses across contracts ## What You'll Build A contract analysis pipeline that: 1. Uploads contracts to a searchable vault 2. Extracts key terms (parties, dates, amounts, obligations) 3. Identifies risky clauses with severity ratings 4. Compares similar clauses across multiple contracts 5. Generates a formatted risk report **Time to complete:** 25 minutes ## Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart LR A["Contract Upload"] --> B["OCR Processing"] B --> C["Vault Storage
+ Indexing"] C --> D["Vault Search"] D --> E["LLM Analysis
Key Terms + Risk Flags"] E --> F["PDF Report
(Formatted)"] ``` ## Prerequisites * Case.dev API key ([get one here](https://console.case.dev)) * Contract documents (PDF, DOCX, or images) *** ## Step 1: Create a Contract Vault Set up a vault to store and index your contracts: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Contracts — Q1 2024" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const vault = await client.vault.create({ name: 'Contracts — Q1 2024' }); console.log(`Vault ID: ${vault.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) vault = client.vault.create(name='Contracts — Q1 2024') print(f'Vault ID: {vault.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Contracts — Q1 2024"), }) fmt.Println(vault.ID) ``` ## Step 2: Upload and Index a Contract Upload a contract, run OCR if needed, and index it for search: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import fs from 'fs'; async function uploadContract( vaultId: string, filePath: string, metadata?: Record ) { const filename = filePath.split('/').pop()!; const contentType = filename.endsWith('.pdf') ? 'application/pdf' : 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'; // 1. Upload to vault const upload = await client.vault.upload(vaultId, { filename, contentType, metadata: { type: 'contract', ...metadata } }); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': contentType }, body: fs.readFileSync(filePath) }); // 2. Ingest (OCR + embedding generation) await client.vault.ingest(vaultId, upload.objectId); // 3. Wait for indexing let obj = await client.vault.objects.retrieve(vaultId, upload.objectId); while (obj.ingestionStatus === 'processing') { await new Promise(r => setTimeout(r, 5000)); obj = await client.vault.objects.retrieve(vaultId, upload.objectId); } console.log(`Uploaded and indexed: ${filename} (${obj.ingestionStatus})`); return { objectId: upload.objectId, filename }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time import requests def upload_contract(vault_id: str, file_path: str, metadata: dict = None): filename = os.path.basename(file_path) content_type = 'application/pdf' if filename.endswith('.pdf') else 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' # 1. Upload to vault upload = client.vault.upload(vault_id, filename=filename, content_type=content_type, metadata={ 'type': 'contract', **(metadata or {}) } ) with open(file_path, 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': content_type}) # 2. Ingest (OCR + embedding generation) client.vault.ingest(upload.object_id, id=vault_id) # 3. Wait for indexing obj = client.vault.objects.retrieve(vault_id, upload.object_id) while obj.ingestion_status == 'processing': time.sleep(5) obj = client.vault.objects.retrieve(vault_id, upload.object_id) print(f'Uploaded and indexed: {filename} ({obj.ingestion_status})') return {'object_id': upload.object_id, 'filename': filename} ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` > [!NOTE] > > **Ingestion handles everything.** Vault ingestion automatically runs OCR on scanned PDFs, chunks the text, and generates embeddings. You don't need to call OCR separately. ## Step 3: Extract Key Terms Use vault search to retrieve the contract text and extract structured terms: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search vault for key contract sections casedev vault search --id $VAULT_ID \ --query "parties effective date termination payment obligations" \ --method hybrid --limit 15 # Then extract terms via LLM (pipe contract text as content) casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a contract analyst. Extract key terms and return as JSON."}' \ --message '{role: user, content: ""}' \ --temperature 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function extractKeyTerms(vaultId: string, objectId: string) { // Search for key sections of this specific contract const results = await client.vault.search(vaultId, { query: 'parties effective date termination payment obligations liability governing law', method: 'hybrid', limit: 15 }); const contractText = results.chunks.map(c => c.text).join('\n\n'); const extraction = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a contract analyst. Extract key terms and return as JSON: { "parties": [{"name": "...", "role": "..."}], "effective_date": "YYYY-MM-DD", "termination_date": "YYYY-MM-DD", "value": {"amount": 0, "currency": "USD"}, "governing_law": "...", "key_obligations": ["..."], "termination_clauses": ["..."], "renewal": {"type": "auto|manual|none", "notice_period": "..."}, "risk_flags": [{"clause": "...", "section": "...", "severity": "high|medium|low", "reason": "..."}] }` }, { role: 'user', content: contractText } ], temperature: 0 }); return JSON.parse(extraction.choices[0].message.content); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import json def extract_key_terms(vault_id: str, object_id: str): # Search for key sections of this specific contract results = client.vault.search(vault_id, query='parties effective date termination payment obligations liability governing law', method='hybrid', top_k=15 ) contract_text = '\n\n'.join(c.text for c in results.chunks) extraction = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': '''You are a contract analyst. Extract key terms and return as JSON: { "parties": [{"name": "...", "role": "..."}], "effective_date": "YYYY-MM-DD", "termination_date": "YYYY-MM-DD", "value": {"amount": 0, "currency": "USD"}, "governing_law": "...", "key_obligations": ["..."], "termination_clauses": ["..."], "renewal": {"type": "auto|manual|none", "notice_period": "..."}, "risk_flags": [{"clause": "...", "section": "...", "severity": "high|medium|low", "reason": "..."}] }''' }, {'role': 'user', 'content': contract_text} ], temperature=0 ) return json.loads(extraction.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search for key sections results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("parties effective date termination payment obligations liability governing law"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(15)), }) // Build contract text from chunks var contractText string for _, chunk := range results.Chunks { contractText += chunk.Text + "\n\n" } // Extract key terms via LLM resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a contract analyst. Extract key terms and return as JSON."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(contractText), }, }), Temperature: casedev.F(float64(0)), }) fmt.Println(resp.Choices[0].Message.Content) ``` ```json title="Example Output" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "parties": [ {"name": "Acme Corp", "role": "Vendor"}, {"name": "BigCo Inc", "role": "Client"} ], "effective_date": "2024-01-01", "termination_date": "2026-12-31", "value": {"amount": 500000, "currency": "USD"}, "governing_law": "Delaware", "key_obligations": [ "Vendor shall deliver software by Q2 2024", "Client shall provide access to systems within 30 days" ], "termination_clauses": [ "Either party may terminate with 90 days notice", "Immediate termination for material breach" ], "renewal": {"type": "auto", "notice_period": "60 days"}, "risk_flags": [ { "clause": "Unlimited liability", "section": "Section 8.2", "severity": "high", "reason": "No cap on liability exposes vendor to unlimited damages" }, { "clause": "Non-compete — 5 years", "section": "Section 12.1", "severity": "high", "reason": "Non-compete extends 5 years post-termination, unusually long" }, { "clause": "Auto-renewal with price escalation", "section": "Section 3.4", "severity": "medium", "reason": "Annual 8% price increase on auto-renewal without cap" } ] } ``` ## Step 4: Compare Clauses Across Contracts Search your vault to find and compare similar clauses across multiple contracts: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for liability clauses across contracts casedev vault search --id $VAULT_ID \ --query "liability clause terms conditions" \ --method hybrid --limit 20 # Compare via LLM casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a senior contract attorney. Compare liability clauses."}' \ --message '{role: user, content: "Compare these liability clauses: "}' \ --temperature 0.3 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function compareClauses(vaultId: string, clauseType: string) { // Search for a specific clause type across all contracts const results = await client.vault.search(vaultId, { query: `${clauseType} clause terms conditions`, method: 'hybrid', limit: 20 }); const chunks = results.chunks.map(c => ({ text: c.text, source: c.filename })); const comparison = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a senior contract attorney. Compare ${clauseType} clauses across multiple contracts. For each contract: - Summarize the clause terms - Note any unusual or favorable/unfavorable provisions - Rate the risk level (high/medium/low) Then provide: - A comparison table - A recommendation on which terms are most favorable - Suggested negotiation points for future contracts` }, { role: 'user', content: `Compare these ${clauseType} clauses:\n\n${ chunks.map(c => `### ${c.source}\n${c.text}`).join('\n\n') }` } ], temperature: 0.3 }); return comparison.choices[0].message.content; } // Example: Compare liability clauses across all contracts const liabilityComparison = await compareClauses(vault.id, 'liability'); console.log(liabilityComparison); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def compare_clauses(vault_id: str, clause_type: str): # Search for a specific clause type across all contracts results = client.vault.search(vault_id, query=f'{clause_type} clause terms conditions', method='hybrid', top_k=20 ) chunks = [{'text': c.text, 'source': c.filename} for c in results.chunks] comparison = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': f'''You are a senior contract attorney. Compare {clause_type} clauses across multiple contracts. For each contract: - Summarize the clause terms - Note any unusual or favorable/unfavorable provisions - Rate the risk level (high/medium/low) Then provide: - A comparison table - A recommendation on which terms are most favorable - Suggested negotiation points for future contracts''' }, { 'role': 'user', 'content': f"Compare these {clause_type} clauses:\n\n" + '\n\n'.join( f"### {c['source']}\n{c['text']}" for c in chunks ) } ], temperature=0.3 ) return comparison.choices[0].message.content # Example: Compare liability clauses across all contracts liability_comparison = compare_clauses(vault.id, 'liability') print(liability_comparison) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search for a specific clause type across all contracts results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("liability clause terms conditions"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(20)), }) // Build context from chunks var clauseText string for _, chunk := range results.Chunks { clauseText += fmt.Sprintf("### %s\n%s\n\n", chunk.Filename, chunk.Text) } // Compare clauses via LLM comparison, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a senior contract attorney. Compare liability clauses across multiple contracts."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Compare these liability clauses:\n\n" + clauseText), }, }), Temperature: casedev.F(float64(0.3)), }) fmt.Println(comparison.Choices[0].Message.Content) ``` ## Production Tips ### Error Handling ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # CLI displays errors to stderr with status codes casedev vault search --id $VAULT_ID --query "key terms" # Error: 404 Not Found — Contract not found in vault # Error: 429 Too Many Requests — retry after a delay ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try { const terms = await extractKeyTerms(vaultId, objectId); } catch (error) { if (error.status === 404) { console.error('Contract not found in vault'); } else if (error.status === 429) { console.error('Rate limited — retry after a delay'); } else { console.error('Extraction failed:', error.message); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try: terms = extract_key_terms(vault_id, object_id) except casedev.NotFoundError: print('Contract not found in vault') except casedev.RateLimitError: print('Rate limited — retry after a delay') except casedev.APIError as e: print(f'Extraction failed: {e.message}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} terms, err := extractKeyTerms(ctx, vaultID, objectID) if err != nil { var apiErr *casedev.Error if errors.As(err, &apiErr) { switch apiErr.StatusCode { case 404: fmt.Println("Contract not found in vault") case 429: fmt.Println("Rate limited — retry after a delay") default: fmt.Printf("Extraction failed: %s\n", apiErr.Message) } } } ``` ### Use Webhooks for Production Pipelines Instead of polling for ingestion status, subscribe to vault events: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault:events:subscriptions create \ --id $VAULT_ID \ --callback-url "https://your-app.com/webhooks/vault" \ --event-type object.ingested \ --event-type object.failed ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.vault.events.subscriptions.create(vaultId, { url: 'https://your-app.com/webhooks/vault', events: ['object.ingested', 'object.failed'] }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.vault.events.subscriptions.create(vault_id, callback_url='https://your-app.com/webhooks/vault', event_types=['object.ingested', 'object.failed'] ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.Vault.Events.Subscriptions.New(ctx, vaultID, casedev.VaultEventSubscriptionNewParams{ CallbackURL: casedev.F("https://your-app.com/webhooks/vault"), EventTypes: casedev.F([]string{"object.ingested", "object.failed"}), }) ``` > [!TIP] > > Use `temperature: 0` for key term extraction and risk identification. The lower temperature ensures more deterministic, factual outputs. *** ## Next Steps * [Vault Search Reference](/vault/search) — Advanced search methods and filtering * [Chat Completions](/llms/chat-completions) — Streaming, structured output, and more * [Discovery Pipeline](/cookbooks/discovery-pipeline) — Batch document processing # Deposition Workflow Source: https://docs.case.dev/cookbooks/deposition-workflow Transcribe and analyze witness testimony with speaker labels, vault storage, and cross-examination reports ## What You'll Build A complete deposition processing pipeline that: 1. Transcribes audio with speaker identification 2. Stores transcripts in a searchable vault 3. Generates timelines of key testimony 4. Cross-references witnesses to find contradictions 5. Produces formatted impeachment reports **Time to complete:** 30 minutes ## Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart LR A["Audio Files
(per witness)"] --> B["Voice Transcription
+ Speakers"] B --> C["Vault Storage
+ Indexing"] C --> D["Vault Search"] D --> E["LLM Analysis"] E --> F["PDF Report
(Formatted)"] ``` ## Prerequisites * Case.dev API key ([get one here](https://console.case.dev)) * A vault for storing transcripts * Deposition audio files (MP3, M4A, WAV, etc.) *** ## Step 1: Set Up Your Vault Create a vault to hold all deposition transcripts for a case: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Smith v. Jones — Depositions" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const vault = await client.vault.create({ name: 'Smith v. Jones — Depositions' }); console.log(`Vault ID: ${vault.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) vault = client.vault.create(name='Smith v. Jones — Depositions') print(f'Vault ID: {vault.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Smith v. Jones — Depositions"), }) fmt.Println(vault.ID) ``` ## Step 2: Upload and Transcribe a Deposition Upload the audio file to your vault, then transcribe with speaker labels: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function transcribeDeposition( vaultId: string, audioFile: Buffer, filename: string, witnessName: string, speakersExpected: number = 3 // Witness, attorney, opposing counsel ) { // 1. Upload audio to the vault const upload = await client.vault.upload(vaultId, { filename, contentType: 'audio/mpeg', metadata: { witness: witnessName, type: 'deposition-audio' } }); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'audio/mpeg' }, body: audioFile }); // 2. Transcribe with speaker labels const job = await client.voice.transcription.create({ vault_id: vaultId, object_id: upload.objectId, speaker_labels: true, speakers_expected: speakersExpected, word_boost: ['plaintiff', 'defendant', 'counsel', 'objection', 'stipulate'] }); // 3. Poll until complete let result = await client.voice.transcription.retrieve(job.id); while (result.status !== 'completed' && result.status !== 'failed') { await new Promise(r => setTimeout(r, 10000)); result = await client.voice.transcription.retrieve(job.id); } if (result.status === 'failed') { throw new Error(`Transcription failed: ${result.error}`); } console.log(`Transcribed ${witnessName}: ${result.word_count} words, ${Math.round(result.audio_duration / 60)} minutes`); return result; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time import requests def transcribe_deposition( vault_id: str, audio_path: str, witness_name: str, speakers_expected: int = 3 ): filename = os.path.basename(audio_path) # 1. Upload audio to the vault upload = client.vault.upload(vault_id, filename=filename, content_type='audio/mpeg', metadata={ 'witness': witness_name, 'type': 'deposition-audio' } ) with open(audio_path, 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': 'audio/mpeg'}) # 2. Transcribe with speaker labels job = client.voice.transcription.create( vault_id=vault_id, object_id=upload.object_id, speaker_labels=True, speakers_expected=speakers_expected, word_boost=['plaintiff', 'defendant', 'counsel', 'objection', 'stipulate'] ) # 3. Poll until complete result = client.voice.transcription.retrieve(job.id) while result.status not in ('completed', 'failed'): time.sleep(10) result = client.voice.transcription.retrieve(job.id) if result.status == 'failed': raise Exception(f'Transcription failed: {result.error}') print(f'Transcribed {witness_name}: {result.word_count} words, {round(result.audio_duration / 60)} minutes') return result ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` > [!NOTE] > > **Speaker labels are automatic.** The transcription service identifies speakers by voice characteristics. Set `speakers_expected` for better accuracy when you know the number of participants. ## Step 3: Store Transcript in the Vault The vault-based transcription automatically stores the transcript. Now ingest it for semantic search: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault ingest --id $VAULT_ID --object-id $OBJECT_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function indexTranscript( vaultId: string, resultObjectId: string, witnessName: string ) { // Ingest the transcript for embedding generation + search await client.vault.ingest(vaultId, resultObjectId); // Poll until indexed let obj = await client.vault.objects.retrieve(vaultId, resultObjectId); while (obj.ingestionStatus === 'processing') { await new Promise(r => setTimeout(r, 5000)); obj = await client.vault.objects.retrieve(vaultId, resultObjectId); } console.log(`Indexed transcript for ${witnessName}: ${obj.ingestionStatus}`); return obj; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def index_transcript(vault_id: str, result_object_id: str, witness_name: str): # Ingest the transcript for embedding generation + search client.vault.ingest(result_object_id, id=vault_id) # Poll until indexed obj = client.vault.objects.retrieve(vault_id, result_object_id) while obj.ingestion_status == 'processing': time.sleep(5) obj = client.vault.objects.retrieve(vault_id, result_object_id) print(f'Indexed transcript for {witness_name}: {obj.ingestion_status}') return obj ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Vault.Ingest(ctx, vaultID, objectID) fmt.Println(result.Status) ``` > [!TIP] > > For production, use [webhooks](/vault/webhooks) instead of polling for both transcription and ingestion status changes. ## Step 4: Batch Process Multiple Depositions Process all depositions for a case in sequence: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Process depositions sequentially for AUDIO in depositions/*.mp3; do WITNESS=$(basename "$AUDIO" .mp3) echo "Processing: $WITNESS" # Transcribe casedev voice:transcription create \ --vault-id $VAULT_ID --file "$AUDIO" \ --speaker-labels --language en-US # Index transcript is automatic when vault indexing is enabled done ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} interface Deposition { audioFile: Buffer; filename: string; witnessName: string; date: string; } async function processCase(vaultId: string, depositions: Deposition[]) { const results = []; for (const depo of depositions) { console.log(`\nProcessing: ${depo.witnessName} (${depo.date})`); // Transcribe const transcription = await transcribeDeposition( vaultId, depo.audioFile, depo.filename, depo.witnessName ); // Index for search await indexTranscript(vaultId, transcription.result_object_id, depo.witnessName); results.push({ witness: depo.witnessName, date: depo.date, objectId: transcription.result_object_id, wordCount: transcription.word_count, duration: transcription.audio_duration }); } console.log(`\nProcessed ${results.length} depositions`); return results; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def process_case(vault_id: str, depositions: list[dict]): results = [] for depo in depositions: print(f"\nProcessing: {depo['witness_name']} ({depo['date']})") # Transcribe transcription = transcribe_deposition( vault_id, depo['audio_path'], depo['witness_name'] ) # Index for search index_transcript(vault_id, transcription.result_object_id, depo['witness_name']) results.append({ 'witness': depo['witness_name'], 'date': depo['date'], 'object_id': transcription.result_object_id, 'word_count': transcription.word_count, 'duration': transcription.audio_duration }) print(f'\nProcessed {len(results)} depositions') return results ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} func processCase(ctx context.Context, client *casedev.Client, vaultID string, depositions []Deposition) []Result { var results []Result for _, depo := range depositions { fmt.Printf("\nProcessing: %s (%s)\n", depo.WitnessName, depo.Date) transcription := transcribeDeposition(ctx, client, vaultID, depo) indexTranscript(ctx, client, vaultID, transcription.ResultObjectID, depo.WitnessName) results = append(results, Result{ Witness: depo.WitnessName, ObjectID: transcription.ResultObjectID, }) } fmt.Printf("\nProcessed %d depositions\n", len(results)) return results } ``` ## Step 5: Generate a Testimony Timeline Search across all depositions and build a chronological timeline of events: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search vault for testimony, then pipe to LLM casedev vault search --id $VAULT_ID \ --query "timeline of events" --method hybrid --limit 15 casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Extract a chronological timeline from deposition testimony."}' \ --message '{role: user, content: ""}' \ --temperature 0.2 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function generateTimeline(vaultId: string, topic: string) { // Search across all indexed transcripts const results = await client.vault.search(vaultId, { query: `timeline of events regarding ${topic}`, method: 'hybrid', limit: 20 }); const chunks = results.chunks.map(c => c.text).join('\n\n'); const sources = results.sources.map(s => s.filename).join(', '); // Generate structured timeline const timeline = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a litigation paralegal. Create a chronological timeline from deposition testimony. For each event: - Date (exact or approximate) - What happened - Who testified about it (witness name) - Direct quote from testimony - Page/line reference if available Format as a markdown table sorted by date.` }, { role: 'user', content: `Topic: ${topic}\n\nTestimony excerpts:\n${chunks}\n\nSources: ${sources}` } ], temperature: 0.2 }); return timeline.choices[0].message.content; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def generate_timeline(vault_id: str, topic: str): # Search across all indexed transcripts results = client.vault.search(vault_id, query=f'timeline of events regarding {topic}', method='hybrid', top_k=20 ) chunks = '\n\n'.join(c.text for c in results.chunks) sources = ', '.join(s.filename for s in results.sources) # Generate structured timeline timeline = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': '''You are a litigation paralegal. Create a chronological timeline from deposition testimony. For each event: - Date (exact or approximate) - What happened - Who testified about it (witness name) - Direct quote from testimony - Page/line reference if available Format as a markdown table sorted by date.''' }, { 'role': 'user', 'content': f'Topic: {topic}\n\nTestimony excerpts:\n{chunks}\n\nSources: {sources}' } ], temperature=0.2 ) return timeline.choices[0].message.content ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search vault for testimony on a topic results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F(topic), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(15)), }) // Build context from search results var chunks string for _, c := range results.Chunks { chunks += c.Text + "\n\n" } // Generate timeline via LLM timeline, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a litigation paralegal. Extract a chronological timeline from deposition testimony."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Topic: " + topic + "\n\nTestimony excerpts:\n" + chunks), }, }), Temperature: casedev.F(float64(0.2)), }) fmt.Println(timeline.Choices[0].Message.Content) ``` ## Step 6: Find Contradictions Across Witnesses Search for a topic and compare what different witnesses said: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for testimony across witnesses casedev vault search --id $VAULT_ID \ --query "accident description" --method hybrid --limit 20 # Analyze contradictions casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Identify contradictions and inconsistencies across witness testimony."}' \ --message '{role: user, content: ""}' \ --temperature 0.3 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function findContradictions(vaultId: string, topic: string) { // Search across all testimony for the topic const results = await client.vault.search(vaultId, { query: topic, method: 'hybrid', limit: 20 }); // Group by source file (each transcript = one witness) const byWitness: Record = {}; for (const chunk of results.chunks) { const witness = chunk.metadata?.witness || chunk.filename; if (!byWitness[witness]) byWitness[witness] = []; byWitness[witness].push(chunk.text); } // Use AI to find contradictions const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a litigation attorney preparing for cross-examination. Analyze testimony from multiple witnesses and identify: 1. Direct contradictions (conflicting facts) 2. Inconsistencies (different emphasis or omissions) 3. Corroborations (matching testimony across witnesses) For each finding, cite the specific quote and witness name. Rate each contradiction as HIGH, MEDIUM, or LOW significance.` }, { role: 'user', content: `Topic: ${topic}\n\nTestimony by witness:\n${ Object.entries(byWitness) .map(([w, texts]) => `\n## ${w}\n${texts.join('\n')}`) .join('\n') }` } ], temperature: 0.3 }); return analysis.choices[0].message.content; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def find_contradictions(vault_id: str, topic: str): # Search across all testimony for the topic results = client.vault.search(vault_id, query=topic, method='hybrid', top_k=20 ) # Group by source file (each transcript = one witness) by_witness = {} for chunk in results.chunks: witness = chunk.metadata.get('witness', chunk.filename) if witness not in by_witness: by_witness[witness] = [] by_witness[witness].append(chunk.text) # Use AI to find contradictions testimony_text = '\n'.join([ f'\n## {w}\n{chr(10).join(texts)}' for w, texts in by_witness.items() ]) analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': '''You are a litigation attorney preparing for cross-examination. Analyze testimony from multiple witnesses and identify: 1. Direct contradictions (conflicting facts) 2. Inconsistencies (different emphasis or omissions) 3. Corroborations (matching testimony across witnesses) For each finding, cite the specific quote and witness name. Rate each contradiction as HIGH, MEDIUM, or LOW significance.''' }, { 'role': 'user', 'content': f'Topic: {topic}\n\nTestimony by witness:\n{testimony_text}' } ], temperature=0.3 ) return analysis.choices[0].message.content ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search across all testimony for the topic results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F(topic), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(20)), }) // Group testimony by witness and build context var testimonyText string for _, chunk := range results.Chunks { testimonyText += fmt.Sprintf("## %s\n%s\n\n", chunk.Filename, chunk.Text) } // Analyze contradictions via LLM analysis, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a litigation attorney. Identify contradictions, inconsistencies, and corroborations across witness testimony."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Topic: " + topic + "\n\nTestimony by witness:\n" + testimonyText), }, }), Temperature: casedev.F(float64(0.3)), }) fmt.Println(analysis.Choices[0].Message.Content) ``` ## Complete Example Putting it all together: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Smith v. Jones — Depositions" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; import fs from 'fs'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); async function main() { // Create a vault for the case const vault = await client.vault.create({ name: 'Smith v. Jones — Depositions' }); // Process depositions await processCase(vault.id, [ { audioFile: fs.readFileSync('depositions/ceo-johnson.m4a'), filename: 'ceo-johnson.m4a', witnessName: 'CEO Johnson', date: '2024-03-15' }, { audioFile: fs.readFileSync('depositions/cto-smith.m4a'), filename: 'cto-smith.m4a', witnessName: 'CTO Smith', date: '2024-03-18' }, { audioFile: fs.readFileSync('depositions/it-director-williams.m4a'), filename: 'it-director-williams.m4a', witnessName: 'IT Director Williams', date: '2024-03-20' } ]); // Generate impeachment report const report = await generateImpeachmentReport( vault.id, 'Smith v. Jones', [ 'When the CEO learned of the data breach', 'Who authorized the system shutdown', 'Timeline of security notifications' ] ); console.log('Report generated successfully'); } main(); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) def main(): # Create a vault for the case vault = client.vault.create(name='Smith v. Jones — Depositions') # Process depositions process_case(vault.id, [ { 'audio_path': 'depositions/ceo-johnson.m4a', 'witness_name': 'CEO Johnson', 'date': '2024-03-15' }, { 'audio_path': 'depositions/cto-smith.m4a', 'witness_name': 'CTO Smith', 'date': '2024-03-18' }, { 'audio_path': 'depositions/it-director-williams.m4a', 'witness_name': 'IT Director Williams', 'date': '2024-03-20' } ]) # Generate impeachment report report = generate_impeachment_report( vault.id, 'Smith v. Jones', [ 'When the CEO learned of the data breach', 'Who authorized the system shutdown', 'Timeline of security notifications' ] ) print('Report generated successfully') main() ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Smith v. Jones — Depositions"), }) fmt.Println(vault.ID) ``` ## Example Contradiction Report ```markdown theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} ### Topic: When the CEO learned of the data breach **CEO Johnson (Deposition, March 15, 2024):** > "I was not informed of any security incident until July 15th, > when our IT director called me at home." **CTO Smith (Deposition, March 18, 2024):** > "I sent an urgent email to the entire executive team, including > the CEO, on July 12th explicitly detailing the intrusion and > recommending immediate action." **IT Director Williams (Deposition, March 20, 2024):** > "The CTO instructed me to brief the CEO on July 12th. I called > his office but was told he was unavailable. I left a detailed > voicemail." ### Analysis The CEO claims no knowledge until July 15th, but both the CTO and IT Director indicate notification attempts on July 12th — three days earlier. The CTO claims direct email notification, and the IT Director confirms a voicemail was left. ### Impeachment Strategy 1. Introduce July 12th email as Exhibit A 2. Subpoena CEO's voicemail records for July 12th 3. Confront CEO with CTO and IT Director testimony ``` *** ## Production Tips ### Error Handling ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # CLI displays errors to stderr with status codes casedev voice:transcription create --vault-id $VAULT_ID --object-id $AUDIO_OBJECT_ID # Error: 413 Payload Too Large — split into segments # Error: 429 Too Many Requests — retry after a delay ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try { const result = await transcribeDeposition(vaultId, audio, filename, witness); } catch (error) { if (error.status === 413) { console.error('Audio file too large — split into segments'); } else if (error.status === 429) { console.error('Rate limited — retry after a delay'); } else { console.error('Transcription failed:', error.message); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try: result = transcribe_deposition(vault_id, audio_path, witness) except casedev.APIError: print('Audio file too large — split into segments') except casedev.RateLimitError: print('Rate limited — retry after a delay') except casedev.APIError as e: print(f'Transcription failed: {e.message}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, err := transcribeDeposition(ctx, client, vaultID, audio, filename, witness) if err != nil { var apiErr *casedev.Error if errors.As(err, &apiErr) { switch apiErr.StatusCode { case 413: fmt.Println("Audio file too large — split into segments") case 429: fmt.Println("Rate limited — retry after a delay") default: fmt.Printf("Transcription failed: %s\n", apiErr.Message) } } } ``` ### Use Webhooks in Production Instead of polling, subscribe to events for transcription and ingestion completion: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Subscribe to vault events casedev vault:events:subscriptions create \ --id $VAULT_ID \ --callback-url "https://your-app.com/webhooks/vault" \ --event-type object.ingested \ --event-type object.failed # Subscribe to transcription events # Your webhook handler receives status updates automatically ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Subscribe to vault events await client.vault.events.subscriptions.create(vaultId, { url: 'https://your-app.com/webhooks/vault', events: ['object.ingested', 'object.failed'] }); // Subscribe to transcription events // Your webhook handler receives status updates automatically ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Subscribe to vault events client.vault.events.subscriptions.create(vault_id, callback_url='https://your-app.com/webhooks/vault', event_types=['object.ingested', 'object.failed'] ) # Subscribe to transcription events # Your webhook handler receives status updates automatically ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Subscribe to vault events client.Vault.Events.Subscriptions.New(ctx, vaultID, casedev.VaultEventSubscriptionNewParams{ CallbackURL: casedev.F("https://your-app.com/webhooks/vault"), EventTypes: casedev.F([]string{"object.ingested", "object.failed"}), }) // Subscribe to transcription events // Your webhook handler receives status updates automatically ``` > [!TIP] > > For long depositions (2+ hours), transcription may take several minutes. Webhooks prevent wasted polling requests. *** ## Next Steps * [Voice Transcription Reference](/voice/transcription) — Speaker labels, language options, and more * [Vault Search Reference](/vault/search) — Advanced search methods and filtering * [Discovery Pipeline](/cookbooks/discovery-pipeline) — Batch document processing # Discovery Pipeline Source: https://docs.case.dev/cookbooks/discovery-pipeline Ingest documents, extract text via OCR, generate embeddings, and enable semantic search ## Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart LR A["Document Upload"] --> B["OCR Processing"] B --> C["Embeddings Generation"] C --> D["Search Index"] ``` ## Prerequisites * Case.dev API key * Node.js 18+ or Python 3.9+ * Documents to process (PDFs, images, Word docs) ## Step 1: Create a vault ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Matter 2024-1234 - Discovery" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; import fs from 'fs'; import path from 'path'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const vault = await client.vault.create({ name: 'Matter 2024-1234 - Discovery', description: 'Documents received from opposing counsel' }); console.log(`Created vault: ${vault.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) vault = client.vault.create( name='Matter 2024-1234 - Discovery', description='Documents received from opposing counsel' ) print(f'Created vault: {vault.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Matter 2024-1234 - Discovery"), Description: casedev.F("Documents received from opposing counsel"), }) fmt.Println(vault.ID) ``` ## Step 2: Subscribe to ingestion events Use webhooks to get notified when documents finish processing instead of polling. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault ingest --id $VAULT_ID --object-id $OBJECT_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const subscription = await client.vault.events.subscriptions.create(vault.id, { callbackUrl: 'https://your-app.com/webhooks/case-vault', eventTypes: ['vault.ingest.completed', 'vault.ingest.failed'] }); console.log(`Webhook subscription: ${subscription.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} subscription = client.vault.events.subscriptions.create(vault.id, callback_url='https://your-app.com/webhooks/case-vault', event_types=['vault.ingest.completed', 'vault.ingest.failed'] ) print(f'Webhook subscription: {subscription.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Vault.Ingest(ctx, objectID, casedev.VaultIngestParams{ ID: casedev.F(vaultID), }) fmt.Println(result.Status) ``` Your webhook endpoint receives events like: ```json title="Webhook payload" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_abc123", "eventType": "vault.ingest.completed", "vaultId": "vault_abc123", "objectId": "obj_xyz789", "data": { "status": "completed" } } ``` > [!NOTE] > > Webhook delivery is **at-least-once**. Use the `id` field as an idempotency key and design handlers to safely process duplicates. See [Vault Webhooks](/vault/webhooks) for signing and retry details. ## Step 3: Batch upload documents ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function uploadDocuments(vaultId: string, documentsDir: string) { const files = fs.readdirSync(documentsDir); const results = []; const contentTypes: Record = { '.pdf': 'application/pdf', '.doc': 'application/msword', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.tiff': 'image/tiff', '.txt': 'text/plain', }; for (const file of files) { const filePath = path.join(documentsDir, file); const stat = fs.statSync(filePath); if (!stat.isFile()) continue; const ext = path.extname(file).toLowerCase(); const contentType = contentTypes[ext] || 'application/octet-stream'; // Get presigned upload URL const upload = await client.vault.upload(vaultId, { filename: file, contentType, metadata: { source: 'discovery', original_path: filePath, } }); // Upload file to S3 const fileBuffer = fs.readFileSync(filePath); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': contentType }, body: fileBuffer }); console.log(`Uploaded: ${file}`); results.push({ file, objectId: upload.objectId }); } return results; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import requests from pathlib import Path def upload_documents(vault_id: str, documents_dir: str): files = list(Path(documents_dir).iterdir()) results = [] content_types = { '.pdf': 'application/pdf', '.doc': 'application/msword', '.docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.png': 'image/png', '.tiff': 'image/tiff', '.txt': 'text/plain', } for file_path in files: if not file_path.is_file(): continue content_type = content_types.get(file_path.suffix.lower(), 'application/octet-stream') # Get presigned upload URL upload = client.vault.upload(vault_id, filename=file_path.name, content_type=content_type, metadata={ 'source': 'discovery', 'original_path': str(file_path), } ) # Upload file to S3 with open(file_path, 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': content_type}) print(f'Uploaded: {file_path.name}') results.append({'file': file_path.name, 'object_id': upload.object_id}) return results ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` ## Step 4: Trigger ingestion Ingestion runs OCR (if needed) and generates embeddings for search. Your webhook will fire when each document finishes. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault ingest --id $VAULT_ID --object-id $OBJECT_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function ingestDocuments(vaultId: string, uploads: { file: string; objectId: string }[]) { for (const { file, objectId } of uploads) { await client.vault.ingest(vaultId, objectId); console.log(`Ingesting: ${file}`); } // Ingestion runs async — your webhook endpoint receives // vault.ingest.completed or vault.ingest.failed for each document } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def ingest_documents(vault_id: str, uploads: list): for upload in uploads: client.vault.ingest(upload['object_id'], id=vault_id) print(f'Ingesting: {upload["file"]}') # Ingestion runs async — your webhook endpoint receives # vault.ingest.completed or vault.ingest.failed for each document ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Vault.Ingest(ctx, objectID, casedev.VaultIngestParams{ ID: casedev.F(vaultID), }) fmt.Println(result.Status) ``` ## Step 5: Search your documents Once your webhook confirms ingestion is complete, documents are searchable. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search \ --id $VAULT_ID \ --query "search query" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function searchDiscovery(vaultId: string, query: string) { const results = await client.vault.search(vaultId, { query, method: 'hybrid', // Combines semantic + keyword limit: 10 }); console.log(`\nResults for: "${query}"\n`); for (const chunk of results.chunks) { console.log(`${chunk.filename} (page ${chunk.page})`); console.log(` Score: ${chunk.hybridScore.toFixed(2)}`); console.log(` "${chunk.text.substring(0, 200)}..."\n`); } return results; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def search_discovery(vault_id: str, query: str): results = client.vault.search(vault_id, query=query, method='hybrid', # Combines semantic + keyword top_k=10 ) print(f'\nResults for: "{query}"\n') for chunk in results.chunks: print(f'{chunk.filename} (page {chunk.page})') print(f' Score: {chunk.hybrid_score:.2f}') print(f' "{chunk.text[:200]}..."\n') return results ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("search query"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), }) for _, chunk := range results.Chunks { fmt.Println(chunk.Text) } ``` ## Complete example ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Matter 2024-1234 - Discovery" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; import fs from 'fs'; import path from 'path'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); async function main() { const documentsDir = './discovery_dump'; // 1. Create vault const vault = await client.vault.create({ name: 'Matter 2024-1234 - Discovery', description: 'Documents from opposing counsel' }); // 2. Subscribe to ingestion events await client.vault.events.subscriptions.create(vault.id, { callbackUrl: 'https://your-app.com/webhooks/case-vault', eventTypes: ['vault.ingest.completed', 'vault.ingest.failed'] }); // 3. Upload and ingest all documents const files = fs.readdirSync(documentsDir); for (const file of files) { const filePath = path.join(documentsDir, file); if (!fs.statSync(filePath).isFile()) continue; const upload = await client.vault.upload(vault.id, { filename: file, contentType: 'application/pdf' }); await fetch(upload.uploadUrl, { method: 'PUT', body: fs.readFileSync(filePath) }); await client.vault.ingest(vault.id, upload.objectId); console.log(`Queued: ${file}`); } // 4. Search (after webhook confirms ingestion is complete) const results = await client.vault.search(vault.id, { query: 'evidence of safety violations in 2023', method: 'hybrid', limit: 10 }); console.log(results.chunks); } main(); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev import requests from pathlib import Path client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) def main(): documents_dir = './discovery_dump' # 1. Create vault vault = client.vault.create( name='Matter 2024-1234 - Discovery', description='Documents from opposing counsel' ) # 2. Subscribe to ingestion events client.vault.events.subscriptions.create(vault.id, callback_url='https://your-app.com/webhooks/case-vault', event_types=['vault.ingest.completed', 'vault.ingest.failed'] ) # 3. Upload and ingest all documents for file_path in Path(documents_dir).iterdir(): if not file_path.is_file(): continue upload = client.vault.upload(vault.id, filename=file_path.name, content_type='application/pdf' ) with open(file_path, 'rb') as f: requests.put(upload.upload_url, data=f) client.vault.ingest(upload.object_id, id=vault.id) print(f'Queued: {file_path.name}') # 4. Search (after webhook confirms ingestion is complete) results = client.vault.search(vault.id, query='evidence of safety violations in 2023', method='hybrid', top_k=10 ) print(results.chunks) if __name__ == '__main__': main() ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Matter 2024-1234 - Discovery"), Description: casedev.F("Documents from opposing counsel"), }) fmt.Println(vault.ID) ``` > [!NOTE] > > **Production tip:** For large document sets (1000+), use parallel uploads with a concurrency limit of 10-20 to maximize throughput while avoiding rate limits. # Document Analyzer Source: https://docs.case.dev/cookbooks/document-analyzer Search documents and generate AI-powered analysis with vault search and LLM ## What You'll Build A script that: 1. Searches your indexed documents in a vault 2. Analyzes the results with an LLM 3. Returns structured insights with source citations **Time to complete:** 15 minutes ## Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart LR A["Your App
vaultId + query"] --> B["Vault Search
Hybrid · 10 chunks + sources"] B --> C["LLM Analysis
Structured response"] ``` ## Prerequisites * Case.dev API key ([get one here](https://console.case.dev)) * A vault with ingested documents (we'll set one up if you don't have one) *** ## Step 1: Set Up Your Vault If you already have a vault with indexed documents, skip to Step 2. ### Create a vault ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/vault \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Legal Research Vault"}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Legal Research Vault" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const vault = await client.vault.create({ name: 'Legal Research Vault' }); console.log(`Vault ID: ${vault.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) vault = client.vault.create(name='Legal Research Vault') print(f'Vault ID: {vault.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Legal Research Vault"), }) fmt.Println(vault.ID) ``` Save the returned `id` — you'll need it. ### Upload a document ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Get upload URL UPLOAD_RESPONSE=$(curl -s -X POST "https://api.case.dev/vault/$VAULT_ID/upload" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"filename": "contract.pdf", "contentType": "application/pdf"}') UPLOAD_URL=$(echo $UPLOAD_RESPONSE | jq -r '.uploadUrl') OBJECT_ID=$(echo $UPLOAD_RESPONSE | jq -r '.objectId') # Upload your file curl -X PUT "$UPLOAD_URL" \ -H "Content-Type: application/pdf" \ --data-binary @contract.pdf ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Get upload URL const upload = await client.vault.upload(vault.id, { filename: 'contract.pdf', contentType: 'application/pdf' }); // Upload the file directly to S3 await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'application/pdf' }, body: fs.readFileSync('contract.pdf') }); console.log(`Object ID: ${upload.objectId}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import requests # Get upload URL upload = client.vault.upload(vault.id, filename='contract.pdf', content_type='application/pdf' ) # Upload the file directly to S3 with open('contract.pdf', 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': 'application/pdf'}) print(f'Object ID: {upload.object_id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` ### Ingest (index) the document ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST "https://api.case.dev/vault/$VAULT_ID/ingest/$OBJECT_ID" \ -H "Authorization: Bearer $CASEDEV_API_KEY" # Check status (poll until completed) curl "https://api.case.dev/vault/$VAULT_ID/objects/$OBJECT_ID" \ -H "Authorization: Bearer $CASEDEV_API_KEY" | jq '.ingestionStatus' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault ingest --id $VAULT_ID --object-id $OBJECT_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.vault.ingest(vault.id, upload.objectId); // Poll until complete let obj = await client.vault.objects.retrieve(vault.id, upload.objectId); while (obj.ingestionStatus === 'processing') { await new Promise(r => setTimeout(r, 5000)); obj = await client.vault.objects.retrieve(vault.id, upload.objectId); } console.log(`Ingestion: ${obj.ingestionStatus}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time client.vault.ingest(upload.object_id, id=vault.id) # Poll until complete obj = client.vault.objects.retrieve(vault.id, upload.object_id) while obj.ingestion_status == 'processing': time.sleep(5) obj = client.vault.objects.retrieve(vault.id, upload.object_id) print(f'Ingestion: {obj.ingestion_status}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Vault.Ingest(ctx, objectID, casedev.VaultIngestParams{ ID: casedev.F(vaultID), }) fmt.Println(result.Status) ``` > [!NOTE] > > **Ingestion is async.** Wait for `ingestionStatus: "completed"` before searching. For production, use [webhooks](/vault/webhooks) instead of polling. ## Step 2: Search Your Documents Query your vault with a natural language question: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST "https://api.case.dev/vault/$VAULT_ID/search" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "What are the key terms of this agreement?", "method": "hybrid", "limit": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search \ --id $VAULT_ID \ --query "What are the key terms of this agreement?" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const searchResults = await client.vault.search(vaultId, { query: 'What are the key terms of this agreement?', method: 'hybrid', limit: 10 }); console.log(`Found ${searchResults.chunks.length} relevant passages`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} search_results = client.vault.search(vault_id, query='What are the key terms of this agreement?', method='hybrid', top_k=10 ) print(f'Found {len(search_results.chunks)} relevant passages') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("What are the key terms of this agreement?"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), }) for _, chunk := range results.Chunks { fmt.Println(chunk.Text) } ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "chunks": [ { "text": "The Parties agree to the following terms...", "object_id": "obj_xyz789", "hybridScore": 0.89, "vectorScore": 0.92, "bm25Score": 0.78 } ], "sources": [ { "id": "obj_xyz789", "filename": "contract.pdf" } ] } ``` ## Step 3: Analyze with an LLM Pass the search results to an LLM for structured analysis: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a legal document analyst. Cite specific passages to support your analysis."}' \ --message '{role: user, content: "\n\nQuestion: What are the key terms of this agreement?"}' \ --temperature 0.3 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const chunks = searchResults.chunks.map(c => c.text).join('\n\n'); const sources = searchResults.sources.map(s => s.filename).join(', '); const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'You are a legal document analyst. Analyze the provided document excerpts and answer the user\'s question. Always cite specific passages to support your analysis.' }, { role: 'user', content: `## Document Excerpts\n\n${chunks}\n\n## Sources\n${sources}\n\n## Question\nWhat are the key terms of this agreement?` } ], temperature: 0.3 }); console.log(analysis.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} chunks = '\n\n'.join(c.text for c in search_results.chunks) sources = ', '.join(s.filename for s in search_results.sources) analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'You are a legal document analyst. Analyze the provided document excerpts and answer the user\'s question. Always cite specific passages to support your analysis.' }, { 'role': 'user', 'content': f'## Document Excerpts\n\n{chunks}\n\n## Sources\n{sources}\n\n## Question\nWhat are the key terms of this agreement?' } ], temperature=0.3 ) print(analysis.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a legal document analyst. Analyze the provided document excerpts and answer the user's question. Always cite specific passages to support your analysis."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("## Document Excerpts\n\n" + chunks + "\n\n## Sources\n" + sources + "\n\n## Question\nWhat are the key terms of this agreement?"), }, }), Temperature: casedev.F(float64(0.3)), }) fmt.Println(resp.Choices[0].Message.Content) ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "choices": [{ "message": { "content": "Based on the contract excerpts, the key terms include:\n\n1. **Payment Terms**: Section 3.2 states that payment is due within 30 days...\n\n2. **Termination**: Either party may terminate with 90 days written notice (Section 7.1)...\n\n3. **Liability Cap**: Liability is limited to the total fees paid in the preceding 12 months (Section 9.3)..." } }], "usage": { "prompt_tokens": 1245, "completion_tokens": 387, "total_tokens": 1632, "cost": 0.004896 } } ``` *** ## Complete Example Putting it all together — a reusable function that searches and analyzes: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Search vault for relevant documents casedev vault search --id $VAULT_ID \ --query "What are the indemnification clauses?" \ --method hybrid --limit 10 # 2. Analyze with LLM casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a senior legal analyst. Answer using only the provided excerpts."}' \ --message '{role: user, content: "\n\nQuestion: What are the indemnification clauses?"}' \ --temperature 0.3 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); async function analyzeDocuments(vaultId: string, query: string) { // 1. Search const searchResults = await client.vault.search(vaultId, { query, method: 'hybrid', limit: 10 }); const chunks = searchResults.chunks.map(c => c.text).join('\n\n'); const sources = searchResults.sources.map(s => s.filename).join(', '); // 2. Analyze const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a senior legal analyst. Provide comprehensive analysis with: 1. Executive Summary 2. Key Findings (cite specific passages) 3. Supporting Evidence 4. Recommendations` }, { role: 'user', content: `## Document Excerpts\n\n${chunks}\n\n## Sources\n${sources}\n\n## Question\n${query}` } ], temperature: 0.3 }); return { answer: analysis.choices[0].message.content, sources: searchResults.sources, usage: analysis.usage }; } // Run it const result = await analyzeDocuments('vault_abc123', 'What are the indemnification clauses?'); console.log(result.answer); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) def analyze_documents(vault_id: str, query: str) -> dict: # 1. Search search_results = client.vault.search(vault_id, query=query, method='hybrid', top_k=10 ) chunks = '\n\n'.join(c.text for c in search_results.chunks) sources = ', '.join(s.filename for s in search_results.sources) # 2. Analyze analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': '''You are a senior legal analyst. Provide comprehensive analysis with: 1. Executive Summary 2. Key Findings (cite specific passages) 3. Supporting Evidence 4. Recommendations''' }, { 'role': 'user', 'content': f'## Document Excerpts\n\n{chunks}\n\n## Sources\n{sources}\n\n## Question\n{query}' } ], temperature=0.3 ) return { 'answer': analysis.choices[0].message.content, 'sources': search_results.sources, 'usage': analysis.usage } # Run it result = analyze_documents('vault_abc123', 'What are the indemnification clauses?') print(result['answer']) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Search vault searchResults, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F(query), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(10)), }) // Build context from chunks var chunks string for _, c := range searchResults.Chunks { chunks += c.Text + "\n\n" } var sources string for _, s := range searchResults.Sources { sources += s.Filename + ", " } // 2. Analyze with LLM analysis, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a senior legal analyst. Answer questions using only the provided document excerpts. Cite sources."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("## Document Excerpts\n\n" + chunks + "\n\n## Question\n" + query), }, }), Temperature: casedev.F(float64(0.3)), }) fmt.Println(analysis.Choices[0].Message.Content) ``` *** ## Extending the Analyzer ### Add Entity Extraction Run a second LLM pass to extract structured entities: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Extract named entities as JSON: {people: [], organizations: [], dates: [], locations: [], monetary_amounts: []}"}' \ --message '{role: user, content: ""}' \ --temperature 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const entities = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Extract named entities as JSON: {people: [], organizations: [], dates: [], locations: [], monetary_amounts: []}' }, { role: 'user', content: chunks } ], temperature: 0 }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} entities = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Extract named entities as JSON: {people: [], organizations: [], dates: [], locations: [], monetary_amounts: []}' }, {'role': 'user', 'content': chunks} ], temperature=0 ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} entities, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Extract named entities as JSON: {people: [], organizations: [], dates: [], locations: [], monetary_amounts: []}"), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(chunks), }, }), Temperature: casedev.F(float64(0)), }) fmt.Println(entities.Choices[0].Message.Content) ``` ## Production Tips ### Error Handling ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # CLI displays errors to stderr with status codes casedev vault search --id $VAULT_ID --query "analysis query" # Error: 404 Not Found — check your vault ID # Error: 429 Too Many Requests — retry after a delay ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try { const result = await analyzeDocuments(vaultId, query); console.log(result.answer); } catch (error) { if (error.status === 404) { console.error('Vault not found — check your vault ID'); } else if (error.status === 429) { console.error('Rate limited — retry after a delay'); } else { console.error('Analysis failed:', error.message); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try: result = analyze_documents(vault_id, query) print(result['answer']) except casedev.NotFoundError: print('Vault not found — check your vault ID') except casedev.RateLimitError: print('Rate limited — retry after a delay') except casedev.APIError as e: print(f'Analysis failed: {e.message}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, err := analyzeDocuments(ctx, vaultID, query) if err != nil { var apiErr *casedev.Error if errors.As(err, &apiErr) { switch apiErr.StatusCode { case 404: fmt.Println("Vault not found — check your vault ID") case 429: fmt.Println("Rate limited — retry after a delay") default: fmt.Printf("Analysis failed: %s\n", apiErr.Message) } } } ``` > [!TIP] > > Use `temperature: 0` for factual extraction tasks. Try cheaper models like `openai/gpt-6-luna` or `google/gemini-3.1-flash-lite` for simpler analysis. *** ## Next Steps * [Vault Search Reference](/vault/search) — Advanced search methods and filtering * [Chat Completions](/llms/chat-completions) — Streaming, system prompts, and more # Document Intelligence Agent Source: https://docs.case.dev/cookbooks/document-intelligence-agent Build a RAG-powered agent that can store and retrieve information from your documents ## What You'll Build An intelligent agent that can: * **Store documents** in an encrypted vault with automatic OCR and embedding generation * **Answer questions** by retrieving relevant document chunks and synthesizing responses * **Add knowledge** dynamically as users provide new information * **Cite sources** with page numbers and document references ## Why RAG? Large Language Models are powerful, but they can only reason on their training data. RAG solves this by: 1. **Embedding** your documents into a searchable vector space 2. **Retrieving** relevant chunks when a user asks a question 3. **Augmenting** the LLM's context with those chunks 4. **Generating** an accurate, grounded response With Case.dev, you don't need to manage embeddings, vector databases, or chunking strategies — Vaults handle all of this automatically. ## Architecture ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart LR A["User Query"] --> B["Vault Search
(Semantic)"] B --> C["LLM Gateway
+ Context"] C --> H["Grounded Response"] D["New Document"] --> E["Vault Upload"] E --> F["Auto-embed"] F --> G["Ready to query"] G -.indexed chunks.-> B ``` ## Prerequisites * Case.dev API key ([get one here](https://console.case.dev)) * Node.js 18+ or Python 3.9+ * Vercel AI SDK (optional, for streaming UI) ## Project Setup ## Step 1: Install dependencies ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # No installation needed — just set your API key export CASEDEV_API_KEY="sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} brew tap CaseMark/casedev && brew install casedev ``` ```bash title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} npm install casedev ai zod ``` ```bash title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} pip install casedev ``` ```bash title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} go get github.com/CaseMark/casedev-go ``` ## Step 2: Set up environment variables ```bash title="Environment" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} CASEDEV_API_KEY=sk_case_your_api_key ``` ## Step 3: Create a vault for your knowledge base ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/vault \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Knowledge Base", "description": "Document intelligence agent knowledge store" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create \ --name "Knowledge Base" \ --description "Document intelligence agent knowledge store" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Create a vault to store your knowledge base const vault = await client.vault.create({ name: 'Knowledge Base', description: 'Document intelligence agent knowledge store' }); console.log(`Vault created: ${vault.id}`); // Save this ID - you'll need it for queries ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Create a vault to store your knowledge base vault = client.vault.create( name='Knowledge Base', description='Document intelligence agent knowledge store' ) print(f'Vault created: {vault.id}') # Save this ID - you'll need it for queries ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Knowledge Base"), Description: casedev.F("Document intelligence agent knowledge store"), }) fmt.Printf("Vault created: %s\n", vault.ID) ``` ## Core Functions ### 1. Add Documents to Knowledge Base When a user uploads a document or provides information, store it in the vault: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const VAULT_ID = process.env.VAULT_ID; /** * Add a document or text to the knowledge base */ async function addToKnowledgeBase(content: string, metadata?: Record) { // For text content, create a text file const blob = new Blob([content], { type: 'text/plain' }); const filename = `knowledge-${Date.now()}.txt`; // Get upload URL const upload = await client.vault.upload(VAULT_ID, { filename, contentType: 'text/plain', metadata: { source: 'user-input', timestamp: new Date().toISOString(), ...metadata } }); // Upload content await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'text/plain' }, body: content }); // Trigger ingestion (generates embeddings automatically) await client.vault.ingest(VAULT_ID, upload.objectId); return { objectId: upload.objectId, filename }; } /** * Add a file (PDF, Word, image) to the knowledge base */ async function addFileToKnowledgeBase( file: Buffer, filename: string, contentType: string ) { const upload = await client.vault.upload(VAULT_ID, { filename, contentType, metadata: { source: 'file-upload', timestamp: new Date().toISOString() } }); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': contentType }, body: file }); // Ingestion handles OCR (if needed) and embedding generation const job = await client.vault.ingest(VAULT_ID, upload.objectId); return { objectId: upload.objectId, jobId: job.id }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import requests from datetime import datetime import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) VAULT_ID = os.environ['VAULT_ID'] def add_to_knowledge_base(content: str, metadata: dict = None): """Add text content to the knowledge base""" filename = f'knowledge-{int(datetime.now().timestamp())}.txt' # Get upload URL upload = client.vault.upload(VAULT_ID, filename=filename, content_type='text/plain', metadata={ 'source': 'user-input', 'timestamp': datetime.now().isoformat(), **(metadata or {}) } ) # Upload content requests.put(upload.upload_url, data=content.encode('utf-8'), headers={'Content-Type': 'text/plain'} ) # Trigger ingestion (generates embeddings automatically) client.vault.ingest(upload.object_id, id=VAULT_ID) return {'object_id': upload.object_id, 'filename': filename} def add_file_to_knowledge_base(file_path: str, content_type: str): """Add a file (PDF, Word, image) to the knowledge base""" filename = os.path.basename(file_path) upload = client.vault.upload(VAULT_ID, filename=filename, content_type=content_type, metadata={ 'source': 'file-upload', 'timestamp': datetime.now().isoformat() } ) with open(file_path, 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': content_type}) # Ingestion handles OCR (if needed) and embedding generation job = client.vault.ingest(upload.object_id, id=VAULT_ID) return {'object_id': upload.object_id, 'job_id': job.id} ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` ### 2. Retrieve Relevant Information Search the knowledge base for content relevant to a user's question: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search \ --id $VAULT_ID \ --query "search query" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} /** * Find relevant content from the knowledge base */ async function findRelevantContent(query: string, limit: number = 5) { const results = await client.vault.search(VAULT_ID, { query, method: 'hybrid', // Combines semantic + keyword search limit }); // Format results for LLM context return results.chunks.map(chunk => ({ content: chunk.text, source: chunk.filename, page: chunk.page, score: chunk.hybridScore })); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def find_relevant_content(query: str, limit: int = 5): """Find relevant content from the knowledge base""" results = client.vault.search(VAULT_ID, query=query, method='hybrid', # Combines semantic + keyword search top_k=limit ) # Format results for LLM context return [{ 'content': chunk.text, 'source': chunk.filename, 'page': chunk.page, 'score': chunk.hybrid_score } for chunk in results.chunks] ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("search query"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), }) for _, chunk := range results.Chunks { fmt.Println(chunk.Text) } ``` ### 3. Generate Responses with Context Use the LLM Gateway to generate responses grounded in your documents: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search knowledge base casedev vault search --id $VAULT_ID \ --query "What are the key terms?" --method hybrid --limit 10 # Answer with LLM casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Answer using only the provided context. Cite sources."}' \ --message '{role: user, content: "Context: \n\nQuestion: What are the key terms?"}' \ --temperature 0.3 --max-tokens 1000 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} /** * Answer a question using the knowledge base */ async function answerQuestion(question: string) { // 1. Retrieve relevant context const relevantContent = await findRelevantContent(question); if (relevantContent.length === 0) { return { answer: "I don't have any information about that in my knowledge base.", sources: [] }; } // 2. Format context for the LLM const context = relevantContent .map((c, i) => `[${i + 1}] ${c.content} (Source: ${c.source}, Page ${c.page})`) .join('\n\n'); // 3. Generate response with LLM const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `You are a helpful assistant that answers questions based on the provided context. Rules: - Only use information from the provided context - Cite sources using [1], [2], etc. - If the context doesn't contain relevant information, say so - Be concise and accurate` }, { role: 'user', content: `Context:\n${context}\n\nQuestion: ${question}` } ], temperature: 0.3, max_tokens: 1000 }); return { answer: response.choices[0].message.content, sources: relevantContent.map(c => ({ filename: c.source, page: c.page, excerpt: c.content.substring(0, 200) + '...' })) }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def answer_question(question: str): """Answer a question using the knowledge base""" # 1. Retrieve relevant context relevant_content = find_relevant_content(question) if not relevant_content: return { 'answer': "I don't have any information about that in my knowledge base.", 'sources': [] } # 2. Format context for the LLM context = '\n\n'.join([ f"[{i+1}] {c['content']} (Source: {c['source']}, Page {c['page']})" for i, c in enumerate(relevant_content) ]) # 3. Generate response with LLM response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': '''You are a helpful assistant that answers questions based on the provided context. Rules: - Only use information from the provided context - Cite sources using [1], [2], etc. - If the context doesn't contain relevant information, say so - Be concise and accurate''' }, { 'role': 'user', 'content': f'Context:\n{context}\n\nQuestion: {question}' } ], temperature=0.3, max_tokens=1000 ) return { 'answer': response.choices[0].message.content, 'sources': [{ 'filename': c['source'], 'page': c['page'], 'excerpt': c['content'][:200] + '...' } for c in relevant_content] } ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Retrieve relevant context from vault results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F(question), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(10)), }) // Format context var context string for i, c := range results.Chunks { context += fmt.Sprintf("[%d] %s (Source: %s)\n\n", i+1, c.Text, c.Filename) } // 2. Generate answer with LLM resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a helpful assistant. Answer using only the provided context. Cite sources using [1], [2], etc."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Context:\n" + context + "\n\nQuestion: " + question), }, }), Temperature: casedev.F(float64(0.3)), MaxTokens: casedev.F(int64(1000)), }) fmt.Println(resp.Choices[0].Message.Content) ``` ## Building the Agent with Tools For a more sophisticated agent that can decide when to search vs. add knowledge, use tool calling: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Tool-calling agents require programmatic control flow. # Use the Go or TypeScript SDK for agent loops. # For simple questions, pipe vault search into LLM: casedev vault search --id $VAULT_ID --query "What deadlines are coming up?" casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a document intelligence agent."}' \ --message '{role: user, content: "Based on these documents: \n\nWhat deadlines are coming up?"}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import { z } from 'zod'; // Define tools for the agent const tools = { searchKnowledgeBase: { description: 'Search the knowledge base for information relevant to a question', parameters: z.object({ query: z.string().describe('The search query') }), execute: async ({ query }) => { const results = await findRelevantContent(query); return results.length > 0 ? results : 'No relevant information found in knowledge base.'; } }, addToKnowledgeBase: { description: 'Add new information to the knowledge base. Use this when the user provides facts or documents.', parameters: z.object({ content: z.string().describe('The content to add'), topic: z.string().optional().describe('Topic or category') }), execute: async ({ content, topic }) => { const result = await addToKnowledgeBase(content, { topic }); return `Added to knowledge base: ${result.filename}`; } } }; /** * Run the agent with tool support */ async function runAgent(userMessage: string, conversationHistory: any[] = []) { const messages = [ { role: 'system', content: `You are a helpful document intelligence assistant. Your capabilities: 1. Search your knowledge base to answer questions 2. Add new information when users provide it Always search the knowledge base before answering factual questions. If you don't find relevant information, say so honestly. When adding information, confirm what was added.` }, ...conversationHistory, { role: 'user', content: userMessage } ]; // First call - may request tool use let response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages, tools: , } tool_choice: 'auto' }); // Handle tool calls while (response.choices[0].message.tool_calls) { const toolCalls = response.choices[0].message.tool_calls; // Execute each tool const toolResults = await Promise.all( toolCalls.map(async (call) => { const tool = tools[call.function.name]; const args = JSON.parse(call.function.arguments); const result = await tool.execute(args); return { role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) }; }) ); // Continue conversation with tool results messages.push(response.choices[0].message); messages.push(...toolResults); response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages, tools: , } })) }); } return response.choices[0].message.content; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import json # Define tools for the agent tools = [ { 'type': 'function', 'function': { 'name': 'search_knowledge_base', 'description': 'Search the knowledge base for information relevant to a question', 'parameters': { 'type': 'object', 'properties': { 'query': { 'type': 'string', 'description': 'The search query' } }, 'required': ['query'] } } }, { 'type': 'function', 'function': { 'name': 'add_to_knowledge_base', 'description': 'Add new information to the knowledge base', 'parameters': { 'type': 'object', 'properties': { 'content': { 'type': 'string', 'description': 'The content to add' }, 'topic': { 'type': 'string', 'description': 'Topic or category' } }, 'required': ['content'] } } } ] def execute_tool(name: str, args: dict): """Execute a tool by name""" if name == 'search_knowledge_base': results = find_relevant_content(args['query']) return results if results else 'No relevant information found.' elif name == 'add_to_knowledge_base': result = add_to_knowledge_base(args['content'], {'topic': args.get('topic', '')}) return f"Added to knowledge base: {result['filename']}" def run_agent(user_message: str, conversation_history: list = None): """Run the agent with tool support""" messages = [ { 'role': 'system', 'content': '''You are a helpful document intelligence assistant. Your capabilities: 1. Search your knowledge base to answer questions 2. Add new information when users provide it Always search the knowledge base before answering factual questions. If you don't find relevant information, say so honestly.''' }, *(conversation_history or []), {'role': 'user', 'content': user_message} ] # First call - may request tool use response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=messages ) # Handle tool calls while response.choices[0].message.tool_calls: tool_calls = response.choices[0].message.tool_calls # Add assistant message with tool calls messages.append(response.choices[0].message) # Execute each tool and add results for call in tool_calls: args = json.loads(call.function.arguments) result = execute_tool(call.function.name, args) messages.append({ 'role': 'tool', 'tool_call_id': call.id, 'content': json.dumps(result) }) # Continue conversation response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=messages ) return response.choices[0].message.content ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Tool-calling agent loop in Go // 1. Initial request with tools resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a document intelligence agent with access to a knowledge base."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(question), }, }), // Tools defined as JSON schema (searchKnowledgeBase, addToKnowledgeBase) }) // 2. If tool calls returned, execute them and continue // See TypeScript example for full tool-calling loop pattern fmt.Println(resp.Choices[0].Message.Content) ``` ## Integration with Vercel AI SDK For Next.js applications, integrate with the Vercel AI SDK for streaming responses: ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // app/api/chat/route.ts import { streamText, tool } from 'ai'; import { createOpenAICompatible } from '@ai-sdk/openai-compatible'; import { z } from 'zod'; import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); const VAULT_ID = process.env.VAULT_ID; // Set up Case.dev as an OpenAI-compatible provider for Vercel AI SDK const casedev = createOpenAICompatible({ name: 'casedev', baseURL: 'https://api.case.dev/llm/v1', headers: { Authorization: `Bearer ${process.env.CASEDEV_API_KEY}` }, }); export async function POST(req: Request) { const { messages } = await req.json(); const result = streamText({ model: casedev('openai/gpt-6-sol'), system: `You are a document intelligence assistant. Check your knowledge base before answering questions. Only respond using information from tool calls. If no relevant information is found, say "I don't have information about that."`, messages, maxSteps: 5, tools: { searchDocuments: tool({ description: 'Search the document knowledge base', parameters: z.object({ query: z.string().describe('The search query') }), execute: async ({ query }) => { const results = await client.vault.search(VAULT_ID, { query, method: 'hybrid', limit: 5 }); return results.chunks.map(c => ({ text: c.text, source: c.filename, page: c.page })); } }), addDocument: tool({ description: 'Add information to the knowledge base', parameters: z.object({ content: z.string().describe('Content to add') }), execute: async ({ content }) => { const upload = await client.vault.upload(VAULT_ID, { filename: `note-${Date.now()}.txt`, contentType: 'text/plain' }); await fetch(upload.uploadUrl, { method: 'PUT', body: content }); await client.vault.ingest(VAULT_ID, upload.objectId); return 'Added to knowledge base successfully'; } }) } }); return result.toDataStreamResponse(); } ``` ## Example Usage ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Add some knowledge await addToKnowledgeBase( 'The Smith v. Jones case was filed on March 15, 2024. The plaintiff alleges negligence in the maintenance of the property.', { topic: 'case-facts' } ); await addToKnowledgeBase( 'Deposition of John Smith on April 2, 2024: Witness stated he observed water damage on the ceiling two weeks before the incident.', { topic: 'depositions' } ); // Ask questions const result = await answerQuestion('When was the Smith v. Jones case filed?'); console.log(result.answer); // "The Smith v. Jones case was filed on March 15, 2024 [1]." const result2 = await answerQuestion('What did John Smith observe?'); console.log(result2.answer); // "John Smith observed water damage on the ceiling two weeks before the incident [1]." // Using the agent const response = await runAgent('My favorite pizza topping is pepperoni. Remember that.'); console.log(response); // "I've added that to my knowledge base. Your favorite pizza topping is pepperoni." const response2 = await runAgent('What is my favorite pizza topping?'); console.log(response2); // "According to my knowledge base, your favorite pizza topping is pepperoni." ``` ## Best Practices > [!NOTE] > > **Chunking is automatic.** Case.dev Vaults automatically chunk documents into semantic segments optimized for retrieval. You don't need to implement chunking yourself. ### 1. Use hybrid search Combine semantic and keyword search for best results: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search --id $VAULT_ID \ --query "liability insurance coverage limits" \ --method hybrid --limit 10 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const results = await client.vault.search(VAULT_ID, { query: 'liability insurance coverage limits', method: 'hybrid', // Best of both worlds limit: 10 }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results = client.vault.search(VAULT_ID, query='liability insurance coverage limits', method='hybrid', # Best of both worlds top_k=10 ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("liability insurance coverage limits"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), TopK: casedev.F(int64(10)), }) ``` ### 2. Set appropriate temperature Use low temperature for factual retrieval: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "..."}' \ --temperature 0.2 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [...], temperature: 0.2 // More deterministic for factual tasks }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[...], temperature=0.2 # More deterministic for factual tasks ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F(messages), Temperature: casedev.F(float64(0.2)), }) ``` ### 3. Structure your prompts Be explicit about using only provided context: ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const systemPrompt = `You are a legal research assistant. Rules: - ONLY use information from the provided context - If information is not in the context, say "I don't have that information" - Always cite sources using [1], [2], etc. - Never make up or infer facts not explicitly stated`; ``` ### 4. Handle no results gracefully ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const results = await findRelevantContent(query); if (results.length === 0 || results[0].score < 0.5) { return "I couldn't find relevant information in the knowledge base."; } ``` ## Next Steps * Add [file upload support](/vault/upload) for PDFs and images * Implement [conversation memory](https://ai-sdk.dev/docs/ai-sdk-ui/chatbot) with Vercel AI SDK * Add [citations with page links](/vault/search) to your responses * Scale with [batch processing](/cookbooks/discovery-pipeline) for large document sets # Cookbooks Overview Source: https://docs.case.dev/cookbooks/index End-to-end tutorials and production patterns Production-ready examples for building legal AI features. Each cookbook includes full code, architecture decisions, and best practices you can adapt for your app. > [card] [Document Analyzer](/cookbooks/document-analyzer) > > Build a document analysis feature: vault search + LLM analysis + PDF reports. > [card] [Discovery Pipeline](/cookbooks/discovery-pipeline) > > Build document ingestion with OCR, indexing, and search for your users. > [card] [Contract Analysis](/cookbooks/contract-analysis) > > Build clause extraction, risk identification, and contract comparison features. > [card] [Deposition Workflow](/cookbooks/deposition-workflow) > > Build transcription with speaker identification and testimony analysis. > [card] [Document Intelligence Agent](/cookbooks/document-intelligence-agent) > > Build a RAG-powered agent that stores, retrieves, and reasons over your documents. ## What's in a cookbook? Each cookbook includes: * **Complete source code** — Copy-paste ready for your project * **Architecture diagram** — How the pieces fit together * **Step-by-step guide** — Detailed integration walkthrough * **Production tips** — Error handling and rate limits ## Request a cookbook Building something specific? [Let us know](mailto:support@casemark.com) what integration patterns would help and we'll prioritize them. # Event Types Source: https://docs.case.dev/events/event-types Subscribable Case.dev webhook events generated from the router event catalog Case.dev exposes the following customer-facing events through webhook endpoints. This page is generated from the router event catalog and typed payload contracts so it stays aligned with the API. > [!NOTE] > > Stable events keep their event name and payload shape frozen except for additive fields. Beta > events may change during their early access window. Generated from `apps/router/server/utils/webhooks/catalog.ts`. | Event | Stability | Scope | Resource | Description | | - | - | - | - | - | | `vault.upload.initiated` | stable | `vault` | `vault` | A vault object upload was initiated. | | `vault.upload.completed` | stable | `vault` | `vault` | A vault object upload finished successfully. | | `vault.upload.failed` | stable | `vault` | `vault` | A vault object upload failed. | | `vault.object.append.started` | stable | `vault` | `vault` | Vault object append started. | | `vault.object.append.completed` | stable | `vault` | `vault` | Vault object append finished successfully. | | `vault.object.append.failed` | stable | `vault` | `vault` | Vault object append failed. | | `vault.object.merge.started` | stable | `vault` | `vault` | Searchable vault object merge started. | | `vault.object.merge.completed` | stable | `vault` | `vault` | Searchable vault object merge finished successfully. | | `vault.object.merge.failed` | stable | `vault` | `vault` | Searchable vault object merge failed. | | `vault.assembly.completed` | beta | `vault` | `vault` | A PDF assembly finished and its volumes are available. | | `vault.assembly.failed` | beta | `vault` | `vault` | A PDF assembly failed. Its reserved volumes are marked failed. | | `vault.object.translation.started` | beta | `vault` | `vault` | Vault object translation started. | | `vault.object.translation.completed` | beta | `vault` | `vault` | Vault object translation finished successfully. | | `vault.object.translation.failed` | beta | `vault` | `vault` | Vault object translation failed. | | `vault.ingest.started` | stable | `vault` | `vault` | Vault object ingest started. | | `vault.ingest.completed` | stable | `vault` | `vault` | Vault object ingest finished successfully. | | `vault.ingest.failed` | stable | `vault` | `vault` | Vault object ingest failed. | | `vault.ingest.page_count.retrieved` | stable | `vault` | `vault` | Vault object page count was derived during ingest. | | `ocr.job.created` | stable | `vision_ocr` | - | An OCR job was enqueued. | | `ocr.job.completed` | stable | `vision_ocr` | - | An OCR job finished successfully. | | `ocr.job.failed` | stable | `vision_ocr` | - | An OCR job failed. | | `voice.transcription.created` | stable | `transcription` | - | A transcription job was created. | | `voice.transcription.reused` | stable | `transcription` | - | A completed transcription job was reused from cache. | | `voice.transcription.audio_derivative.started` | stable | `transcription` | - | Audio derivative creation started for a large Vault video. | | `voice.transcription.audio_derivative.completed` | stable | `transcription` | - | Audio derivative creation completed for a large Vault video. | | `voice.transcription.audio_derivative.failed` | stable | `transcription` | - | Audio derivative creation failed for a large Vault video. | | `voice.transcription.completed` | stable | `transcription` | - | A transcription job finished successfully. | | `voice.transcription.failed` | stable | `transcription` | - | A transcription job failed. | | `voice.transcription.deleted` | stable | `transcription` | - | A transcription job was deleted. | | `linc.session.ready` | beta | `agent` | - | A native Linc session finished provisioning and is ready for turns. | | `linc.session.provisioning_failed` | beta | `agent` | - | A native Linc session failed before the runtime became ready. | | `linc.session.ended` | beta | `agent` | - | A native Linc session reached a terminal state (user\_deleted, completed, failed, cancelled, runtime\_crashed, timed\_out). | | `linc.session.scope.updated` | beta | `agent` | - | A persistent native Linc conversation resumed with a newly authorized vault and object scope. | | `linc.session.turn.completed` | beta | `agent` | - | A native Linc session completed an assistant turn. | | `linc.session.turn.failed` | beta | `agent` | - | A native Linc assistant turn failed after retries were exhausted or the runtime reported a terminal turn error. | | `matter.content_purge.requested` | beta | `legal` | `matter` | A scoped content purge was requested. | | `matter.content_purge.started` | beta | `legal` | `matter` | A scoped content purge attempt started. | | `matter.content_purge.failed` | beta | `legal` | `matter` | A scoped content purge attempt failed and can be retried. | | `matter.content_purge.completed` | beta | `legal` | `matter` | A scoped content purge completed without deleting its Matter or Vault. | | `matter.created` | beta | `legal` | `matter` | A matter was created. | | `matter.updated` | beta | `legal` | `matter` | A matter was updated. | | `matter.purge.requested` | beta | `legal` | `matter` | A durable Matter purge was requested. | | `matter.purge.started` | beta | `legal` | `matter` | A durable Matter purge attempt started. | | `matter.purge.failed` | beta | `legal` | `matter` | A durable Matter purge attempt failed and can be retried. | | `matter.purge.completed` | beta | `legal` | `matter` | A durable Matter purge completed. | | `work_item.execution.completed` | beta | `legal` | `matter` | A matter work item finished execution. | | `work_item.execution.failed` | beta | `legal` | `matter` | A matter work item execution failed. | | `billing.charge.succeeded` | stable | `webhooks` | - | A billing charge succeeded. | | `billing.charge.failed` | stable | `webhooks` | - | A billing charge failed. | | `balance.changed` | stable | `webhooks` | - | The organization credit balance changed. | | `compute.run.completed` | stable | `compute` | - | A compute function run completed successfully. | | `compute.run.failed` | stable | `compute` | - | A compute function run failed. | | `deployment.succeeded` | stable | `webhooks` | - | A deployment succeeded. | | `deployment.failed` | stable | `webhooks` | - | A deployment failed. | | `webhook.endpoint.auto_disabled` | stable | `webhooks` | - | A webhook endpoint was automatically disabled after too many consecutive delivery failures. Subscribe to this to be notified when a downstream customer endpoint starts failing. | | `connection.reauth_required` | beta | `connectors` | - | A connector connection lost provider authorization and needs reconnecting. | | `connection.revoked` | beta | `connectors` | - | A connector connection was unlinked and its provider tokens revoked. | | `link.orphaned` | beta | `connectors` | - | A connector link lost its provider folder, provider access, or vault. | | `run.completed` | beta | `connectors` | - | A connector transfer run finished (possibly with per-file errors). | | `run.progress` | beta | `connectors` | - | A running connector import made progress (sent at most every few seconds). | | `run.failed` | beta | `connectors` | - | A connector transfer run failed before completing. | | `link.objects_changed` | beta | `connectors` | - | A connector run changed the set of synced objects behind a link. | | `voice.call.ended` | beta | `voice` | - | A phone call leg ended, with its disposition and duration. | | `voice.call.analyzed` | beta | `voice` | - | Post-call analysis is ready: summary, outcome, next steps, and extraction. | ## vault.upload.initiated A vault object upload was initiated. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `filename` | `string` | Yes | Original filename provided by the uploader. | | `mimeType` | `string` | No | MIME type of the uploaded file, if detected. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.upload.initiated", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "filename": "filename_value", "mimeType": "mimeType_value" } } ``` ## vault.upload.completed A vault object upload finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `filename` | `string` | Yes | - | | `mimeType` | `string` | Yes | - | | `sizeBytes` | `number` | Yes | Size of the uploaded file in bytes. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.upload.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "filename": "filename_value", "mimeType": "mimeType_value", "sizeBytes": 42 } } ``` ## vault.upload.failed A vault object upload failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `error` | `string` | Yes | Human-readable error description. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.upload.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "error": "Processing failed" } } ``` ## vault.object.append.started Vault object append started. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `appendObjectIds` | `string[]` | Yes | Vault object IDs whose pages will be appended onto the target object, in order. | | `appendedPageStart` | `number` | No | First 1-indexed page added by this append operation. | | `workflowId` | `string` | No | Stable identifier for an asynchronous append operation. | | `clientReference` | `string` | No | Caller-provided correlation value. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.append.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "appendObjectIds": ["appendObjectId_123"], "appendedPageStart": 42, "workflowId": "workflow_123", "clientReference": "clientReference_value" } } ``` ## vault.object.append.completed Vault object append finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `appendObjectIds` | `string[]` | Yes | Vault object IDs whose pages will be appended onto the target object, in order. | | `appendedPageStart` | `number` | No | First 1-indexed page added by this append operation. | | `workflowId` | `string` | No | Stable identifier for an asynchronous append operation. | | `clientReference` | `string` | No | Caller-provided correlation value. | | `sizeBytes` | `number` | Yes | Size of the updated target object in bytes. | | `pageCount` | `number` | Yes | Page count of the updated target object. | | `appendedPageEnd` | `number` | No | Last 1-indexed page added by this append operation. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.append.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "appendObjectIds": ["appendObjectId_123"], "appendedPageStart": 42, "workflowId": "workflow_123", "clientReference": "clientReference_value", "sizeBytes": 42, "pageCount": 42, "appendedPageEnd": 42 } } ``` ## vault.object.append.failed Vault object append failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `appendObjectIds` | `string[]` | Yes | Vault object IDs whose pages will be appended onto the target object, in order. | | `appendedPageStart` | `number` | No | First 1-indexed page added by this append operation. | | `workflowId` | `string` | No | Stable identifier for an asynchronous append operation. | | `clientReference` | `string` | No | Caller-provided correlation value. | | `error` | `string` | Yes | Human-readable error description. | | `errorCode` | `string` | No | Bounded failure classification; never a raw worker error. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.append.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "appendObjectIds": ["appendObjectId_123"], "appendedPageStart": 42, "workflowId": "workflow_123", "clientReference": "clientReference_value", "error": "Processing failed", "errorCode": "errorCode_value" } } ``` ## vault.object.merge.started Searchable vault object merge started. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectIds` | `string[]` | Yes | - | | `clientReference` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.merge.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectIds": ["sourceObjectId_123"], "clientReference": "clientReference_value" } } ``` ## vault.object.merge.completed Searchable vault object merge finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectIds` | `string[]` | Yes | - | | `clientReference` | `string` | No | - | | `sizeBytes` | `number` | Yes | - | | `pageCount` | `number` | Yes | - | | `filename` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.merge.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectIds": ["sourceObjectId_123"], "clientReference": "clientReference_value", "sizeBytes": 42, "pageCount": 42, "filename": "filename_value" } } ``` ## vault.object.merge.failed Searchable vault object merge failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectIds` | `string[]` | Yes | - | | `clientReference` | `string` | No | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.merge.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectIds": ["sourceObjectId_123"], "clientReference": "clientReference_value", "error": "Processing failed" } } ``` ## vault.assembly.completed A PDF assembly finished and its volumes are available. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | - | | `assemblyId` | `string` | Yes | - | | `volumeObjectIds` | `string[]` | Yes | Output volume objects, in manifest order. | | `outputPageCount` | `number` | Yes | - | | `clientReference` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.assembly.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "assemblyId": "assembly_123", "volumeObjectIds": ["volumeObjectId_123"], "outputPageCount": 42, "clientReference": "clientReference_value" } } ``` ## vault.assembly.failed A PDF assembly failed. Its reserved volumes are marked failed. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | - | | `assemblyId` | `string` | Yes | - | | `volumeObjectIds` | `string[]` | Yes | Volume objects reserved for the output, now marked failed. | | `errorCode` | `string` | Yes | Bounded failure classification, such as SOURCE\_ENCRYPTED. | | `error` | `string` | Yes | - | | `retryable` | `boolean` | Yes | - | | `clientReference` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.assembly.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "assemblyId": "assembly_123", "volumeObjectIds": ["volumeObjectId_123"], "errorCode": "errorCode_value", "error": "Processing failed", "retryable": true, "clientReference": "clientReference_value" } } ``` ## vault.object.translation.started Vault object translation started. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectId` | `string` | Yes | - | | `engine` | `TranslationEngine` | Yes | - | | `sourceLanguage` | `string \| null` | No | - | | `targetLanguage` | `string` | Yes | - | | `model` | `TranslationModel` | Yes | - | | `pageCount` | `number` | No | - | | `characterCount` | `number` | No | - | | `cost` | `number` | No | - | | `currency` | `'USD'` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.translation.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectId": "sourceObject_123", "engine": "engine_value", "sourceLanguage": "sourceLanguage_value", "targetLanguage": "targetLanguage_value", "model": "model_value", "pageCount": 42, "characterCount": 42, "cost": 42, "currency": "usd" } } ``` ## vault.object.translation.completed Vault object translation finished successfully. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectId` | `string` | Yes | - | | `engine` | `TranslationEngine` | Yes | - | | `sourceLanguage` | `string` | Yes | - | | `targetLanguage` | `string` | Yes | - | | `model` | `TranslationModel` | Yes | - | | `pageCount` | `number` | No | - | | `characterCount` | `number` | No | - | | `cost` | `number` | No | - | | `currency` | `'USD'` | No | - | | `filename` | `string` | Yes | - | | `contentType` | `'application/pdf' \| 'text/plain'` | Yes | - | | `sizeBytes` | `number` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.translation.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectId": "sourceObject_123", "engine": "engine_value", "sourceLanguage": "sourceLanguage_value", "targetLanguage": "targetLanguage_value", "model": "model_value", "pageCount": 42, "characterCount": 42, "cost": 42, "currency": "usd", "filename": "filename_value", "contentType": "contentType_value", "sizeBytes": 42 } } ``` ## vault.object.translation.failed Vault object translation failed. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `sourceObjectId` | `string` | Yes | - | | `engine` | `TranslationEngine` | Yes | - | | `targetLanguage` | `string` | Yes | - | | `model` | `TranslationModel` | Yes | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.object.translation.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "sourceObjectId": "sourceObject_123", "engine": "engine_value", "targetLanguage": "targetLanguage_value", "model": "model_value", "error": "Processing failed" } } ``` ## vault.ingest.started Vault object ingest started. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `stage` | `string` | No | Pipeline stage that began (e.g. 'extraction', 'chunking'). | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.ingest.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "stage": "stage_value" } } ``` ## vault.ingest.completed Vault object ingest finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `durationMs` | `number` | Yes | Total ingest duration in milliseconds. | | `chunkCount` | `number` | No | Number of chunks produced. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.ingest.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "durationMs": 1284, "chunkCount": 42 } } ``` ## vault.ingest.failed Vault object ingest failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `error` | `string` | Yes | Human-readable error description. | | `stage` | `string` | No | Pipeline stage that failed, if applicable. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.ingest.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "error": "Processing failed", "stage": "stage_value" } } ``` ## vault.ingest.page\_count.retrieved Vault object page count was derived during ingest. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vault` | | Resource scope | `vault` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `vaultId` | `string` | Yes | The vault this event pertains to. | | `objectId` | `string` | Yes | The object within the vault. | | `filename` | `string` | Yes | Original filename for the vault object. | | `mimeType` | `string` | No | MIME type of the vault object, if detected. | | `pageCount` | `number` | Yes | Number of pages derived for this vault object. | | `documentKind` | `string` | Yes | File classification used by the ingest pipeline (e.g. 'pdf', 'docx'). | | `source` | `string` | Yes | Extractor path that produced the page count. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.ingest.page_count.retrieved", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "object_123", "filename": "filename_value", "mimeType": "mimeType_value", "pageCount": 42, "documentKind": "documentKind_value", "source": "source_value" } } ``` ## ocr.job.created An OCR job was enqueued. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vision_ocr` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | OCR job identifier. | | `objectId` | `string` | Yes | The vault object being processed. | | `vaultId` | `string` | Yes | - | | `pageCount` | `number` | No | Number of pages queued for OCR. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "ocr.job.created", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "objectId": "object_123", "vaultId": "vault_123", "pageCount": 42 } } ``` ## ocr.job.completed An OCR job finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vision_ocr` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | OCR job identifier. | | `objectId` | `string` | Yes | The vault object being processed. | | `vaultId` | `string` | Yes | - | | `durationMs` | `number` | Yes | Processing duration in milliseconds. | | `pageCount` | `number` | Yes | Number of pages processed. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "ocr.job.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "objectId": "object_123", "vaultId": "vault_123", "durationMs": 1284, "pageCount": 42 } } ``` ## ocr.job.failed An OCR job failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `vision_ocr` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | OCR job identifier. | | `objectId` | `string` | Yes | The vault object being processed. | | `vaultId` | `string` | Yes | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "ocr.job.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "objectId": "object_123", "vaultId": "vault_123", "error": "Processing failed" } } ``` ## voice.transcription.created A transcription job was created. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | No | Vault that owns the source object, when the transcription came from a vault workflow. | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | No | Actual media object submitted to the speech provider. | | `objectId` | `string` | No | Source vault object for vault-backed jobs. | | `format` | `string` | No | Requested transcript output format. | | `mode` | `'vault' \| 'direct'` | Yes | Transcription mode used by the request. | | `status` | `string` | No | Provider status returned at job creation time. | | `speakerLabels` | `boolean` | No | - | | `autoHighlights` | `boolean` | No | - | | `contentSafety` | `boolean` | No | - | | `languageDetection` | `boolean` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.created", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "objectId": "object_123", "format": "format_value", "mode": "vault", "status": "active", "speakerLabels": true, "autoHighlights": true, "contentSafety": true, "languageDetection": true } } ``` ## voice.transcription.reused A completed transcription job was reused from cache. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | No | Vault that owns the source object, when the transcription came from a vault workflow. | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | No | Actual media object submitted to the speech provider. | | `objectId` | `string` | Yes | - | | `format` | `string` | No | - | | `mode` | `'vault'` | Yes | - | | `from_cache` | `true` | Yes | - | | `options_hash` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.reused", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "objectId": "object_123", "format": "format_value", "mode": "vault", "from_cache": true, "options_hash": "options_hash_value" } } ``` ## voice.transcription.audio\_derivative.started Audio derivative creation started for a large Vault video. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | Yes | - | | `sourceObjectId` | `string` | Yes | - | | `error` | `string` | No | - | | `sourceDurationMs` | `number` | No | - | | `sourceAudioDurationMs` | `number` | No | - | | `sourceAudioStartMs` | `number` | No | - | | `timelineOffsetMs` | `number` | No | - | | `derivativeDurationMs` | `number` | No | - | | `durationDriftMs` | `number` | No | - | | `audioStreamIndex` | `number` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.audio_derivative.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "sourceObjectId": "sourceObject_123", "error": "Processing failed", "sourceDurationMs": 1284, "sourceAudioDurationMs": 1284, "sourceAudioStartMs": 1284, "timelineOffsetMs": 1284, "derivativeDurationMs": 1284, "durationDriftMs": 1284, "audioStreamIndex": 42 } } ``` ## voice.transcription.audio\_derivative.completed Audio derivative creation completed for a large Vault video. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | Yes | - | | `sourceObjectId` | `string` | Yes | - | | `error` | `string` | No | - | | `sourceDurationMs` | `number` | No | - | | `sourceAudioDurationMs` | `number` | No | - | | `sourceAudioStartMs` | `number` | No | - | | `timelineOffsetMs` | `number` | No | - | | `derivativeDurationMs` | `number` | No | - | | `durationDriftMs` | `number` | No | - | | `audioStreamIndex` | `number` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.audio_derivative.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "sourceObjectId": "sourceObject_123", "error": "Processing failed", "sourceDurationMs": 1284, "sourceAudioDurationMs": 1284, "sourceAudioStartMs": 1284, "timelineOffsetMs": 1284, "derivativeDurationMs": 1284, "durationDriftMs": 1284, "audioStreamIndex": 42 } } ``` ## voice.transcription.audio\_derivative.failed Audio derivative creation failed for a large Vault video. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | Yes | - | | `sourceObjectId` | `string` | Yes | - | | `error` | `string` | No | - | | `sourceDurationMs` | `number` | No | - | | `sourceAudioDurationMs` | `number` | No | - | | `sourceAudioStartMs` | `number` | No | - | | `timelineOffsetMs` | `number` | No | - | | `derivativeDurationMs` | `number` | No | - | | `durationDriftMs` | `number` | No | - | | `audioStreamIndex` | `number` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.audio_derivative.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "sourceObjectId": "sourceObject_123", "error": "Processing failed", "sourceDurationMs": 1284, "sourceAudioDurationMs": 1284, "sourceAudioStartMs": 1284, "timelineOffsetMs": 1284, "derivativeDurationMs": 1284, "durationDriftMs": 1284, "audioStreamIndex": 42 } } ``` ## voice.transcription.completed A transcription job finished successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | No | Vault that owns the source object, when the transcription came from a vault workflow. | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | No | Actual media object submitted to the speech provider. | | `sourceObjectId` | `string` | Yes | - | | `resultObjectId` | `string` | Yes | - | | `audioDurationSeconds` | `number` | No | - | | `wordCount` | `number` | Yes | - | | `confidence` | `number` | No | - | | `textLength` | `number` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "sourceObjectId": "sourceObject_123", "resultObjectId": "resultObject_123", "audioDurationSeconds": 42, "wordCount": 42, "confidence": 42, "textLength": 42 } } ``` ## voice.transcription.failed A transcription job failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | No | Vault that owns the source object, when the transcription came from a vault workflow. | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | No | Actual media object submitted to the speech provider. | | `sourceObjectId` | `string` | No | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "sourceObjectId": "sourceObject_123", "error": "Processing failed" } } ``` ## voice.transcription.deleted A transcription job was deleted. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `transcription` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `jobId` | `string` | Yes | - | | `vaultId` | `string` | No | Vault that owns the source object, when the transcription came from a vault workflow. | | `assemblyaiId` | `string` | No | AssemblyAI transcript identifier. | | `inputObjectId` | `string` | No | Actual media object submitted to the speech provider. | | `transcriptId` | `string` | Yes | - | | `mode` | `'vault' \| 'direct'` | Yes | - | | `providerDeleted` | `boolean` | Yes | - | | `providerAlreadyDeleted` | `boolean` | Yes | - | | `providerDeleteFailed` | `boolean` | Yes | - | | `providerErrorStatusCode` | `number` | No | - | | `inputObjectDeleted` | `boolean` | No | - | | `resultObjectDeleted` | `boolean` | Yes | - | | `localRecordDeleted` | `boolean` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.transcription.deleted", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "jobId": "job_123", "vaultId": "vault_123", "assemblyaiId": "assemblyai_123", "inputObjectId": "inputObject_123", "transcriptId": "transcript_123", "mode": "vault", "providerDeleted": true, "providerAlreadyDeleted": true, "providerDeleteFailed": true, "providerErrorStatusCode": 42, "inputObjectDeleted": true, "resultObjectDeleted": true, "localRecordDeleted": true } } ``` ## linc.session.ready A native Linc session finished provisioning and is ready for turns. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `title` | `string \| null` | No | - | | `organizationId` | `string` | Yes | - | | `status` | `'active'` | Yes | - | | `nativeSessionId` | `string \| null` | No | - | | `readyAt` | `string` | Yes | - | | `replayUrl` | `string \| null` | No | - | | `vaultIds` | `string[] \| null` | No | - | | `vaultScopes` | `Array<{vaultId: string; objectIds: string[]}> \| null` | No | - | | `objectIds` | `string[] \| null` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.ready", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "title": "title_value", "organizationId": "organization_123", "status": "active", "nativeSessionId": "nativeSession_123", "readyAt": "readyAt_value", "replayUrl": "replayUrl_value", "vaultIds": ["vaultId_123"], "vaultScopes": [{ "vaultId": "vault_123", "objectIds": ["object_123"] }], "objectIds": ["objectId_123"] } } ``` ## linc.session.provisioning\_failed A native Linc session failed before the runtime became ready. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `title` | `string \| null` | No | - | | `organizationId` | `string` | Yes | - | | `status` | `'failed'` | Yes | - | | `failureCode` | `string` | Yes | - | | `errorMessage` | `string` | Yes | - | | `failedAt` | `string` | Yes | - | | `provisioningMs` | `number \| null` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.provisioning_failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "title": "title_value", "organizationId": "organization_123", "status": "failed", "failureCode": "failureCode_value", "errorMessage": "errorMessage_value", "failedAt": "failedAt_value", "provisioningMs": 1284 } } ``` ## linc.session.ended A native Linc session reached a terminal state (user\_deleted, completed, failed, cancelled, runtime\_crashed, timed\_out). | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `title` | `string \| null` | No | - | | `organizationId` | `string \| null` | No | - | | `terminalStatus` | `'done' \| 'failed' \| 'cancelled'` | No | - | | `reason` | `LincSessionEndedReason` | Yes | - | | `error` | `string \| null` | No | - | | `endedAt` | `string` | Yes | - | | `lastEventSeq` | `number` | Yes | - | | `replayUrl` | `string \| null` | No | - | | `resultMetadata` | `object \| null` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.ended", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "title": "title_value", "organizationId": "organization_123", "terminalStatus": "terminalStatus_value", "reason": "reason_value", "error": "Processing failed", "endedAt": "endedAt_value", "lastEventSeq": 42, "replayUrl": "replayUrl_value", "resultMetadata": {} } } ``` ## linc.session.scope.updated A persistent native Linc conversation resumed with a newly authorized vault and object scope. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `organizationId` | `string` | Yes | - | | `workspaceId` | `string` | Yes | - | | `vaultIds` | `string[] \| null` | No | - | | `vaultScopes` | `Array<{vaultId: string; objectIds: string[]}> \| null` | No | - | | `objectIds` | `string[] \| null` | No | - | | `matterIds` | `string[] \| null` | No | - | | `updatedAt` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.scope.updated", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "organizationId": "organization_123", "workspaceId": "workspace_123", "vaultIds": ["vaultId_123"], "vaultScopes": [{ "vaultId": "vault_123", "objectIds": ["object_123"] }], "objectIds": ["objectId_123"], "matterIds": ["matterId_123"], "updatedAt": "updatedAt_value" } } ``` ## linc.session.turn.completed A native Linc session completed an assistant turn. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `title` | `string \| null` | No | - | | `organizationId` | `string \| null` | No | - | | `turnId` | `string` | Yes | - | | `turnSeq` | `number` | Yes | - | | `message` | `object` | Yes | - | | `usage` | `unknown` | No | - | | `finishReason` | `string \| null` | No | - | | `completedAt` | `string` | Yes | - | | `lastEventSeq` | `number` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.turn.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "title": "title_value", "organizationId": "organization_123", "turnId": "turn_123", "turnSeq": 42, "message": {}, "usage": { "inputTokens": 123, "outputTokens": 456 }, "finishReason": "finishReason_value", "completedAt": "completedAt_value", "lastEventSeq": 42 } } ``` ## linc.session.turn.failed A native Linc assistant turn failed after retries were exhausted or the runtime reported a terminal turn error. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `agent` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `sessionId` | `string` | Yes | - | | `runtimeProvider` | `string` | Yes | - | | `runtimeId` | `string \| null` | No | - | | `model` | `string \| null` | No | - | | `organizationId` | `string \| null` | No | Owning organization. | | `commandId` | `string \| null` | No | Runtime command identifier, when available. | | `turnId` | `string` | Yes | Stable turn identifier. | | `turnSeq` | `number` | Yes | Sequence of the terminal failed-turn frame. | | `finalAttempt` | `number` | Yes | Final retry attempt number. | | `finalError` | `string` | Yes | Content-safe terminal error classification. | | `failedAt` | `string` | Yes | ISO-8601 failure timestamp. | | `lastEventSeq` | `number` | Yes | Last known session event sequence. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "linc.session.turn.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "sessionId": "session_123", "runtimeProvider": "runtimeProvider_value", "runtimeId": "runtime_123", "model": "model_value", "organizationId": "organization_123", "commandId": "command_123", "turnId": "turn_123", "turnSeq": 42, "finalAttempt": 42, "finalError": "finalError_value", "failedAt": "failedAt_value", "lastEventSeq": 42 } } ``` ## matter.content\_purge.requested A scoped content purge was requested. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `requestId` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.content_purge.requested", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "requestId": "request_123" } } ``` ## matter.content\_purge.started A scoped content purge attempt started. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `requestId` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.content_purge.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "requestId": "request_123" } } ``` ## matter.content\_purge.failed A scoped content purge attempt failed and can be retried. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `requestId` | `string` | Yes | - | | `failureCode` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.content_purge.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "requestId": "request_123", "failureCode": "failureCode_value" } } ``` ## matter.content\_purge.completed A scoped content purge completed without deleting its Matter or Vault. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `requestId` | `string` | Yes | - | | `counts` | `{objects: number; transcriptions: number; sessions: number; workItems: number}` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.content_purge.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "requestId": "request_123", "counts": {} } } ``` ## matter.created A matter was created. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `title` | `string` | No | Human-readable matter title. | | `status` | `string` | Yes | Matter status at creation time. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.created", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "title": "title_value", "status": "active" } } ``` ## matter.updated A matter was updated. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `object` | `object` | Yes | Current state of the matter. | | `previous_attributes` | `object` | No | Only-changed fields with their previous values. Present when the emitter supports change tracking. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.updated", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "object": {}, "previous_attributes": {} } } ``` ## matter.purge.requested A durable Matter purge was requested. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.purge.requested", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123" } } ``` ## matter.purge.started A durable Matter purge attempt started. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.purge.started", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123" } } ``` ## matter.purge.failed A durable Matter purge attempt failed and can be retried. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `failureCode` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.purge.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "failureCode": "failureCode_value" } } ``` ## matter.purge.completed A durable Matter purge completed. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `purgeId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `attempt` | `number` | Yes | - | | `workflowId` | `string` | No | - | | `counts` | `{objects: number transcriptions: number sessions: number chats: number}` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "matter.purge.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "purgeId": "purge_123", "vaultId": "vault_123", "attempt": 42, "workflowId": "workflow_123", "counts": {} } } ``` ## work\_item.execution.completed A matter work item finished execution. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `workItemId` | `string` | Yes | - | | `durationMs` | `number` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "work_item.execution.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "workItemId": "workItem_123", "durationMs": 1284 } } ``` ## work\_item.execution.failed A matter work item execution failed. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `legal` | | Resource scope | `matter` | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `matterId` | `string` | Yes | - | | `workItemId` | `string` | Yes | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "work_item.execution.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "matterId": "matter_123", "workItemId": "workItem_123", "error": "Processing failed" } } ``` ## billing.charge.succeeded A billing charge succeeded. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `chargeId` | `string` | Yes | Stripe charge or invoice ID. | | `amountCents` | `number` | Yes | Amount in cents. | | `currency` | `string` | Yes | ISO 4217 currency code. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "billing.charge.succeeded", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "chargeId": "charge_123", "amountCents": 2500, "currency": "usd" } } ``` ## billing.charge.failed A billing charge failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `chargeId` | `string` | Yes | - | | `amountCents` | `number` | Yes | - | | `currency` | `string` | Yes | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "billing.charge.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "chargeId": "charge_123", "amountCents": 2500, "currency": "usd", "error": "Processing failed" } } ``` ## balance.changed The organization credit balance changed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `balanceCents` | `number` | Yes | New credit balance in cents. | | `deltaCents` | `number` | Yes | Change amount (positive = credit added, negative = deducted). | | `reason` | `string` | No | Reason for the change (e.g. 'charge', 'top\_up', 'promo'). | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "balance.changed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "balanceCents": 2500, "deltaCents": 2500, "reason": "reason_value" } } ``` ## compute.run.completed A compute function run completed successfully. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `compute` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `runId` | `string` | Yes | - | | `functionId` | `string` | Yes | - | | `durationMs` | `number` | Yes | - | | `exitCode` | `number` | No | Exit code of the compute function. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "compute.run.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "runId": "run_123", "functionId": "function_123", "durationMs": 1284, "exitCode": 42 } } ``` ## compute.run.failed A compute function run failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `compute` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `runId` | `string` | Yes | - | | `functionId` | `string` | Yes | - | | `error` | `string` | Yes | - | | `exitCode` | `number` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "compute.run.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "runId": "run_123", "functionId": "function_123", "error": "Processing failed", "exitCode": 42 } } ``` ## deployment.succeeded A deployment succeeded. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `deploymentId` | `string` | Yes | - | | `appName` | `string` | No | Application or project name. | | `url` | `string` | No | URL of the deployed application. | | `durationMs` | `number` | No | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "deployment.succeeded", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "deploymentId": "deployment_123", "appName": "appName_value", "url": "url_value", "durationMs": 1284 } } ``` ## deployment.failed A deployment failed. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `deploymentId` | `string` | Yes | - | | `appName` | `string` | No | Application or project name. | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "deployment.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "deploymentId": "deployment_123", "appName": "appName_value", "error": "Processing failed" } } ``` ## webhook.endpoint.auto\_disabled A webhook endpoint was automatically disabled after too many consecutive delivery failures. Subscribe to this to be notified when a downstream customer endpoint starts failing. | Property | Value | | - | - | | Stability | `stable` | | Required scope | `webhooks` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `endpointId` | `string` | Yes | The endpoint that was disabled. | | `url` | `string` | Yes | URL of the disabled endpoint. | | `consecutiveFailures` | `number` | Yes | Number of consecutive failures that triggered the disable. | | `lastFailureAt` | `string` | Yes | Timestamp of the last failed delivery attempt. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "webhook.endpoint.auto_disabled", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "endpointId": "endpoint_123", "url": "url_value", "consecutiveFailures": 42, "lastFailureAt": "lastFailureAt_value" } } ``` ## connection.reauth\_required A connector connection lost provider authorization and needs reconnecting. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `connectionId` | `string` | Yes | - | | `provider` | `string` | Yes | - | | `reason` | `string` | No | Why reauth is needed (e.g. 'invalid\_grant'). | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "connection.reauth_required", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "connectionId": "connection_123", "provider": "provider_value", "reason": "reason_value" } } ``` ## connection.revoked A connector connection was unlinked and its provider tokens revoked. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `connectionId` | `string` | Yes | - | | `provider` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "connection.revoked", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "connectionId": "connection_123", "provider": "provider_value" } } ``` ## link.orphaned A connector link lost its provider folder, provider access, or vault. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `linkId` | `string` | Yes | - | | `connectionId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `direction` | `'import' \| 'export'` | Yes | - | | `orphanReason` | `'provider_folder_gone' \| 'provider_access_lost' \| 'vault_deleted'` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "link.orphaned", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "linkId": "link_123", "connectionId": "connection_123", "vaultId": "vault_123", "direction": "direction_value", "orphanReason": "orphanReason_value" } } ``` ## run.completed A connector transfer run finished (possibly with per-file errors). | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `runId` | `string` | Yes | - | | `linkId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `direction` | `'import' \| 'export'` | Yes | - | | `status` | `string` | Yes | 'completed' or 'completed\_with\_errors'. | | `stats` | `{listed: number added: number updated: number deleted: number skipped: number failed: number bytes: number}` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "run.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "runId": "run_123", "linkId": "link_123", "vaultId": "vault_123", "direction": "direction_value", "status": "active", "stats": {} } } ``` ## run.progress A running connector import made progress (sent at most every few seconds). | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `runId` | `string` | Yes | - | | `linkId` | `string` | Yes | - | | `connectionId` | `string` | Yes | - | | `provider` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `direction` | `'import'` | Yes | - | | `stage` | `'discovering' \| 'copying'` | Yes | 'discovering' while the provider folder is listed, then 'copying'. Completion is `run.completed`. | | `sequence` | `number` | Yes | Increases with every event for a run (milliseconds since epoch); ignore one lower than the last seen. | | `found` | `number` | No | Files found so far while discovering; absent for runs that list in one call. | | `stats` | `RunCompletedPayload['stats']` | Yes | - | | `recentPaths` | `string[]` | Yes | Paths, relative to the linked folder, of files copied since the previous event (at most 20). | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "run.progress", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "runId": "run_123", "linkId": "link_123", "connectionId": "connection_123", "provider": "provider_value", "vaultId": "vault_123", "direction": "direction_value", "stage": "stage_value", "sequence": 42, "found": 42, "stats": "stats_value", "recentPaths": ["recentPath_123"] } } ``` ## run.failed A connector transfer run failed before completing. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `runId` | `string` | Yes | - | | `linkId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `direction` | `'import' \| 'export'` | Yes | - | | `error` | `string` | Yes | - | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "run.failed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "runId": "run_123", "linkId": "link_123", "vaultId": "vault_123", "direction": "direction_value", "error": "Processing failed" } } ``` ## link.objects\_changed A connector run changed the set of synced objects behind a link. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `connectors` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | `linkId` | `string` | Yes | - | | `vaultId` | `string` | Yes | - | | `runId` | `string` | Yes | - | | `changed` | `number` | Yes | Number of ledger rows added/updated/deleted by the run. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "link.objects_changed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "linkId": "link_123", "vaultId": "vault_123", "runId": "run_123", "changed": 42 } } ``` ## voice.call.ended A phone call leg ended, with its disposition and duration. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `voice` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | *(none)* | - | - | Empty `data` object. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.call.ended", "occurred_at": "2026-04-24T15:12:09.481Z", "data": {} } ``` ## voice.call.analyzed Post-call analysis is ready: summary, outcome, next steps, and extraction. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `voice` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | *(none)* | - | - | Empty `data` object. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.call.analyzed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": {} } ``` ## voice.call.ended A phone call leg ended, with its disposition and duration. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `voice` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | *(none)* | - | - | Empty `data` object. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.call.ended", "occurred_at": "2026-04-24T15:12:09.481Z", "data": {} } ``` ## voice.call.analyzed Post-call analysis is ready: summary, outcome, next steps, and extraction. | Property | Value | | - | - | | Stability | `beta` | | Required scope | `voice` | | Resource scope | None | ### Payload | Field | Type | Required | Description | | - | - | - | - | | *(none)* | - | - | Empty `data` object. | ### Example ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "voice.call.analyzed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": {} } ``` # Events Overview Source: https://docs.case.dev/events/index Receive signed HTTP callbacks when Case.dev events happen Events let your app react to Case.dev activity without polling. Configure an HTTPS endpoint, choose the event types you want, and Case.dev sends a signed JSON delivery when matching events happen in your organization. > [card] [API reference](/api-reference/webhooks) > > See the full endpoint reference for webhook subscriptions, deliveries, replay, rotation, and event > types. ## Why use webhooks? * **React immediately** when vault ingestion, OCR, transcription, matter, billing, or deployment events finish. * **Reduce polling** for long-running jobs and update your UI from delivery events. * **Scope subscriptions** by event type, vault, or matter so each receiver only gets what it needs. * **Recover safely** with delivery history, manual replay, retries, and endpoint auto-disable. ## Quick example ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/webhooks/v1/endpoints \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.example.com/webhooks/casedev", "eventTypeFilters": ["vault.ingest.completed"] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev webhooks:v1:endpoints create \ --url "https://your-app.example.com/webhooks/casedev" \ --event-type-filter vault.ingest.completed ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev' const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }) const endpoint = await client.webhooks.v1.endpoints.create({ url: 'https://your-app.example.com/webhooks/casedev', eventTypeFilters: ['vault.ingest.completed'], }) console.log(endpoint.endpoint.id, endpoint.signingSecret) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ["CASEDEV_API_KEY"]) endpoint = client.webhooks.v1.endpoints.create( url="https://your-app.example.com/webhooks/casedev", event_type_filters=["vault.ingest.completed"], ) print(endpoint.endpoint.id, endpoint.signing_secret) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} endpoint, _ := client.Webhooks.V1.Endpoints.New(ctx, casedev.WebhooksV1EndpointNewParams{ URL: casedev.F("https://your-app.example.com/webhooks/casedev"), EventTypeFilters: casedev.F([]string{"vault.ingest.completed"}), }) fmt.Println(endpoint.Endpoint.ID, endpoint.SigningSecret) ``` ```json title="Delivery" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "evt_01HV8ZK8M7Q9YJ6P5E3P2R1A0B", "type": "vault.ingest.completed", "occurred_at": "2026-04-24T15:12:09.481Z", "data": { "vaultId": "vault_123", "objectId": "obj_123", "durationMs": 1284, "chunkCount": 42 } } ``` Case.dev includes delivery ID, timestamp, and signature headers on every delivery. Verify the signature against the raw request body before parsing the JSON. A delivery includes an `id`, `type`, `occurred_at`, and `data` payload for the event. ## Event filters Use exact names for narrow subscriptions, prefix wildcards for a service area, or `*` for every event your API key can receive. | Filter | Matches | | - | - | | `vault.ingest.completed` | One exact event type. | | `vault.ingest.*` | Every event beginning with `vault.ingest.` | | `vault.*` | Every event beginning with `vault.` | | `*` | Every subscribable event in the generated list. | Add `resourceScopes.vaultIds` or `resourceScopes.matterIds` when an endpoint should only receive events for specific resources. ## Delivery behavior Delivery is at least once. Store processed event IDs and make your handler idempotent. | Receiver result | Case.dev behavior | | - | - | | `2xx` response | Delivery is marked `delivered`. | | `408`, `429`, `5xx` | Delivery is retried. | | Network error or timeout | Delivery is retried. | | Other `4xx` | Delivery fails without retry. | Retries run inline first, then in the background. Repeated failures can auto-disable an endpoint until you re-enable it from the dashboard or API. ## Endpoints > [card] [Quickstart](/events/quickstart) > > Create an endpoint, verify signatures, and send a test event. > [card] [Event types](/events/event-types) > > Generated reference for subscribable events and payload shapes. > [card] [API reference](/api-reference/webhooks) > > OpenAPI reference for endpoint, delivery, replay, rotation, and catalog APIs. # Quickstart Source: https://docs.case.dev/events/quickstart Create a webhook endpoint and receive your first signed event This guide creates an endpoint, verifies deliveries in your receiver, and sends a test event. ## Create an endpoint ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/webhooks/v1/endpoints \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://your-app.example.com/webhooks/casedev", "description": "Production event receiver", "eventTypeFilters": ["vault.ingest.completed"] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev webhooks:v1:endpoints create \ --url "https://your-app.example.com/webhooks/casedev" \ --description "Production event receiver" \ --event-type-filter vault.ingest.completed ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev' const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }) const endpoint = await client.webhooks.v1.endpoints.create({ url: 'https://your-app.example.com/webhooks/casedev', description: 'Production event receiver', eventTypeFilters: ['vault.ingest.completed'], }) console.log(endpoint.endpoint.id, endpoint.signingSecret) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ["CASEDEV_API_KEY"]) endpoint = client.webhooks.v1.endpoints.create( url="https://your-app.example.com/webhooks/casedev", description="Production event receiver", event_type_filters=["vault.ingest.completed"], ) print(endpoint.endpoint.id, endpoint.signing_secret) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} endpoint, _ := client.Webhooks.V1.Endpoints.New(ctx, casedev.WebhooksV1EndpointNewParams{ URL: casedev.F("https://your-app.example.com/webhooks/casedev"), Description: casedev.F("Production event receiver"), EventTypeFilters: casedev.F([]string{"vault.ingest.completed"}), }) fmt.Println(endpoint.Endpoint.ID, endpoint.SigningSecret) ``` The response includes `endpoint.id` and `signingSecret`. Store the signing secret in your secrets manager before closing the response. ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "endpoint": { "id": "evsub_123", "url": "https://your-app.example.com/webhooks/casedev", "eventTypeFilters": ["vault.ingest.completed"], "status": "active" }, "signingSecret": "whsec_..." } ``` ## Add a receiver The TypeScript, Python, and Go SDKs ship a `Webhook` helper that verifies the signature, enforces a 5-minute timestamp tolerance, and returns the parsed event. Hand it the raw request body — re-stringified JSON breaks the signature. Keep receiver logs bounded to delivery status and event type; avoid logging event IDs or payload data unless you redact them first. ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import express from 'express' import { Webhook, WebhookVerificationError } from 'casedev/webhooks' const app = express() const wh = new Webhook(process.env.CASEDEV_WEBHOOK_SECRET!) app.post('/webhooks/casedev', express.raw({ type: 'application/json' }), (req, res) => { try { const event = wh.verify(req.body, req.headers) console.info('case.dev webhook received', { type: event.type }) if (event.type === 'vault.ingest.completed') { // Trigger internal work from event.data here; do not log the payload directly. } return res.sendStatus(204) } catch (err) { if (err instanceof WebhookVerificationError) return res.status(400).send(err.code) throw err } }) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os from flask import Flask, abort, request from casedev.webhooks import Webhook, WebhookVerificationError app = Flask(__name__) wh = Webhook(os.environ["CASEDEV_WEBHOOK_SECRET"]) @app.post("/webhooks/casedev") def casedev_webhook(): try: event = wh.verify(request.get_data(), request.headers) except WebhookVerificationError as exc: abort(400, exc.code) app.logger.info("case.dev webhook received", extra={"event_type": event["type"]}) return ("", 204) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import ( "io" "net/http" "os" "github.com/casemark/casedev-go/webhooks" ) var wh, _ = webhooks.NewVerifier(os.Getenv("CASEDEV_WEBHOOK_SECRET")) func receive(w http.ResponseWriter, r *http.Request) { body, _ := io.ReadAll(r.Body) var event webhooks.Envelope if err := wh.VerifyInto(body, r.Header, &event); err != nil { if ve, ok := webhooks.AsVerificationError(err); ok { http.Error(w, string(ve.Code), http.StatusBadRequest) return } http.Error(w, err.Error(), http.StatusInternalServerError) return } // event.Type is the discriminator; json.Unmarshal event.Data into the // event-specific struct. w.WriteHeader(http.StatusNoContent) } ``` ## Send a test event ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST "https://api.case.dev/webhooks/v1/endpoints/$ENDPOINT_ID/test" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "eventType": "vault.ingest.completed", "payload": { "vaultId": "vault_123", "objectId": "obj_123", "durationMs": 1284, "chunkCount": 42 } }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev webhooks:v1:endpoints test "$ENDPOINT_ID" \ --event-type vault.ingest.completed \ --payload '{"vaultId":"vault_123","objectId":"obj_123","durationMs":1284,"chunkCount":42}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.webhooks.v1.endpoints.test(endpointId, { eventType: 'vault.ingest.completed', payload: { vaultId: 'vault_123', objectId: 'obj_123', durationMs: 1284, chunkCount: 42, }, }) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.webhooks.v1.endpoints.test( endpoint_id, event_type="vault.ingest.completed", payload={ "vaultId": "vault_123", "objectId": "obj_123", "durationMs": 1284, "chunkCount": 42, }, ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} _, _ = client.Webhooks.V1.Endpoints.Test(ctx, endpointID, casedev.WebhooksV1EndpointTestParams{ EventType: casedev.F("vault.ingest.completed"), Payload: casedev.F(map[string]any{ "vaultId": "vault_123", "objectId": "obj_123", "durationMs": 1284, "chunkCount": 42, }), }) ``` The test endpoint performs one synchronous delivery. Use it to confirm reachability and signature verification before broadening your filters. ## Go live Start with exact event names, then widen to patterns like `vault.*` after your receiver is stable. Use [Event types](/events/event-types) for the generated event list and [API reference](/api-reference/webhooks) for endpoint update, replay, and rotation APIs. # Connect Case.dev to ChatGPT Source: https://docs.case.dev/getting-started/chatgpt Add Case.dev to ChatGPT as a remote MCP connector with OAuth. Connect Case.dev to ChatGPT so your team can create matters, search vaults, run OCR, and complete legal workflows without leaving ChatGPT. > [!TIP] > > ChatGPT supports remote MCP connectors, so you can connect Case.dev directly. ## Add the connector 1. Open ChatGPT **Settings**. 2. Go to **Connectors**. 3. If needed, enable **Developer mode** in **Connectors → Advanced**. 4. Add a custom remote MCP server. 5. Enter the Case.dev endpoint: ```text title="Remote MCP endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} https://api.case.dev/mcp ``` 6. Sign in to Case.dev and approve access. ## Authentication flow When you add the connector, ChatGPT sends you to Case.dev to sign in and approve access. After that, your tools are available in chat. ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} sequenceDiagram participant ChatGPT participant Router as api.case.dev participant Console as console.case.dev ChatGPT->>Router: Connect to /mcp Router-->>ChatGPT: Protected-resource metadata ChatGPT->>Console: Open OAuth approval Console->>Console: User signs in and approves Console->>Router: Exchange code for token Router-->>ChatGPT: MCP bearer token ChatGPT->>Router: Invoke Case.dev tools ``` ## First workflow to try Start with a simple matter setup flow: 1. `Create a matter called Johnson v. Acme Corp.` 2. `Upload the complaint into the matter vault.` 3. `Create a work item to extract the parties, claims, court, and deadlines.` 4. `Poll the work item until it completes.` 5. `Return the output and download link details.` This is a quick way to confirm that Case.dev is connected and ready to use. ## Example prompts * `Set up a new matter for this dispute and create the first legal ops checklist.` * `Search the vault for arbitration clauses and compare the top results.` * `Run OCR on these exhibits and tell me which pages were low confidence.` * `Run legal research on Delaware forum-selection enforcement and save the answer to the matter.` ## Troubleshooting > [accordion] The server connects but no tools run > > Refresh the connector and start a new chat. ChatGPT can keep a previous tool list or sign-in > state until the connector is refreshed. > [accordion] OAuth succeeds but the connector still shows an error > > Remove the connector, add it again, and complete the approval flow one more time. This usually > clears saved connector details from an earlier setup attempt. > [accordion] I only want a smaller tool surface > > Limit the tools exposed in your connector configuration if your workspace supports tool > filtering. ## Related > [card] [MCP Reference](/casedev-mcp/index) > > See the Case.dev MCP endpoint and available tools. > [card] [Skills](/skills/index) > > Pair the MCP server with reusable legal skills. # Connect Case.dev to Claude Source: https://docs.case.dev/getting-started/claude Add Case.dev to Claude as a remote MCP connector with OAuth. Connect Case.dev to Claude so you can work with matters, vaults, OCR, transcription, and legal research directly inside Claude. > [!TIP] > > Claude supports remote MCP connectors. Availability depends on your Claude plan and workspace. ## Add the connector 1. Open Claude and go to **Settings**. 2. Open **Connectors**. 3. Choose **Add custom connector**. 4. Enter the Case.dev MCP endpoint: ```text title="Remote MCP endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} https://api.case.dev/mcp ``` 5. Save the connector, then sign in to Case.dev and approve access. ## Authentication flow Claude sends you to Case.dev to sign in and approve access. After that, your Case.dev tools are available in the conversation. ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} sequenceDiagram participant Claude participant Router as api.case.dev participant Console as console.case.dev Claude->>Router: Connect to /mcp Router-->>Claude: 401 + protected-resource metadata Claude->>Console: Open authorization flow Console->>Console: User signs in and approves Console->>Router: Exchange authorization code Router-->>Claude: MCP access token Claude->>Router: Call tools on /mcp ``` ## First workflow to try Start with a straightforward matter intake flow: 1. `Create a new matter called Johnson v. Acme Corp for a commercial contract dispute.` 2. `Create a vault for that matter and upload the complaint PDF I attached.` 3. `Start a work item that extracts the parties, claims, filing date, and requested relief.` 4. `Poll the work item until it finishes, then summarize the output.` 5. `Download the extracted output into the vault and give me the object details.` This is a quick way to confirm that Claude is connected and ready to use. ## Example prompts * `Create a new matter for Johnson v. Acme Corp and scaffold the first three work items.` * `Search the matter vault for indemnification clauses and show me the strongest hits.` * `OCR this scanned exhibit set and flag handwritten annotations.` * `Run legal research on California spoliation sanctions and save the result back to the matter.` ## Troubleshooting > [accordion] I connected the server but no tools appear > > Refresh the connector, then start a new chat. Claude can keep the previous tool list until you reconnect. > [accordion] OAuth keeps bouncing me back to sign in > > Make sure you complete the Case.dev sign-in and approval flow in the browser window Claude > opens. If your browser blocks pop-ups or third-party cookies, allow them and try again. > [accordion] A tool call returns a permission or auth error > > Reconnect the connector so Claude picks up a fresh sign-in and your latest permissions. ## Related > [card] [MCP Reference](/casedev-mcp/index) > > See the Case.dev MCP endpoint, authentication setup, and available tools. > [card] [API Reference](/api-reference) > > Browse the underlying REST endpoints behind the MCP tools. # Connect Case.dev to Microsoft 365 Copilot Source: https://docs.case.dev/getting-started/copilot Add Case.dev to a Microsoft 365 Copilot declarative agent through an MCP-backed plugin. Connect Case.dev to Microsoft 365 Copilot so teams can create matters, search vaults, run OCR, and launch legal workflows from the Microsoft 365 tools they already use. > [!WARNING] > > Microsoft 365 Copilot setup usually happens through an IT or platform team. Start in a test > tenant, confirm sign-in and tool access, then roll it out more broadly. ## Recommended setup path Use Microsoft 365 Agents Toolkit or Copilot Studio to connect Case.dev as an action source for your Copilot agent. ```text title="Remote MCP endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} https://api.case.dev/mcp ``` ## High-level setup 1. Create a new **Declarative Agent** in Microsoft 365 Agents Toolkit. 2. Choose **Add an Action** and start with an existing **MCP server**. 3. Enter `https://api.case.dev/mcp`. 4. Fetch the available operations and choose the actions you want to make available. 5. Configure authentication for the agent. 6. Provision and sideload the agent into your Microsoft 365 tenant. 7. Enable the agent for the users or groups who should have Case.dev access. ## Authentication Case.dev supports the OAuth authorization-code flow used by Microsoft Copilot integrations. For the smoothest rollout: * Use discovery-based OAuth when your Copilot environment supports it. * Test sign-in and approval in a development tenant first. * Start with the most important actions, then expand from there. ## First workflow to try Start with a simple matter intake workflow: 1. `Create a matter named Johnson v. Acme Corp.` 2. `Upload the attached complaint into the matter vault.` 3. `Create a work item that extracts parties, claims, deadlines, and requested relief.` 4. `Check the work item until it completes.` 5. `Return the result and link the output object.` ## Example prompts * `Open a new matter for Johnson v. Acme Corp and give me a case kickoff checklist.` * `Search the matter vault for every document mentioning indemnification.` * `Run OCR on this scanned filing set and summarize the result.` * `Create a work item to draft a deposition outline from the uploaded exhibits.` ## Troubleshooting > [accordion] The agent packages but validation fails > > Reduce the number of actions in the first version of the agent, then add more once the package > is working. > [accordion] Users cannot authenticate to Case.dev > > Verify that your Copilot environment is using the OAuth authorization-code flow and that the > final redirect stays on a Microsoft-owned callback domain. > [accordion] Too many tools are showing up in the agent > > Rebuild the package with a narrower set of actions so the first release stays focused and easy > to validate. ## Related > [card] [MCP Reference](/casedev-mcp/index) > > See the Case.dev MCP endpoint and the tools available in Copilot. > [card] [Matters](/matters/index) > > Learn how matters work before you add matter creation and editing actions. # Digitize Evidence Source: https://docs.case.dev/getting-started/digitize-evidence Extract text from scanned documents **The problem:** Opposing counsel sent you 500 pages of blurry photocopies. You need to search them, but they're just images. **The solution:** Run OCR to extract text, then search or analyze with AI. ## 1. Submit for OCR ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/ocr/v1/process \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "document_url": "https://your-storage.com/user-upload.pdf", "engine": "doctr", "features": {"embed": {}} }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/document.pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Process a document uploaded by your user const job = await client.ocr.v1.process({ document_url: documentUrl, // URL from your user's upload engine: 'doctr', // Fast, good for printed text features: { embed: {} // Generate searchable PDF } }); console.log(`OCR job started: ${job.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Process a document uploaded by your user job = client.ocr.v1.process( document_url=document_url, # URL from your user's upload engine='doctr', # Fast, good for printed text features={ 'embed': {} # Generate searchable PDF } ) print(f'OCR job started: {job.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/document.pdf"), }) fmt.Println(job.ID) ``` ## 2. Wait for completion OCR runs asynchronously. Poll for status or use webhooks to notify your users: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Poll for status curl "https://api.case.dev/ocr/v1/$JOB_ID" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 retrieve --id $JOB_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Poll for completion let result = await client.ocr.v1.retrieve(job.id); while (result.status === 'processing' || result.status === 'pending') { console.log(`Status: ${result.status} (${result.chunks_completed}/${result.chunk_count} pages)`); await new Promise(r => setTimeout(r, 5000)); result = await client.ocr.v1.retrieve(job.id); } if (result.status === 'completed') { console.log(`✅ OCR complete! ${result.page_count} pages processed.`); console.log(`Confidence: ${(result.confidence * 100).toFixed(1)}%`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time # Poll for completion result = client.ocr.v1.retrieve(job.id) while result.status in ['processing', 'pending']: print(f'Status: {result.status} ({result.chunks_completed}/{result.chunk_count} pages)') time.sleep(5) result = client.ocr.v1.retrieve(job.id) if result.status == 'completed': print(f'✅ OCR complete! {result.page_count} pages processed.') print(f'Confidence: {result.confidence * 100:.1f}%') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Ocr.V1.Get(ctx, jobID) fmt.Println(result.Status) ``` ## 3. Download results Provide extracted text, structured data, or a searchable PDF: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Download text curl "https://api.case.dev/ocr/v1/$JOB_ID/download/text" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -o extracted.txt # Download searchable PDF curl "https://api.case.dev/ocr/v1/$JOB_ID/download/pdf" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -o searchable.pdf ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 download --id $JOB_ID --type text ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Download plain text for your user const text = await client.ocr.v1.download(job.id, 'text'); // Download searchable PDF (original with invisible text layer) const pdf = await client.ocr.v1.download(job.id, 'pdf'); fs.writeFileSync('searchable-document.pdf', Buffer.from(pdf)); // Download structured JSON (with word coordinates for highlighting) const json = await client.ocr.v1.download(job.id, 'json'); console.log(`Extracted ${json.pages.length} pages`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Download plain text for your user text = client.ocr.v1.download(job.id, 'text') # Download searchable PDF (original with invisible text layer) pdf = client.ocr.v1.download(job.id, 'pdf') with open('searchable-document.pdf', 'wb') as f: f.write(pdf) # Download structured JSON (with word coordinates for highlighting) json_data = client.ocr.v1.download(job.id, 'json') print(f'Extracted {len(json_data["pages"])} pages') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} text, _ := client.Ocr.V1.Download(ctx, jobID, casedev.OcrV1DownloadParamsTypeText) // text is *http.Response with content body ``` ## 4. Analyze with AI Enhance your feature with automatic data extraction: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [ {"role": "system", "content": "Extract key dates, parties, and claims. Format as JSON."}, {"role": "user", "content": "[OCR TEXT]"} ], "temperature": 0 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Extract key dates, parties, and claims from this document. Format as JSON."}' \ --message '{role: user, content: ""}' \ --temperature 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Extract key information for your user const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Extract key dates, parties, and claims from this document. Format as JSON.' }, { role: 'user', content: text } ], temperature: 0 // Deterministic for factual extraction }); // Return structured data to your user console.log(analysis.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Extract key information for your user analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Extract key dates, parties, and claims from this document. Format as JSON.' }, { 'role': 'user', 'content': text } ], temperature=0 # Deterministic for factual extraction ) # Return structured data to your user print(analysis.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Extract key information for your user resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Extract key dates, parties, and claims from this document. Format as JSON."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(text), // OCR-extracted text }, }), Temperature: casedev.F(float64(0)), }) fmt.Println(resp.Choices[0].Message.Content) ``` ## OCR engines Choose the right engine based on your users' document types: | Engine | Best for | Speed | | - | - | - | | `doctr` | Clean printed text | Fast | | `paddleocr` | Tables, forms, complex layouts | Slower | > [!NOTE] > > **Recommendation:** Start with `doctr` for most use cases. Switch to `paddleocr` if your users need table extraction or have complex document layouts. # Discovery Search Source: https://docs.case.dev/getting-started/discovery-search Search thousands of documents in seconds **The problem:** You have 5,000 documents from discovery. Finding the relevant ones takes weeks of manual review. **The solution:** Upload to a Vault. We OCR, chunk, and index everything. Search by meaning in seconds. ## 1. Create a vault Vaults are secure containers for your users' documents. Each vault gets automatic OCR, chunking, and vector indexing. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/vault \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Case Documents - User 12345", "description": "Discovery documents for case review" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Case Documents - User 12345" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Create a vault for your user's documents const vault = await client.vault.create({ name: 'Case Documents - User 12345', description: 'Discovery documents for case review' }); console.log(`Vault created: ${vault.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Create a vault for your user's documents vault = client.vault.create( name='Case Documents - User 12345', description='Discovery documents for case review' ) print(f'Vault created: {vault.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Case Documents - User 12345"), Description: casedev.F("Discovery documents for case review"), }) fmt.Println(vault.ID) ``` ## 2. Upload documents Handle file uploads from your users and trigger automatic processing: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Get upload URL UPLOAD=$(curl -s -X POST "https://api.case.dev/vault/$VAULT_ID/upload" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"filename": "document.pdf", "contentType": "application/pdf"}') UPLOAD_URL=$(echo $UPLOAD | jq -r '.uploadUrl') OBJECT_ID=$(echo $UPLOAD | jq -r '.objectId') # 2. Upload file curl -X PUT "$UPLOAD_URL" \ -H "Content-Type: application/pdf" \ --data-binary "@document.pdf" # 3. Trigger ingestion curl -X POST "https://api.case.dev/vault/$VAULT_ID/ingest/$OBJECT_ID" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault upload \ --id $VAULT_ID \ --filename "document.pdf" \ --content-type "application/pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import fs from 'fs'; async function uploadDocument(vaultId: string, filePath: string) { // Get presigned upload URL const upload = await client.vault.upload(vaultId, { filename: filePath.split('/').pop()!, contentType: 'application/pdf' }); // Upload file to S3 const file = fs.readFileSync(filePath); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'application/pdf' }, body: file }); // Trigger OCR + embedding pipeline await client.vault.ingest(vaultId, upload.objectId); return upload.objectId; } // Process uploads from your user const files = fs.readdirSync('./uploads'); for (const file of files) { await uploadDocument(vault.id, `./uploads/${file}`); console.log(`Processed: ${file}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import requests def upload_document(vault_id: str, file_path: str) -> str: # Get presigned upload URL upload = client.vault.upload(vault_id, filename=os.path.basename(file_path), content_type='application/pdf' ) # Upload file to S3 with open(file_path, 'rb') as f: requests.put(upload.upload_url, data=f, headers={'Content-Type': 'application/pdf'}) # Trigger OCR + embedding pipeline client.vault.ingest(upload.object_id, id=vault_id) return upload.object_id # Process uploads from your user for file in os.listdir('./uploads'): upload_document(vault.id, f'./uploads/{file}') print(f'Processed: {file}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} upload, _ := client.Vault.Upload(ctx, vaultID, casedev.VaultUploadParams{ Filename: casedev.F("document.pdf"), ContentType: casedev.F("application/pdf"), }) // PUT file to upload.UploadURL via net/http fmt.Println(upload.ObjectID) ``` ## 3. Search by meaning Enable your users to search by meaning, not just keywords: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST "https://api.case.dev/vault/$VAULT_ID/search" \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "communications about equipment failure", "method": "hybrid", "topK": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault search \ --id $VAULT_ID \ --query "search query" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // In your search endpoint or UI handler const results = await client.vault.search(vault.id, { query: userQuery, // e.g., "communications about equipment failure" method: 'hybrid', topK: 10 }); // Return results to your user for (const chunk of results.chunks) { console.log(`📄 ${chunk.filename} (score: ${chunk.hybridScore.toFixed(2)})`); console.log(`"${chunk.text.substring(0, 200)}..."`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # In your search endpoint or UI handler results = client.vault.search(vault.id, query=user_query, # e.g., "communications about equipment failure" method='hybrid', top_k=10 ) # Return results to your user for chunk in results.chunks: print(f'📄 {chunk.filename} (score: {chunk.hybrid_score:.2f})') print(f'"{chunk.text[:200]}..."') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("search query"), Method: casedev.F(casedev.VaultSearchParamsMethodHybrid), }) for _, chunk := range results.Chunks { fmt.Println(chunk.Text) } ``` ## 4. Summarize findings Enhance results with AI-generated summaries for your users: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [ {"role": "system", "content": "Summarize these search results concisely."}, {"role": "user", "content": "User searched for: [QUERY]\n\nResults:\n\n[SEARCH RESULTS]"} ], "max_tokens": 500 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Summarize these search results concisely. Highlight the most relevant findings."}' \ --message '{role: user, content: "User searched for: \n\nResults:\n\n"}' \ --max-tokens 500 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const context = results.chunks.map(c => c.text).join('\n\n---\n\n'); const summary = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Summarize these search results concisely. Highlight the most relevant findings.' }, { role: 'user', content: `User searched for: "${userQuery}"\n\nResults:\n\n${context}` } ], max_tokens: 500 }); // Return summary along with search results console.log(summary.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} context = '\n\n---\n\n'.join([c.text for c in results.chunks]) summary = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Summarize these search results concisely. Highlight the most relevant findings.' }, { 'role': 'user', 'content': f'User searched for: "{user_query}"\n\nResults:\n\n{context}' } ], max_tokens=500 ) # Return summary along with search results print(summary.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Summarize search results for your user resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Summarize these search results concisely. Highlight the most relevant findings."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("User searched for: " + query + "\n\nResults:\n\n" + searchResultsText), }, }), MaxTokens: casedev.F(int64(500)), }) fmt.Println(resp.Choices[0].Message.Content) ``` > [!NOTE] > > **Time saved:** What used to take weeks of manual review now takes minutes. The AI finds relevant passages even when documents use different terminology. # Getting Started Source: https://docs.case.dev/getting-started/index Build legal automation in 5 minutes ## Install the SDK ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # No installation needed — just set your API key export CASEDEV_API_KEY="sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} brew tap CaseMark/casedev && brew install casedev ``` ```bash title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} npm install casedev ``` ```bash title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} pip install casedev ``` ```bash title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} go get github.com/CaseMark/casedev-go ``` ## Initialize the client ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Include in every request: # -H "Authorization: Bearer $CASEDEV_API_KEY" export CASEDEV_API_KEY="sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # CLI reads CASEDEV_API_KEY from environment export CASEDEV_API_KEY="sk_case_YOUR_API_KEY" casedev llm:v1 list-models # verify it works ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev' const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY, }) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev( api_key=os.environ['CASEDEV_API_KEY'] ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import ( casedev "github.com/CaseMark/casedev-go" ) client := casedev.NewClient() // uses CASEDEV_API_KEY env var ``` ## Your first API call Let's build a simple legal extraction feature—pulling parties from a case description. > [!TIP] > > **Curated Model Catalog:** Browse all available models with pricing and capabilities at > [case.dev/models](https://case.dev/models). ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [ {"role": "system", "content": "You are a legal assistant. Extract the Plaintiff and Defendant."}, {"role": "user", "content": "Smith v. Jones Construction..."} ] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a legal assistant. Extract the Plaintiff and Defendant from the text."}' \ --message '{role: user, content: "Smith v. Jones Construction, filed in the Superior Court of California..."}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'You are a legal assistant. Extract the Plaintiff and Defendant from the text.', }, { role: 'user', content: 'Smith v. Jones Construction, filed in the Superior Court of California. John Smith alleges negligence regarding...', }, ], }) console.log(response.choices[0].message.content) // Output: "Plaintiff: John Smith\nDefendant: Jones Construction" ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'You are a legal assistant. Extract the Plaintiff and Defendant from the text.' }, { 'role': 'user', 'content': 'Smith v. Jones Construction, filed in the Superior Court of California. John Smith alleges negligence regarding...' } ] ) print(response.choices[0].message.content) # Output: "Plaintiff: John Smith\nDefendant: Jones Construction" ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a legal assistant. Extract the Plaintiff and Defendant from the text."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Smith v. Jones Construction, filed in the Superior Court of California. John Smith alleges negligence regarding..."), }, }), }) fmt.Println(resp.Choices[0].Message.Content) // Output: "Plaintiff: John Smith\nDefendant: Jones Construction" ``` ## What's next? > [card] [Document Search](/getting-started/discovery-search) > > Build semantic search across thousands of documents for your users > [card] [OCR Integration](/getting-started/digitize-evidence) > > Add document digitization to extract text from scanned PDFs > [card] [Audio Transcription](/getting-started/litigation-depositions) > > Enable your users to convert audio recordings to searchable text ## Authentication Get your API key from the [Console](https://console.case.dev). You get **$10 free usage** every month, or **$30/month** when you add a payment method. All requests require your API key in the `Authorization` header: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} Authorization: Bearer sk_case_YOUR_API_KEY ``` > [!NOTE] > > **Keep your API key secret.** Don't commit it to version control. Use environment variables. ## Connect from your AI client If you already live in Claude, ChatGPT, or Microsoft 365 Copilot, connect Case.dev there instead of building a separate wrapper first. > [card] [Claude](/getting-started/claude) > > Add Case.dev as a remote MCP connector in Claude and authenticate with OAuth. > [card] [ChatGPT](/getting-started/chatgpt) > > Connect Case.dev to ChatGPT's remote MCP flow for chat and research tools. > [card] [Copilot](/getting-started/copilot) > > Package Case.dev into a Microsoft 365 Copilot declarative agent. # Deposition Prep Source: https://docs.case.dev/getting-started/litigation-depositions Transcribe and analyze witness testimony **The problem:** You have 50 hours of video depositions. You suspect the CEO contradicted the CTO on the breach timeline, but you can't re-watch everything. **The solution:** Transcribe the audio, search by topic, and use AI to find contradictions. ## 1. Transcribe the depositions ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/voice/transcription \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "audio_url": "https://your-storage.com/user-recording.mp4", "speaker_labels": true, "auto_chapters": true }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev voice:transcription create \ --audio-url "https://storage.example.com/recording.mp3" \ --speaker-labels ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Transcribe audio uploaded by your user const job = await client.voice.transcription.create({ audio_url: audioUrl, // URL from your user's upload speaker_labels: true, // Identify who's speaking auto_chapters: true // Detect topic changes }); console.log(`Transcription started: ${job.id}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Transcribe audio uploaded by your user job = client.voice.transcription.create( audio_url=audio_url, # URL from your user's upload speaker_labels=True, # Identify who's speaking auto_chapters=True # Detect topic changes ) print(f'Transcription started: {job.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Voice.Transcription.New(ctx, casedev.VoiceTranscriptionNewParams{ AudioURL: casedev.F("https://storage.example.com/recording.mp3"), SpeakerLabels: casedev.F(true), }) fmt.Println(job.ID) ``` ## 2. Get the transcripts ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Get transcription result curl "https://api.case.dev/voice/transcription/$JOB_ID" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev voice:transcription create \ --audio-url "https://storage.example.com/recording.mp3" \ --speaker-labels ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Wait for completion async function waitForTranscription(jobId: string) { let result = await client.voice.transcription.retrieve(jobId); while (result.status !== 'completed') { if (result.status === 'error') throw new Error('Transcription failed'); await new Promise(r => setTimeout(r, 10000)); result = await client.voice.transcription.retrieve(jobId); } return result; } const transcript = await waitForTranscription(job.id); // Deliver speaker-labeled transcript to your user for (const utterance of transcript.utterances) { console.log(`${utterance.speaker}: ${utterance.text}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time def wait_for_transcription(job_id: str): result = client.voice.transcription.retrieve(job_id) while result.status != 'completed': if result.status == 'error': raise Exception('Transcription failed') time.sleep(10) result = client.voice.transcription.retrieve(job_id) return result transcript = wait_for_transcription(job.id) # Deliver speaker-labeled transcript to your user for utterance in transcript.utterances: print(f'{utterance.speaker}: {utterance.text}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Voice.Transcription.New(ctx, casedev.VoiceTranscriptionNewParams{ AudioURL: casedev.F("https://storage.example.com/recording.mp3"), SpeakerLabels: casedev.F(true), }) fmt.Println(job.ID) ``` ## 3. Store in a vault for search Store transcripts in a vault so your users can search across multiple recordings: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Create vault VAULT=$(curl -s -X POST https://api.case.dev/vault \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"name": "Audio Transcripts - User 12345"}') VAULT_ID=$(echo $VAULT | jq -r '.id') ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev vault create --name "Audio Transcripts - User 12345" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Create a vault for your user's transcripts const vault = await client.vault.create({ name: 'Audio Transcripts - User 12345' }); // Upload transcript as a searchable document async function uploadTranscript(vaultId: string, name: string, text: string) { const upload = await client.vault.upload(vaultId, { filename: `${name}.txt`, contentType: 'text/plain' }); await fetch(upload.uploadUrl, { method: 'PUT', headers: { 'Content-Type': 'text/plain' }, body: text }); await client.vault.ingest(vaultId, upload.objectId); } await uploadTranscript(vault.id, 'recording-001', transcript.text); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import requests # Create a vault for your user's transcripts vault = client.vault.create(name='Audio Transcripts - User 12345') def upload_transcript(vault_id: str, name: str, text: str): upload = client.vault.upload(vault_id, filename=f'{name}.txt', content_type='text/plain' ) requests.put(upload.upload_url, data=text.encode(), headers={'Content-Type': 'text/plain'}) client.vault.ingest(upload.object_id, id=vault_id) upload_transcript(vault.id, 'recording-001', transcript.text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} vault, _ := client.Vault.New(ctx, casedev.VaultNewParams{ Name: casedev.F("Audio Transcripts - User 12345"), }) fmt.Println(vault.ID) ``` ## 4. Find contradictions Help your users extract insights from transcripts: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [ {"role": "system", "content": "Summarize this transcript. Identify key points and action items."}, {"role": "user", "content": "[TRANSCRIPT TEXT]"} ] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Summarize this transcript. Identify key points, action items, and any notable quotes."}' \ --message '{role: user, content: ""}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Analyze transcript for your user const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Summarize this transcript. Identify key points, action items, and any notable quotes.' }, { role: 'user', content: transcript.text } ] }); // Return analysis to your user console.log(analysis.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Analyze transcript for your user analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Summarize this transcript. Identify key points, action items, and any notable quotes.' }, { 'role': 'user', 'content': transcript.text } ] ) # Return analysis to your user print(analysis.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Analyze transcript for your user resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Summarize this transcript. Identify key points, action items, and any notable quotes."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(transcript.Text), }, }), }) // Return analysis to your user fmt.Println(resp.Choices[0].Message.Content) ``` **Example output:** Build advanced features like contradiction detection for legal applications: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for statements about a specific topic casedev vault search \ --id $VAULT_ID \ --query "timeline of events on July 15th" \ --top-k 10 # Use AI to identify contradictions (pipe search results) casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{"role":"system","content":"Analyze these statements and identify any contradictions. Cite specific quotes."}' \ --message '{"role":"user","content":""}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search for statements about a specific topic const statements = await client.vault.search(vault.id, { query: 'timeline of events on July 15th', topK: 10 }); // Use AI to identify contradictions const contradictions = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Analyze these statements and identify any contradictions. Cite specific quotes.' }, { role: 'user', content: statements.chunks.map(c => c.text).join('\n\n') } ] }); console.log(contradictions.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for statements about a specific topic statements = client.vault.search(vault.id, query='timeline of events on July 15th', top_k=10 ) # Use AI to identify contradictions contradictions = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Analyze these statements and identify any contradictions. Cite specific quotes.' }, { 'role': 'user', 'content': '\n\n'.join(c.text for c in statements.chunks) } ] ) print(contradictions.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search for statements about a specific topic statements, _ := client.Vault.Search(ctx, vaultID, casedev.VaultSearchParams{ Query: casedev.F("timeline of events on July 15th"), TopK: casedev.F(int64(10)), }) // Build content from chunks var texts []string for _, chunk := range statements.Chunks { texts = append(texts, chunk.Text) } content := strings.Join(texts, "\n\n") // Use AI to identify contradictions contradictions, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Analyze these statements and identify any contradictions. Cite specific quotes."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(content), }, }), }) fmt.Println(contradictions.Choices[0].Message.Content) ``` > [!NOTE] > > **Time saved:** What used to take days of re-watching video now takes minutes. The AI finds contradictions you might have missed. # Web Research Source: https://docs.case.dev/getting-started/research-automation AI-powered research with citations **The problem:** You need to research a legal issue across multiple jurisdictions. Manual research takes days. **The solution:** Use AI-powered web search to get answers with citations and retrieve supporting sources. > [!WARNING] > > **Web data only.** This searches publicly available web content. For comprehensive legal research (case law, statutes, regulations), use specialized platforms like Lexis, Westlaw, or OpenLaws. ## Quick answer with citations Let your users get AI-generated answers to questions: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/search/v1/answer \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "What is the statute of limitations for medical malpractice in California?", "includeDomains": ["law.cornell.edu", "findlaw.com", "justia.com"] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev search:v1 answer \ --query "What is the statute of limitations?" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Answer your user's question const result = await client.search.v1.answer({ query: userQuery, // e.g., "What is the statute of limitations for medical malpractice in California?" includeDomains: ['law.cornell.edu', 'findlaw.com', 'justia.com'] }); // Return answer with citations to your user console.log(result.answer); // "In California, the statute of limitations for medical malpractice // is 3 years from the date of injury or 1 year from discovery [1]..." console.log('\nSources:'); for (const citation of result.citations) { console.log(`[${citation.id}] ${citation.title}`); console.log(` ${citation.url}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Answer your user's question result = client.search.v1.answer( query=user_query, # e.g., "What is the statute of limitations..." include_domains=['law.cornell.edu', 'findlaw.com', 'justia.com'] ) # Return answer with citations to your user print(result.answer) print('\nSources:') for citation in result.citations: print(f'[{citation.id}] {citation.title}') print(f' {citation.url}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Search.V1.Answer(ctx, casedev.SearchV1AnswerParams{ Query: casedev.F("What is the statute of limitations?"), }) fmt.Println(result.Answer) for _, c := range result.Citations { fmt.Printf("[%s] %s: %s\n", c.ID, c.Title, c.URL) } ``` ## Web search For simple searches, expose the search endpoint directly: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/search/v1/search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "SEC cryptocurrency enforcement actions 2024", "numResults": 20, "startPublishedDate": "2024-01-01", "excludeDomains": ["reddit.com", "twitter.com"], "includeText": true }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev search:v1 search \ --query "search query" \ --num-results 20 --include-text ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Search on behalf of your user const results = await client.search.v1.search({ query: userSearchQuery, numResults: 20, startPublishedDate: '2024-01-01', excludeDomains: ['reddit.com', 'twitter.com'], includeText: true }); // Return results to your user for (const result of results.results) { console.log(`${result.title}`); console.log(`${result.url}`); console.log(`Published: ${result.publishedDate}\n`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search on behalf of your user results = client.search.v1.search( query=user_search_query, num_results=20, start_published_date='2024-01-01', exclude_domains=['reddit.com', 'twitter.com'], include_text=True ) # Return results to your user for result in results.results: print(result.title) print(result.url) print(f'Published: {result.published_date}\n') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Search.V1.Search(ctx, casedev.SearchV1SearchParams{ Query: casedev.F("search query"), NumResults: casedev.F(int64(20)), IncludeText: casedev.F(true), }) for _, r := range results.Results { fmt.Println(r.Title, r.URL) } ``` ## Research models Choose based on your users' needs: | Model | Time | Depth | Use case | | - | - | - | - | | `fast` | \~30 sec | Basic | Quick fact-checking | | `normal` | \~2 min | Good | Standard research | | `pro` | \~5 min | Best | Complex topics | > [!NOTE] > > **Tip:** Use `includeDomains` to restrict results to authoritative sources like government sites and legal databases. # Source: https://docs.case.dev/index CASE.DEV · INTRODUCTION # The Infrastructure for Legal Engineering. API-native legal systems that can act. The matter, vault, model, and agent layer for software that does the work instead of waiting for input. [Get Started ↗](/getting-started/index) [View Console ↗](https://console.case.dev) [Install CLI](/cli) [Read Linc](https://casemark.com/blog/why-we-built-linc-the-terminal-based-legal-agent) [Matters](/matters/index) CLI `brew tap CaseMark/casedev && brew install casedev` Linc `npm install -g @casemark/linc` ## Explore > [card] [CLI](/cli) > > Run case.dev from your terminal. Install with Homebrew. > [card] [SDK](/sdks) > > Official bindings for TypeScript, Python, and Go. > [card] [MCP](/casedev-mcp/index) > > Connect to Claude, ChatGPT, Copilot, and any MCP client. ## Services > [card] [Matters](/matters/index) > > Matter-native orchestration, work items, parties, logs, shares, and human review. > [card] [Linc](/linc/index) > > Durable legal agent sessions with sandboxed tools, files, skills, and resumable state. > [card] [Vault](/vault/index) > > Secure document storage with indexing, OCR pipelines, and semantic retrieval. [Explore Services ↗](/services) # Citations Source: https://docs.case.dev/legal-research/citations Parse, verify, and retrieve legal citations Legal citations must be verified before use. This page covers all citation-related endpoints: parsing citations from text, extracting them from documents, verifying they exist, and retrieving full content. ## Verify citations Check if a citation refers to a real case. Essential for catching AI hallucinations. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/verify ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "The Court held in Bush v. Gore, 531 U.S. 98 (2000)..." }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 verify \ --text "The Court held in Bush v. Gore, 531 U.S. 98 (2000)..." ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.verify({ text: 'The Court held in Bush v. Gore, 531 U.S. 98 (2000)...' }); console.log(result.summary); // { total: 1, verified: 1, notFound: 0, multipleMatches: 0 } for (const citation of result.citations) { if (citation.status === 'verified') { console.log(`✓ ${citation.case.name}: ${citation.case.url}`); } else { console.log(`✗ ${citation.original}: not found`); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.verify( text='The Court held in Bush v. Gore, 531 U.S. 98 (2000)...' ) print(result.summary) # { total: 1, verified: 1, not_found: 0, multiple_matches: 0 } for citation in result.citations: if citation.status == 'verified': print(f'✓ {citation.case.name}: {citation.case.url}') else: print(f'✗ {citation.original}: not found') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F("The Court held in Bush v. Gore, 531 U.S. 98 (2000)..."), }) fmt.Println(result.Summary) // { Total: 1, Verified: 1, NotFound: 0, MultipleMatches: 0 } for _, citation := range result.Citations { if citation.Status == "verified" { fmt.Printf("✓ %s: %s\n", citation.Case.Name, citation.Case.URL) } else { fmt.Printf("✗ %s: not found\n", citation.Original) } } ``` ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "summary": { "total": 1, "verified": 1, "notFound": 0, "multipleMatches": 0 }, "citations": [ { "original": "531 U.S. 98", "span": { "start": 32, "end": 43 }, "status": "verified", "verificationSource": "courtlistener", "confidence": 1, "normalized": "531 U.S. 98", "case": { "id": 118365, "name": "Bush v. Gore", "shortName": "Bush", "court": "scotus", "dateDecided": "2000-12-12", "parallelCitations": ["121 S. Ct. 525", "148 L. Ed. 2d 388"], "url": "https://www.courtlistener.com/opinion/118365/bush-v-gore/" } } ] } ``` ### Verification statuses | Status | Meaning | | - | - | | `verified` | Citation matches a real case in CourtListener (\~10M cases) | | `not_found` | No match found — likely hallucination or typo | | `multiple_matches` | Multiple possible matches — review `candidates` array | Each citation also includes `verificationSource` and `confidence`. CourtListener returns `confidence: 1.0`, while heuristic fallback uses a score based on the source verification signals. *** ## Parse citations from text Extract and parse Bluebook components from citation text. Use when you have text and need structured citation data. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/citations ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/citations \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 get-citations \ --text "See Roe v. Wade, 410 U.S. 113 (1973), overruled by Dobbs v. Jackson, 597 U.S. 215 (2022)." ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.citations({ text: 'See Roe v. Wade, 410 U.S. 113 (1973), overruled by Dobbs v. Jackson, 597 U.S. 215 (2022).' }); for (const citation of result.citations) { console.log(`${citation.normalized}`); console.log(` Volume: ${citation.components.volume}`); console.log(` Reporter: ${citation.components.reporter}`); console.log(` Page: ${citation.components.page}`); console.log(` Found: ${citation.found}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.get_citations( text='See Roe v. Wade, 410 U.S. 113 (1973), overruled by Dobbs v. Jackson, 597 U.S. 215 (2022).' ) for citation in result.citations: print(f'{citation.normalized}') print(f' Volume: {citation.components.volume}') print(f' Reporter: {citation.components.reporter}') print(f' Page: {citation.components.page}') print(f' Found: {citation.found}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.GetCitations(ctx, casedev.LegalV1GetCitationsParams{ Text: casedev.F("See Roe v. Wade, 410 U.S. 113 (1973), overruled by Dobbs v. Jackson, 597 U.S. 215 (2022)."), }) for _, citation := range result.Citations { fmt.Println(citation.Normalized) fmt.Printf(" Volume: %d\n", citation.Components.Volume) fmt.Printf(" Reporter: %s\n", citation.Components.Reporter) fmt.Printf(" Page: %d\n", citation.Components.Page) fmt.Printf(" Found: %v\n", citation.Found) } ``` ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "citations": [ { "original": "410 U.S. 113", "span": { "start": 17, "end": 29 }, "components": { "caseName": "Roe v. Wade", "volume": 410, "reporter": "U.S.", "page": 113, "year": 1973, "court": "scotus" }, "normalized": "410 U.S. 113", "found": true } ] } ``` *** ## Extract citations from URL Fetch a document and extract all citations from it. Use when you have a URL and want to analyze what it cites. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/citations-from-url ``` **Key difference from `citations`:** This endpoint fetches content from a URL and categorizes citations by type (cases, statutes, regulations). The `citations` endpoint parses text you provide and returns Bluebook components. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/citations-from-url \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 get-citations-from-url \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.citationsFromUrl({ url: 'https://www.courtlistener.com/opinion/118365/bush-v-gore/' }); console.log(`Total citations: ${result.totalCitations}`); console.log(`Cases: ${result.citations.cases.length}`); console.log(`Statutes: ${result.citations.statutes.length}`); console.log(`Regulations: ${result.citations.regulations.length}`); // Most-cited authorities for (const cite of result.citations.cases.slice(0, 5)) { console.log(`${cite.citation} (${cite.count} times)`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.get_citations_from_url( url='https://www.courtlistener.com/opinion/118365/bush-v-gore/' ) print(f'Total citations: {result.total_citations}') print(f'Cases: {len(result.citations.cases)}') print(f'Statutes: {len(result.citations.statutes)}') print(f'Regulations: {len(result.citations.regulations)}') # Most-cited authorities for cite in result.citations.cases[:5]: print(f'{cite.citation} ({cite.count} times)') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.GetCitationsFromURL(ctx, casedev.LegalV1GetCitationsFromURLParams{ URL: casedev.F("https://www.courtlistener.com/opinion/118365/bush-v-gore/"), }) fmt.Printf("Total citations: %d\n", result.TotalCitations) fmt.Printf("Cases: %d\n", len(result.Citations.Cases)) fmt.Printf("Statutes: %d\n", len(result.Citations.Statutes)) fmt.Printf("Regulations: %d\n", len(result.Citations.Regulations)) // Most-cited authorities for _, cite := range result.Citations.Cases[:5] { fmt.Printf("%s (%d times)\n", cite.Citation, cite.Count) } ``` ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "url": "https://www.courtlistener.com/opinion/118365/bush-v-gore/", "title": "Bush v. Gore, 531 U.S. 98 (2000)", "totalCitations": 15, "citations": { "cases": [ { "type": "usReporter", "citation": "478 U.S. 109", "count": 3 }, { "type": "federalReporter", "citation": "772 F.2d 1444", "count": 1 } ], "statutes": [ { "type": "usc", "citation": "3 U.S.C. § 5", "count": 2 } ], "regulations": [] }, "externalLinks": ["https://www.law.cornell.edu/uscode/text/3/5"] } ``` ### Citation types | Type | Description | Example | | - | - | - | | `usReporter` | US Supreme Court | `531 U.S. 98` | | `federalReporter` | Federal Circuit Courts | `123 F.3d 456` | | `stateReporter` | State Courts | `123 Cal.App.4th 456` | | `usc` | US Code | `42 U.S.C. § 1983` | | `cfr` | Code of Federal Regulations | `29 C.F.R. § 1910.134` | *** ## Get full text Retrieve the full content of a legal document with optional highlights and summary. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/full-text ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/full-text \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 get-full-text \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" \ --highlight-query "equal protection" \ --max-characters 50000 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const doc = await client.legal.fullText({ url: 'https://www.courtlistener.com/opinion/118365/bush-v-gore/', highlightQuery: 'equal protection', maxCharacters: 50000 }); console.log(doc.title); console.log(`Length: ${doc.characterCount} chars`); // Relevant passages for (const highlight of doc.highlights) { console.log(`> ${highlight}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} doc = client.legal.v1.get_full_text( url='https://www.courtlistener.com/opinion/118365/bush-v-gore/', highlight_query='equal protection', max_characters=50000 ) print(doc.title) print(f'Length: {doc.character_count} chars') # Relevant passages for highlight in doc.highlights: print(f'> {highlight}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} doc, _ := client.Legal.V1.GetFullText(ctx, casedev.LegalV1GetFullTextParams{ URL: casedev.F("https://www.courtlistener.com/opinion/118365/bush-v-gore/"), HighlightQuery: casedev.F("equal protection"), MaxCharacters: casedev.F(int64(50000)), }) fmt.Println(doc.Title) fmt.Printf("Length: %d chars\n", doc.CharacterCount) // Relevant passages for _, highlight := range doc.Highlights { fmt.Printf("> %s\n", highlight) } ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `url` | string | URL of the legal document | | `maxCharacters` | number | Max characters to return (1,000-50,000, default 10,000) | | `highlightQuery` | string | Query to highlight relevant passages | | `summaryQuery` | string | Query to generate a focused summary | *** ## Resolve jurisdictions Convert jurisdiction names to IDs for filtering searches and verification. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/jurisdictions ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/jurisdictions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 list-jurisdictions --name california # Use in search casedev legal:v1 find \ --query "wrongful termination" \ --jurisdiction california ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.jurisdictions({ name: 'california' }); for (const j of result.jurisdictions) { console.log(`${j.name} (${j.id}) - ${j.level}`); } // California (california) - state // Use in search const cases = await client.legal.find({ query: 'wrongful termination', jurisdiction: 'california' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.list_jurisdictions(name='california') for j in result.jurisdictions: print(f'{j.name} ({j.id}) - {j.level}') # California (california) - state # Use in search cases = client.legal.v1.find( query='wrongful termination', jurisdiction='california' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.ListJurisdictions(ctx, casedev.LegalV1ListJurisdictionsParams{ Name: casedev.F("california"), }) for _, j := range result.Jurisdictions { fmt.Printf("%s (%s) - %s\n", j.Name, j.ID, j.Level) } // California (california) - state // Use in search cases, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F("wrongful termination"), Jurisdiction: casedev.F("california"), }) ``` ### Available jurisdictions | ID | Name | Level | | - | - | - | | `us-federal` | US Federal | Federal | | `us-scotus` | US Supreme Court | Federal | | `california` | California | State | | `new-york` | New York | State | | `texas` | Texas | State | | ... | All 50 states | State | *** ## Common patterns ### Verify AI output before display ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Verify the AI-generated text curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "AI generated citation text..." }' # If not found, search for a real alternative curl -X POST https://api.case.dev/legal/v1/find \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "extracted topic from text" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Verify AI-generated text casedev legal:v1 verify --text "AI generated citation text..." # If not found, search for a real alternative casedev legal:v1 find --query "extracted topic from text" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function safeDisplayCitation(aiGeneratedText: string) { const result = await client.legal.verify({ text: aiGeneratedText }); if (result.summary.notFound > 0) { // AI hallucinated — find a real alternative const search = await client.legal.find({ query: extractTopic(aiGeneratedText) }); return { warning: 'Citation corrected', cases: search.candidates }; } return { verified: true, citations: result.citations }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def safe_display_citation(ai_generated_text: str): result = client.legal.v1.verify(text=ai_generated_text) if result.summary.not_found > 0: # AI hallucinated — find a real alternative search = client.legal.v1.find(query=extract_topic(ai_generated_text)) return {"warning": "Citation corrected", "cases": search.candidates} return {"verified": True, "citations": result.citations} ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Verify the AI-generated text result, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F(aiGeneratedText), }) if result.Summary.NotFound > 0 { // AI hallucinated — find a real alternative search, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F(extractTopic(aiGeneratedText)), }) // Use search.Candidates as corrected results } // Otherwise, result.Citations contains verified citations ``` ### Build a citation checker ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/citations-from-url \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Extract all citations from the brief casedev legal:v1 get-citations-from-url \ --url "https://example.com/brief.pdf" # Verify each citation found casedev legal:v1 verify --text "531 U.S. 98" casedev legal:v1 verify --text "410 U.S. 113" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function checkBrief(documentUrl: string) { // Extract all citations from the brief const extracted = await client.legal.citationsFromUrl({ url: documentUrl }); // Verify each case citation const results = []; for (const cite of extracted.citations.cases) { const verification = await client.legal.verify({ text: cite.citation }); results.push({ citation: cite.citation, count: cite.count, verified: verification.summary.verified > 0 }); } return results; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def check_brief(document_url: str): # Extract all citations from the brief extracted = client.legal.v1.get_citations_from_url(url=document_url) # Verify each case citation results = [] for cite in extracted.citations.cases: verification = client.legal.v1.verify(text=cite.citation) results.append({ "citation": cite.citation, "count": cite.count, "verified": verification.summary.verified > 0, }) return results ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Extract all citations from the brief extracted, _ := client.Legal.V1.GetCitationsFromURL(ctx, casedev.LegalV1GetCitationsFromURLParams{ URL: casedev.F(documentURL), }) // Verify each case citation for _, cite := range extracted.Citations.Cases { verification, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F(cite.Citation), }) fmt.Printf("%s (×%d) — verified: %v\n", cite.Citation, cite.Count, verification.Summary.Verified > 0) } ``` ### Get full context for a verified citation ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Verify the citation curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "531 U.S. 98" }' # If verified, get full text with highlights curl -X POST https://api.case.dev/legal/v1/full-text \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://www.courtlistener.com/opinion/118365/bush-v-gore/", "highlightQuery": "holding" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Verify the citation casedev legal:v1 verify --text "531 U.S. 98" # If verified, get full text with highlights casedev legal:v1 get-full-text \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" \ --highlight-query "holding" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const verification = await client.legal.verify({ text: '531 U.S. 98' }); if (verification.citations[0].status === 'verified') { const fullDoc = await client.legal.fullText({ url: verification.citations[0].case.url, highlightQuery: 'holding' }); console.log(fullDoc.highlights); // Key passages about the holding } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} verification = client.legal.v1.verify(text='531 U.S. 98') if verification.citations[0].status == 'verified': full_doc = client.legal.v1.get_full_text( url=verification.citations[0].case.url, highlight_query='holding' ) print(full_doc.highlights) # Key passages about the holding ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} verification, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F("531 U.S. 98"), }) if verification.Citations[0].Status == "verified" { fullDoc, _ := client.Legal.V1.GetFullText(ctx, casedev.LegalV1GetFullTextParams{ URL: casedev.F(verification.Citations[0].Case.URL), HighlightQuery: casedev.F("holding"), }) fmt.Println(fullDoc.Highlights) // Key passages about the holding } ``` # Docket Search Source: https://docs.case.dev/legal-research/docket-search Search federal court dockets and filings Search federal court dockets or retrieve a specific docket with optional filing entries. Covers all federal district and appellate courts. Use `legal.listCourts()` to resolve court slugs for filtering. ## Search dockets ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/docket ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/docket \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "search", "query": "Apple v. Samsung", "court": "cand", "dateFiledAfter": "2020-01-01", "limit": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 docket ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const results = await client.legal.docket({ type: 'search', query: 'Apple v. Samsung', court: 'cand', // Northern District of California dateFiledAfter: '2020-01-01', limit: 10, }); console.log(`Found ${results.found} dockets`); for (const docket of results.dockets) { console.log(`${docket.caseName} (${docket.docketNumber})`); console.log(` Court: ${docket.court}`); console.log(` Filed: ${docket.dateFiled}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results = client.legal.v1.docket( type='search', query='Apple v. Samsung', court='cand', date_filed_after='2020-01-01', limit=10, ) print(f'Found {results.found} dockets') for docket in results.dockets: print(f'{docket.case_name} ({docket.docket_number})') print(f' Court: {docket.court}') print(f' Filed: {docket.date_filed}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response, _ := client.Legal.V1.Docket(ctx) fmt.Println(response) ``` ## Look up a docket Retrieve a specific docket by ID. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/docket \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "lookup", "docketId": "4214664" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 docket ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const docket = await client.legal.docket({ type: 'lookup', docketId: '4214664', }); console.log(`${docket.docket.caseName}`); console.log(`Court: ${docket.docket.court}`); console.log(`Assigned to: ${docket.docket.assignedTo}`); console.log(`Filed: ${docket.docket.dateFiled}`); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} docket = client.legal.v1.docket( type='lookup', docket_id='4214664', ) print(docket.docket.case_name) print(f'Court: {docket.docket.court}') print(f'Assigned to: {docket.docket.assigned_to}') print(f'Filed: {docket.docket.date_filed}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response, _ := client.Legal.V1.Docket(ctx) fmt.Println(response) ``` ## Look up docket entries Pass `includeEntries: true` in lookup mode to return the docket plus filing entries and attached RECAP document metadata. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/docket \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "lookup", "docketId": "4214664", "includeEntries": true, "limit": 10, "offset": 0 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 docket \ --type lookup \ --docket-id 4214664 \ --include-entries \ --limit 10 \ --offset 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const docket = await client.legal.docket({ type: 'lookup', docketId: '4214664', includeEntries: true, limit: 10, offset: 0, }); for (const entry of docket.entries ?? []) { console.log(`#${entry.entryNumber ?? 'n/a'} ${entry.date}: ${entry.description}`); for (const document of entry.documents) { console.log(` Document ${document.documentNumber}: ${document.pdfUrl ?? 'not available'}`); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} docket = client.legal.v1.docket( type='lookup', docket_id='4214664', include_entries=True, limit=10, offset=0, ) for entry in docket.entries or []: print(f'#{entry.entry_number or "n/a"} {entry.date}: {entry.description}') for document in entry.documents: print(f' Document {document.document_number}: {document.pdf_url or "not available"}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} docket, _ := client.Legal.V1.Docket(ctx, casedev.LegalV1DocketParams{ Type: casedev.F(casedev.LegalV1DocketParamsTypeLookup), DocketID: casedev.F("4214664"), IncludeEntries: casedev.F(true), Limit: casedev.F(int64(10)), Offset: casedev.F(int64(0)), }) for _, entry := range docket.Entries { fmt.Printf("#%v %s: %s\n", entry.EntryNumber, entry.Date, entry.Description) } ``` ## Live PACER fetch For dockets not yet in the RECAP archive, you can trigger a live fetch from PACER. This purchases fresh docket data using CaseMark's PACER account and ingests it into the RECAP archive. > [!WARNING] > > Live PACER fetches incur PACER fees of up to **\$3.00 per docket sheet**, plus a **\$0.05 service fee**. You must pass `acknowledgePacerFees: true` to confirm you accept these charges. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/docket \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "lookup", "docketId": "4214664", "live": true, "acknowledgePacerFees": true }' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const docket = await client.legal.docket({ type: 'lookup', docketId: '4214664', live: true, acknowledgePacerFees: true, }); console.log(`Fetched: ${docket.docket.caseName}`); console.log(`PACER fees: up to $${docket.pacerFees.maxPacerCost} + $${docket.pacerFees.serviceFee} service fee`); console.log(`Fetch took ${docket.pacerFees.fetchDurationMs}ms`); ``` ### How it works 1. The endpoint first tries to fetch the docket from the free RECAP archive 2. If `live: true`, it triggers a live PACER purchase to fetch fresh docket data 3. CaseMark's PACER account is used -- you don't need your own PACER credentials 4. The fetch typically takes 5-30 seconds depending on docket size 5. Once fetched, the docket is added to the RECAP archive and freely available for future lookups ### Cost and guardrails | Item | Cost | | - | - | | Service fee | \$0.05 per request | | PACER fee | Up to \$3.00 per docket sheet (PACER's cap) | | **Maximum total** | **\$3.05 per fetch** | Additional guardrails: * **Daily spend cap**: \$25/day per organization (resets at midnight UTC) * **Fee acknowledgment required**: Requests without `acknowledgePacerFees: true` return 400 * **Free tier users**: The standard \$10 free credit limit applies -- live fetches count toward it ### Live fetch response When `live: true`, the response includes a `pacerFees` object: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "type": "lookup", "live": true, "docket": { ... }, "pacerFees": { "serviceFee": 0.05, "maxPacerCost": 3.00, "currency": "USD", "fetchDurationMs": 12500 } } ``` ## Resolve court IDs Court slugs like `cand`, `nysd`, `ca9` identify specific courts. Use `legal.listCourts()` to search for the correct slug to pass as the `court` parameter in `legal.docket()`. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/courts ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/courts \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "northern district california", "jurisdiction": "FD" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 courts ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const courts = await client.legal.listCourts({ query: 'northern district california', jurisdiction: 'FD', // Federal District }); for (const court of courts.courts) { console.log(`${court.name} → ${court.id}`); // "U.S. District Court for the Northern District of California → cand" } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} courts = client.legal.v1.list_courts( query='northern district california', jurisdiction='FD', ) for court in courts.courts: print(f'{court.name} → {court.id}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response, _ := client.Legal.V1.ListCourts(ctx) fmt.Println(response) ``` ### Jurisdiction codes | Code | Jurisdiction | | - | - | | `F` | Federal (all) | | `FD` | Federal District | | `FB` | Federal Bankruptcy | | `FA` | Federal Appellate | | `FS` | Federal Special (e.g. Tax Court) | | `S` | State (all) | | `SA` | State Appellate | | `SS` | State Supreme | ## Parameters ### Docket search | Parameter | Type | Required | Description | | - | - | - | - | | `type` | `'search'` | Yes | Search mode | | `query` | `string` | Yes | Case name or party name (2-500 chars) | | `court` | `string` | No | Court slug (e.g. `cand`, `ca9`). Use `legal.listCourts()` to find slugs. | | `dateFiledAfter` | `string` | No | Lower bound filing date (YYYY-MM-DD) | | `dateFiledBefore` | `string` | No | Upper bound filing date (YYYY-MM-DD) | | `limit` | `integer` | No | Page size (1-100, default 25) | | `offset` | `integer` | No | Pagination offset (default 0) | ### Docket lookup | Parameter | Type | Required | Description | | - | - | - | - | | `type` | `'lookup'` | Yes | Lookup mode | | `docketId` | `string` | Yes | Docket ID | | `includeEntries` | `boolean` | No | Include docket entries/filings (default false). | | `live` | `boolean` | No | Trigger live PACER fetch (default false) | | `acknowledgePacerFees` | `boolean` | No | Required when `live: true` -- confirms PACER fee acceptance | | `limit` | `integer` | No | Entries page size (1-100, default 25) | | `offset` | `integer` | No | Entries pagination offset (default 0) | ### Courts lookup | Parameter | Type | Required | Description | | - | - | - | - | | `query` | `string` | No | Search court name (min 2 chars) | | `jurisdiction` | `string` | No | Filter by jurisdiction code | | `inUseOnly` | `boolean` | No | Only courts with docket data (default true) | | `limit` | `integer` | No | Page size (1-100, default 50) | | `offset` | `integer` | No | Pagination offset (default 0) | ## Response fields ### Docket object | Field | Type | Description | | - | - | - | | `id` | `string` | Docket ID | | `caseName` | `string` | Full case name | | `docketNumber` | `string` | Court docket number (e.g. `5:11-cv-01846`) | | `court` | `string` | Full court name | | `courtId` | `string` | Court slug | | `dateFiled` | `string` | Filing date | | `dateTerminated` | `string \| null` | Termination date | | `cause` | `string \| null` | Cause of action (e.g. `35 U.S.C. 271 Patent Infringement`) | | `natureOfSuit` | `string \| null` | Nature of suit classification | | `parties` | `string[]` | Party names | | `assignedTo` | `string \| null` | Assigned judge | | `url` | `string` | Docket detail URL | | `pacerCaseId` | `string \| null` | PACER case ID | ### Docket entry | Field | Type | Description | | - | - | - | | `entryNumber` | `integer` | Filing number on the docket | | `date` | `string` | Filing date | | `description` | `string` | Docket text (e.g. "COMPLAINT filed by Apple Inc.") | | `documents` | `array` | Attached RECAP documents | ### Document | Field | Type | Description | | - | - | - | | `id` | `string` | Document ID | | `documentNumber` | `string` | Document number | | `attachmentNumber` | `integer \| null` | Attachment number (null for main document) | | `description` | `string` | Document description | | `pdfUrl` | `string \| null` | PDF download URL (if available in RECAP) | | `pageCount` | `integer \| null` | Number of pages | | `isAvailable` | `boolean` | `true` = free via RECAP archive, `false` = requires PACER | ## Pricing | Method | Price | | - | - | | `legal.docket()` | Free | | `legal.listCourts()` | Free | ## Data source All docket data comes from [CourtListener's RECAP archive](https://free.law/recap/), which aggregates federal court filings contributed by the RECAP browser extension. Coverage includes: * All federal district courts * All federal appellate courts * Federal bankruptcy courts * Specialty courts (Tax Court, Court of Federal Claims, etc.) RECAP coverage varies by court and case. High-profile cases and active litigation tend to have the most complete filing histories. # Legal Research Overview Source: https://docs.case.dev/legal-research/index Search, analyze, and verify legal sources from authoritative databases Build legal research into your application. Search case law by topic, find similar authorities, verify citations, and retrieve full document text—all from authoritative sources. ## Capabilities Legal Research provides a complete toolkit for working with legal sources: | Capability | Method | What it does | | - | - | - | | **Search** | `legal.find()` | Find cases by topic or keyword | | **SEC filings** | `legal.secFiling()` | Search EDGAR filings or fetch company filing history | | **SEC financial data** | `legal.secXbrl()` | Get structured XBRL financial values for a company or across companies | | **Docket search** | `legal.docket()` | Search federal court dockets and filings | | **Court lookup** | `legal.listCourts()` | Resolve court names to CourtListener IDs | | **Patent search** | `legal.patentSearch()` | Search US patent applications and grants | | **Trademark lookup** | `legal.trademarkSearch()` | Look up US trademark status and details | | **Discover** | `legal.similar()` | Find semantically similar cases to a source | | **Verify** | `legal.verify()` | Confirm citations exist (catch hallucinations) | | **Parse** | `legal.citations()` | Extract Bluebook components from text | | **Extract** | `legal.citationsFromUrl()` | Pull all citations from a document URL | | **Retrieve** | `legal.fullText()` | Get full document content with highlights | | **Research** | `legal.research()` | Deep multi-query research with variations | | **Resolve** | `legal.jurisdictions()` | Convert jurisdiction names to IDs | These methods work together to create **credible legal workflows**—where every citation is verified and every source is retrievable. ## Quick start ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for cases curl -X POST https://api.case.dev/legal/v1/find \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"query": "qualified immunity excessive force"}' # Verify a citation curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"text": "531 U.S. 98"}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Search for cases on a topic casedev legal:v1 find \ --query "qualified immunity excessive force" \ --jurisdiction us-federal # Find similar cases to expand research casedev legal:v1 similar \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" \ --num-results 5 # Verify a citation before citing it casedev legal:v1 verify --text "531 U.S. 98" # Get full document text casedev legal:v1 get-full-text \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" \ --highlight-query "equal protection" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Search for cases on a topic const results = await client.legal.find({ query: 'qualified immunity excessive force', jurisdiction: 'us-federal', }); console.log(`Found ${results.found} cases`); for (const candidate of results.candidates) { console.log(`${candidate.title}: ${candidate.url}`); } // Find similar cases to expand research const similar = await client.legal.similar({ url: results.candidates[0].url, numResults: 5 }); // Verify a citation before citing it const verification = await client.legal.verify({ text: '531 U.S. 98' }); if (verification.summary.verified > 0) { const citation = verification.citations[0]; console.log(`Verified: ${citation.case.name}`); // "Bush v. Gore" } // Get full document text const doc = await client.legal.fullText({ url: 'https://www.courtlistener.com/opinion/118365/bush-v-gore/', highlightQuery: 'equal protection' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Search for cases on a topic results = client.legal.v1.find( query='qualified immunity excessive force', jurisdiction='us-federal', ) print(f'Found {results.found} cases') for candidate in results.candidates: print(f'{candidate.title}: {candidate.url}') # Find similar cases to expand research similar = client.legal.v1.similar( url=results.candidates[0].url, num_results=5 ) # Verify a citation before citing it verification = client.legal.v1.verify(text='531 U.S. 98') if verification.summary.verified > 0: citation = verification.citations[0] print(f'Verified: {citation.case.name}') # "Bush v. Gore" # Get full document text doc = client.legal.v1.get_full_text( url='https://www.courtlistener.com/opinion/118365/bush-v-gore/', highlight_query='equal protection' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev "github.com/CaseMark/casedev-go" // Search for cases on a topic results, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F("qualified immunity excessive force"), Jurisdiction: casedev.F("us-federal"), }) fmt.Printf("Found %d cases\n", results.Found) for _, candidate := range results.Candidates { fmt.Printf("%s: %s\n", candidate.Title, candidate.URL) } // Find similar cases to expand research similar, _ := client.Legal.V1.Similar(ctx, casedev.LegalV1SimilarParams{ URL: casedev.F(results.Candidates[0].URL), NumResults: casedev.F(int64(5)), }) // Verify a citation before citing it verification, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F("531 U.S. 98"), }) if verification.Summary.Verified > 0 { citation := verification.Citations[0] fmt.Printf("Verified: %s\n", citation.Case.Name) // "Bush v. Gore" } // Get full document text doc, _ := client.Legal.V1.GetFullText(ctx, casedev.LegalV1GetFullTextParams{ URL: casedev.F("https://www.courtlistener.com/opinion/118365/bush-v-gore/"), HighlightQuery: casedev.F("equal protection"), }) ``` ## Why verify citations? AI models hallucinate. They confidently cite "Smith v. Jones, 542 U.S. 123"—a case that doesn't exist. If your users trust those citations, they file briefs with fake authorities and face sanctions. Legal Research solves this by verifying every citation against authoritative databases: ```text theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} │ AI generates: "Miranda v. Arizona, 384 U.S. 436" │ │ ↓ │ │ legal.verify("384 U.S. 436") │ │ → status: "verified", case: "Miranda v. Arizona" │ │ ↓ │ │ Safe to cite with URL to authoritative source │ └─────────────────────────────────────────────────────────────────┘ ``` | Status | Meaning | Action | | - | - | - | | `verified` | Citation matches a real case | Safe to cite | | `not_found` | No match in database | Likely hallucination—search for alternatives | | `multiple_matches` | Multiple possible matches | Review candidates manually | ## Building credible workflows The real power comes from combining methods. Here's how to build a research workflow where every citation is verified and every source is retrievable: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Deep search with multiple query variations curl -X POST https://api.case.dev/legal/v1/research \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "topic", "additionalQueries": ["topic Supreme Court", "topic leading case"], "numResults": 15 }' # 2. Verify each candidate curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "Candidate Case Title" }' # 3. Expand research with similar cases curl -X POST https://api.case.dev/legal/v1/similar \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://www.courtlistener.com/opinion/...", "numResults": 5 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Deep search with multiple query variations casedev legal:v1 research \ --query "topic" \ --additional-query "topic Supreme Court" \ --additional-query "topic leading case" \ --num-results 15 # 2. Verify each candidate casedev legal:v1 verify --text "Candidate Case Title" # 3. Expand research with similar cases casedev legal:v1 similar \ --url "https://www.courtlistener.com/opinion/..." \ --num-results 5 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function researchWithVerification(topic: string) { // 1. Deep search with multiple query variations const research = await client.legal.research({ query: topic, additionalQueries: [ `${topic} Supreme Court`, `${topic} leading case`, ], numResults: 15 }); // 2. Verify each candidate before presenting to user const verified = []; for (const candidate of research.candidates) { const result = await client.legal.verify({ text: candidate.title }); if (result.summary.verified > 0) { verified.push({ ...candidate, citation: result.citations[0] }); } } // 3. Expand research with similar cases if (verified.length > 0) { const similar = await client.legal.similar({ url: verified[0].url, numResults: 5 }); return { primary: verified, related: similar.similarSources }; } return { primary: verified, related: [] }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def research_with_verification(topic: str): # 1. Deep search with multiple query variations research = client.legal.v1.research( query=topic, additional_queries=[ f"{topic} Supreme Court", f"{topic} leading case", ], num_results=15, ) # 2. Verify each candidate before presenting to user verified = [] for candidate in research.candidates: result = client.legal.v1.verify(text=candidate.title) if result.summary.verified > 0: verified.append({ **candidate, "citation": result.citations[0], }) # 3. Expand research with similar cases if verified: similar = client.legal.v1.similar( url=verified[0]["url"], num_results=5, ) return {"primary": verified, "related": similar.similar_sources} return {"primary": verified, "related": []} ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Deep search with multiple query variations research, _ := client.Legal.V1.Research(ctx, casedev.LegalV1ResearchParams{ Query: casedev.F(topic), AdditionalQueries: casedev.F([]string{ topic + " Supreme Court", topic + " leading case", }), NumResults: casedev.F(int64(15)), }) // 2. Verify each candidate before presenting to user var verified []Candidate for _, candidate := range research.Candidates { result, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F(candidate.Title), }) if result.Summary.Verified > 0 { verified = append(verified, candidate) } } // 3. Expand research with similar cases if len(verified) > 0 { similar, _ := client.Legal.V1.Similar(ctx, casedev.LegalV1SimilarParams{ URL: casedev.F(verified[0].URL), NumResults: casedev.F(int64(5)), }) // Use similar.SimilarSources as related cases } ``` This pattern ensures your users only see **real cases with working links**—never hallucinated authorities. ## Endpoints > [card] [find](/api-reference/legal/find-legal-sources) > > Search for cases by topic or keyword > [card] [similar](/api-reference/legal/find-similar-legal-sources) > > Find semantically similar cases to a source > [card] [verify](/api-reference/legal/verify-legal-citations) > > Verify citations against authoritative databases > [card] [citations](/api-reference/legal/parse-citations-from-text) > > Parse Bluebook citation components from text > [card] [citationsFromUrl](/api-reference/legal/extract-citations-from-url) > > Extract all citations from a document URL > [card] [fullText](/api-reference/legal/get-full-text-of-legal-document) > > Retrieve full document content with highlights > [card] [research](/api-reference/legal/deep-legal-research) > > Deep multi-query research with variations > [card] [docket](/api-reference/legal/search-federal-dockets-and-filings) > > Search federal court dockets and filings > [card] [listCourts](/api-reference/legal/list-court-listener-courts) > > Resolve court names to CourtListener IDs > [card] [patentSearch](/api-reference/legal/search-uspto-patent-applications) > > Search US patent applications and grants > [card] [trademarkSearch](/api-reference/legal/look-up-uspto-trademark-status) > > Look up US trademark status and details > [card] [jurisdictions](/api-reference/legal/resolve-jurisdiction) > > Resolve jurisdiction names to canonical IDs ## Supported sources Search and verification covers authoritative legal databases: | Source | Content | | - | - | | **CourtListener** | \~10M court opinions | | **Federal Courts** | Supreme Court, Circuit Courts, District Courts | | **State Courts** | All 50 states via regional reporters | | **Statutes** | US Code (USC) citations | | **Regulations** | Code of Federal Regulations (CFR) | | **Cornell Law** | Statutes, regulations, legal encyclopedias | ## Pricing | Method | Price | Use case | | - | - | - | | `legal.verify()` | Free | Verify AI-generated citations | | `legal.citations()` | Free | Parse citations from text | | `legal.jurisdictions()` | Free | Resolve jurisdiction names | | `legal.citationsFromUrl()` | \$0.01/request | Extract citations from document URL | | `legal.fullText()` | \$0.01/request | Retrieve document content | | `legal.find()` | \$0.01/request | Search for cases | | `legal.secFiling()` | Free | Search EDGAR filings and entity history | | `legal.secXbrl()` | Free | Structured XBRL financial data | | `legal.similar()` | \$0.01/request | Find related cases | | `legal.trademarkSearch()` | \$0.005/request | Look up trademark status | | `legal.docket()` | Free | Search dockets and retrieve filings | | `legal.listCourts()` | Free | Resolve court names to IDs | | `legal.research()` | \$0.05/request | Deep multi-query research | ## Next steps > [card] [Case Search](/legal-research/search) > > Find cases by topic and discover related authorities > [card] [SEC Filings](/legal-research/sec-filings) > > Search EDGAR full-text filings and company filing history > [card] [SEC XBRL Financial Data](/legal-research/sec-xbrl) > > Get structured financial values from SEC XBRL filings > [card] [Docket Search](/legal-research/docket-search) > > Search federal court dockets and filings > [card] [Patent Search](/legal-research/patent-search) > > Search US patent applications and granted patents > [card] [Trademark Search](/legal-research/trademark-search) > > Look up US trademark status and details > [card] [Citations](/legal-research/citations) > > Parse, verify, and extract legal citations ## Related services > [card] [LLMs](/llms) > > Combine legal research with AI for analysis and drafting > [card] [Vault](/vault) > > Store legal documents and build case-specific knowledge bases > [card] [Web Search](/web-search) > > Supplement legal research with general web search # Patent Search Source: https://docs.case.dev/legal-research/patent-search Search US patent applications and granted patents via the USPTO Search US patent applications and granted patents via the [USPTO Open Data Portal](https://data.uspto.gov/apis/patent-file-wrapper/search). Covers applications filed on or after January 1, 2001. Supports free-text queries, field-specific filters, date ranges, sorting, and pagination. ## Search patents ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/patent-search ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/patent-search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "neural network medical imaging", "assignee": "General Electric", "applicationType": "Utility", "filingDateFrom": "2018-01-01", "limit": 5, "sortBy": "filingDate", "sortOrder": "desc" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 patent-search \ --query "neural network medical imaging" \ --assignee "General Electric" \ --application-type Utility \ --filing-date-from 2018-01-01 \ --limit 5 \ --sort-by filingDate \ --sort-order desc ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.patentSearch({ query: 'neural network medical imaging', assignee: 'General Electric', applicationType: 'Utility', filingDateFrom: '2018-01-01', limit: 5, sortBy: 'filingDate', sortOrder: 'desc' }); console.log(`Found ${result.totalResults} patents`); for (const item of result.results) { console.log(`${item.title} (${item.applicationNumber})`); if (item.patentNumber) { console.log(` Patent: ${item.patentNumber}`); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.patent_search( query='neural network medical imaging', assignee='General Electric', application_type='Utility', filing_date_from='2018-01-01', limit=5, sort_by='filingDate', sort_order='desc' ) print(f'Found {result.total_results} patents') for item in result.results: print(f'{item.title} ({item.application_number})') if item.patent_number: print(f' Patent: {item.patent_number}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.PatentSearch(ctx, casedev.LegalV1PatentSearchParams{ Query: casedev.F("neural network medical imaging"), Assignee: casedev.F("General Electric"), ApplicationType: casedev.F("Utility"), FilingDateFrom: casedev.F("2018-01-01"), Limit: casedev.F(int64(5)), SortBy: casedev.F("filingDate"), SortOrder: casedev.F("desc"), }) fmt.Printf("Found %d patents\n", result.TotalResults) for _, item := range result.Results { fmt.Printf("%s (%s)\n", item.Title, item.ApplicationNumber) if item.PatentNumber != "" { fmt.Printf(" Patent: %s\n", item.PatentNumber) } } ``` ### Key parameters | Parameter | Type | Description | | - | - | - | | `query` | string | Free-text query or field-specific search (supports AND/OR/NOT) | | `applicationType` | string | Utility, Design, Plant, Provisional, Reissue | | `applicationStatus` | string | Filter by status (Patented Case, Pending, Abandoned) | | `assignee` | string | Filter by assignee/owner name | | `inventor` | string | Filter by inventor name | | `filingDateFrom` | string | Start of filing date range (YYYY-MM-DD) | | `filingDateTo` | string | End of filing date range (YYYY-MM-DD) | | `grantDateFrom` | string | Start of grant date range (YYYY-MM-DD) | | `grantDateTo` | string | End of grant date range (YYYY-MM-DD) | | `limit` | number | Results to return (max 100) | | `offset` | number | Pagination offset | See the [API reference](/api-reference/legal/search-uspto-patent-applications) for the full parameter and response schema. # Case Search Source: https://docs.case.dev/legal-research/search Find cases by topic and discover related authorities Search for legal sources by topic, find similar cases, and conduct deep research with multiple query variations. ## Find cases Search for legal sources including cases, statutes, and regulations from authoritative databases. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/find ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/find \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "qualified immunity excessive force police", "jurisdiction": "us-federal", "numResults": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 find \ --query "qualified immunity excessive force police" \ --jurisdiction us-federal \ --num-results 10 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.find({ query: 'qualified immunity excessive force police', jurisdiction: 'us-federal', numResults: 10 }); console.log(`Found ${result.found} candidates`); for (const candidate of result.candidates) { console.log(`${candidate.title}`); console.log(` ${candidate.url}`); console.log(` ${candidate.snippet.slice(0, 100)}...`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.find( query='qualified immunity excessive force police', jurisdiction='us-federal', num_results=10 ) print(f'Found {result.found} candidates') for candidate in result.candidates: print(f'{candidate.title}') print(f' {candidate.url}') print(f' {candidate.snippet[:100]}...') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F("qualified immunity excessive force police"), Jurisdiction: casedev.F("us-federal"), NumResults: casedev.F(int64(10)), }) fmt.Printf("Found %d candidates\n", result.Found) for _, candidate := range result.Candidates { fmt.Println(candidate.Title) fmt.Printf(" %s\n", candidate.URL) fmt.Printf(" %s...\n", candidate.Snippet[:100]) } ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `query` | string | Search query (3-1,000 characters) | | `jurisdiction` | string | Optional jurisdiction ID (e.g., `us-federal`, `california`) | | `numResults` | number | Results to return (1-25, default 10) | ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "query": "qualified immunity excessive force police", "jurisdiction": "us-federal", "found": 10, "candidates": [ { "url": "https://www.courtlistener.com/opinion/...", "title": "Harlow v. Fitzgerald, 457 U.S. 800 (1982)", "snippet": "Government officials performing discretionary functions are shielded from liability...", "source": "courtlistener.com", "publishedDate": "1982-06-24" } ], "hint": "IMPORTANT: Use legal.verify() on each candidate before citing." } ``` > [!WARNING] > > **Always verify before citing.** Search results are candidates, not verified sources. Use `legal.verify()` to confirm each citation exists in the database before your user cites it. *** ## Find similar cases Given a legal document URL, find semantically similar sources. Useful for expanding research or finding citing cases. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/similar ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/similar \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://www.courtlistener.com/opinion/118365/bush-v-gore/", "numResults": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 similar \ --url "https://www.courtlistener.com/opinion/118365/bush-v-gore/" \ --num-results 10 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.similar({ url: 'https://www.courtlistener.com/opinion/118365/bush-v-gore/', numResults: 10 }); console.log(`Found ${result.found} similar sources`); for (const source of result.similarSources) { console.log(`${source.title}`); console.log(` ${source.url}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.similar( url='https://www.courtlistener.com/opinion/118365/bush-v-gore/', num_results=10 ) print(f'Found {result.found} similar sources') for source in result.similar_sources: print(f'{source.title}') print(f' {source.url}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.Similar(ctx, casedev.LegalV1SimilarParams{ URL: casedev.F("https://www.courtlistener.com/opinion/118365/bush-v-gore/"), NumResults: casedev.F(int64(10)), }) fmt.Printf("Found %d similar sources\n", result.Found) for _, source := range result.SimilarSources { fmt.Println(source.Title) fmt.Printf(" %s\n", source.URL) } ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `url` | string | URL of the source document | | `jurisdiction` | string | Optional jurisdiction filter | | `numResults` | number | Results to return (1-25, default 10) | | `startPublishedDate` | string | Only include sources after this date (ISO format) | ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "sourceUrl": "https://www.courtlistener.com/opinion/118365/bush-v-gore/", "jurisdiction": "all", "found": 10, "similarSources": [ { "url": "https://www.courtlistener.com/opinion/...", "title": "Reynolds v. Sims, 377 U.S. 533 (1964)", "snippet": "The Equal Protection Clause requires substantially equal legislative representation...", "source": "courtlistener.com", "publishedDate": "1964-06-15" } ] } ``` *** ## Deep research Conduct comprehensive research with multiple query variations. Uses advanced search to find sources across different phrasings of the legal issue. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/research ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/research \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "employment discrimination disparate impact", "additionalQueries": [ "Title VII disparate impact theory", "Griggs v Duke Power significance" ], "numResults": 15 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 research \ --query "employment discrimination disparate impact" \ --additional-query "Title VII disparate impact theory" \ --additional-query "Griggs v Duke Power significance" \ --additional-query "statistical evidence employment discrimination" \ --jurisdiction us-federal \ --num-results 15 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.research({ query: 'employment discrimination disparate impact', additionalQueries: [ 'Title VII disparate impact theory', 'Griggs v Duke Power significance', 'statistical evidence employment discrimination' ], jurisdiction: 'us-federal', numResults: 15 }); console.log(`Deep search found ${result.found} sources`); for (const candidate of result.candidates) { console.log(`${candidate.title}`); // Deep search includes highlighted passages if (candidate.highlights?.length > 0) { console.log(` Key passage: "${candidate.highlights[0]}"`); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.research( query='employment discrimination disparate impact', additional_queries=[ 'Title VII disparate impact theory', 'Griggs v Duke Power significance', 'statistical evidence employment discrimination' ], jurisdiction='us-federal', num_results=15 ) print(f'Deep search found {result.found} sources') for candidate in result.candidates: print(f'{candidate.title}') # Deep search includes highlighted passages if candidate.highlights: print(f' Key passage: "{candidate.highlights[0]}"') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.Research(ctx, casedev.LegalV1ResearchParams{ Query: casedev.F("employment discrimination disparate impact"), AdditionalQueries: casedev.F([]string{ "Title VII disparate impact theory", "Griggs v Duke Power significance", "statistical evidence employment discrimination", }), Jurisdiction: casedev.F("us-federal"), NumResults: casedev.F(int64(15)), }) fmt.Printf("Deep search found %d sources\n", result.Found) for _, candidate := range result.Candidates { fmt.Println(candidate.Title) // Deep search includes highlighted passages if len(candidate.Highlights) > 0 { fmt.Printf(" Key passage: \"%s\"\n", candidate.Highlights[0]) } } ``` ### Parameters | Parameter | Type | Description | | - | - | - | | `query` | string | Primary search query | | `additionalQueries` | string\[] | Up to 5 alternative phrasings | | `jurisdiction` | string | Optional jurisdiction filter | | `numResults` | number | Results to return (1-25, default 10) | ### Response ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "query": "employment discrimination disparate impact", "additionalQueries": ["Title VII disparate impact theory", "..."], "jurisdiction": "us-federal", "searchType": "deep", "found": 15, "candidates": [ { "url": "https://www.courtlistener.com/opinion/...", "title": "Griggs v. Duke Power Co., 401 U.S. 424 (1971)", "snippet": "The Act proscribes not only overt discrimination but also practices...", "highlights": [ "Congress directed the thrust of the Act to the consequences of employment practices", "The touchstone is business necessity" ], "source": "courtlistener.com", "publishedDate": "1971-03-08" } ] } ``` ### When to use deep research | Scenario | Use | | - | - | | Quick case lookup | `legal.find()` | | Thorough brief research | `legal.research()` with query variations | | Finding all related cases | `legal.similar()` from a key case | *** ## Common patterns ### Research workflow ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Deep search with variations curl -X POST https://api.case.dev/legal/v1/research \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "topic", "additionalQueries": ["variation 1", "variation 2"], "jurisdiction": "us-federal", "numResults": 20 }' # 2. Verify top candidates curl -X POST https://api.case.dev/legal/v1/verify \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "text": "Candidate Title, 457 U.S. 800" }' # 3. Find similar cases to the best result curl -X POST https://api.case.dev/legal/v1/similar \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://www.courtlistener.com/opinion/...", "numResults": 5 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Deep search with variations casedev legal:v1 research \ --query "topic" \ --additional-query "variation 1" \ --additional-query "variation 2" \ --jurisdiction us-federal \ --num-results 20 # 2. Verify top candidates casedev legal:v1 verify --text "Candidate Title, 457 U.S. 800" # 3. Find similar cases to the best result casedev legal:v1 similar \ --url "https://www.courtlistener.com/opinion/..." \ --num-results 5 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function researchTopic(topic: string, jurisdiction?: string) { // 1. Deep search with variations const research = await client.legal.research({ query: topic, additionalQueries: generateVariations(topic), jurisdiction, numResults: 20 }); // 2. Verify top candidates const verified = []; for (const candidate of research.candidates.slice(0, 10)) { const result = await client.legal.verify({ text: candidate.title }); if (result.summary.verified > 0) { verified.push({ ...candidate, verification: result.citations[0] }); } } // 3. Find similar cases to the best result if (verified.length > 0) { const similar = await client.legal.similar({ url: verified[0].url, numResults: 5 }); return { primary: verified, related: similar.similarSources }; } return { primary: verified, related: [] }; } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def research_topic(topic: str, jurisdiction: str = None): # 1. Deep search with variations research = client.legal.v1.research( query=topic, additional_queries=generate_variations(topic), jurisdiction=jurisdiction, num_results=20, ) # 2. Verify top candidates verified = [] for candidate in research.candidates[:10]: result = client.legal.v1.verify(text=candidate.title) if result.summary.verified > 0: verified.append({ **candidate, "verification": result.citations[0], }) # 3. Find similar cases to the best result if verified: similar = client.legal.v1.similar( url=verified[0]["url"], num_results=5, ) return {"primary": verified, "related": similar.similar_sources} return {"primary": verified, "related": []} ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Deep search with variations research, _ := client.Legal.V1.Research(ctx, casedev.LegalV1ResearchParams{ Query: casedev.F(topic), AdditionalQueries: casedev.F(generateVariations(topic)), Jurisdiction: casedev.F(jurisdiction), NumResults: casedev.F(int64(20)), }) // 2. Verify top candidates var verified []Candidate for _, candidate := range research.Candidates[:10] { result, _ := client.Legal.V1.Verify(ctx, casedev.LegalV1VerifyParams{ Text: casedev.F(candidate.Title), }) if result.Summary.Verified > 0 { verified = append(verified, candidate) } } // 3. Find similar cases to the best result if len(verified) > 0 { similar, _ := client.Legal.V1.Similar(ctx, casedev.LegalV1SimilarParams{ URL: casedev.F(verified[0].URL), NumResults: casedev.F(int64(5)), }) // Use similar.SimilarSources as related cases } ``` ### Build a case timeline ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Find the seed case curl -X POST https://api.case.dev/legal/v1/find \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "seed case topic", "numResults": 1 }' # Find similar cases across time curl -X POST https://api.case.dev/legal/v1/similar \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "url": "https://www.courtlistener.com/opinion/...", "numResults": 25 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Find the seed case casedev legal:v1 find --query "seed case topic" --num-results 1 # Find similar cases across time (use the URL from above) casedev legal:v1 similar \ --url "https://www.courtlistener.com/opinion/..." \ --num-results 25 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function buildTimeline(seedCase: string) { // Find the seed case const search = await client.legal.find({ query: seedCase, numResults: 1 }); const seedUrl = search.candidates[0].url; // Find similar cases across time const similar = await client.legal.similar({ url: seedUrl, numResults: 25 }); // Sort by date return similar.similarSources .filter(s => s.publishedDate) .sort((a, b) => new Date(a.publishedDate) - new Date(b.publishedDate)); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} def build_timeline(seed_case: str): # Find the seed case search = client.legal.v1.find(query=seed_case, num_results=1) seed_url = search.candidates[0].url # Find similar cases across time similar = client.legal.v1.similar(url=seed_url, num_results=25) # Sort by date sources = [s for s in similar.similar_sources if s.published_date] sources.sort(key=lambda s: s.published_date) return sources ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Find the seed case search, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F(seedCase), NumResults: casedev.F(int64(1)), }) seedURL := search.Candidates[0].URL // Find similar cases across time similar, _ := client.Legal.V1.Similar(ctx, casedev.LegalV1SimilarParams{ URL: casedev.F(seedURL), NumResults: casedev.F(int64(25)), }) // Sort similar.SimilarSources by PublishedDate sort.Slice(similar.SimilarSources, func(i, j int) bool { return similar.SimilarSources[i].PublishedDate < similar.SimilarSources[j].PublishedDate }) ``` ### Jurisdiction-specific research ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/find \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "your query", "jurisdiction": "us-federal", "numResults": 5 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Research across multiple jurisdictions casedev legal:v1 find --query "your query" --jurisdiction us-federal --num-results 5 casedev legal:v1 find --query "your query" --jurisdiction california --num-results 5 casedev legal:v1 find --query "your query" --jurisdiction new-york --num-results 5 casedev legal:v1 find --query "your query" --jurisdiction texas --num-results 5 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Research across multiple jurisdictions async function multiJurisdictionSearch(query: string) { const jurisdictions = ['us-federal', 'california', 'new-york', 'texas']; const results = await Promise.all( jurisdictions.map(j => client.legal.find({ query, jurisdiction: j, numResults: 5 }) ) ); return jurisdictions.map((j, i) => ({ jurisdiction: j, cases: results[i].candidates })); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Research across multiple jurisdictions def multi_jurisdiction_search(query: str): jurisdictions = ['us-federal', 'california', 'new-york', 'texas'] results = [] for j in jurisdictions: result = client.legal.v1.find( query=query, jurisdiction=j, num_results=5 ) results.append({"jurisdiction": j, "cases": result.candidates}) return results ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Research across multiple jurisdictions jurisdictions := []string{"us-federal", "california", "new-york", "texas"} for _, j := range jurisdictions { result, _ := client.Legal.V1.Find(ctx, casedev.LegalV1FindParams{ Query: casedev.F(query), Jurisdiction: casedev.F(j), NumResults: casedev.F(int64(5)), }) fmt.Printf("%s: %d cases\n", j, result.Found) } ``` ## Supported sources Search covers authoritative legal databases: | Source | Content | | - | - | | CourtListener | \~10M court opinions | | Cornell Law | Statutes, regulations, legal encyclopedias | | Supreme Court | All SCOTUS opinions | | govinfo.gov | Federal Register, CFR, USC | | State courts | Via regional reporters | # SEC Filings Source: https://docs.case.dev/legal-research/sec-filings Search EDGAR full-text filings and fetch per-entity SEC filing history Search SEC EDGAR filings with a single legal research primitive. `legal.secFiling()` supports both full-text filing search via `efts.sec.gov` and structured company filing history via `data.sec.gov`. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/sec-filing ``` ## Full-text filing search Use `type: 'search'` to search across the text of filings and exhibits. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/sec-filing \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "search", "query": "\"material weakness\" internal controls", "formTypes": ["10-K", "10-Q"], "ticker": "AAPL", "dateAfter": "2020-01-01", "dateBefore": "2025-01-01", "limit": 10, "offset": 0 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 sec-filing \ --type search \ --query '"material weakness" internal controls' \ --form-type 10-K \ --form-type 10-Q \ --ticker AAPL \ --date-after 2020-01-01 \ --date-before 2025-01-01 \ --limit 10 \ --offset 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.secFiling({ type: 'search', query: '"material weakness" internal controls', formTypes: ['10-K', '10-Q'], ticker: 'AAPL', dateAfter: '2020-01-01', dateBefore: '2025-01-01', limit: 10, offset: 0, }); console.log(result.total); console.log(result.filings[0].snippet); console.log(result.filings[0].documents[0].url); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.sec_filing( type='search', query='"material weakness" internal controls', form_types=['10-K', '10-Q'], ticker='AAPL', date_after='2020-01-01', date_before='2025-01-01', limit=10, offset=0, ) print(result.total) print(result.filings[0].snippet) print(result.filings[0].documents[0].url) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.SecFiling(ctx, casedev.LegalV1SecFilingParams{ Type: casedev.F(casedev.LegalV1SecFilingParamsTypeSearch), Query: casedev.F("\"material weakness\" internal controls"), FormTypes: casedev.F([]string{"10-K", "10-Q"}), Ticker: casedev.F("AAPL"), DateAfter: casedev.F("2020-01-01"), DateBefore: casedev.F("2025-01-01"), Limit: casedev.F(int64(10)), Offset: casedev.F(int64(0)), }) ``` ## Entity filing history Use `type: 'entity'` when you already know the filer by CIK or ticker. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/sec-filing \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "entity", "ticker": "AAPL", "formTypes": ["10-K", "8-K"], "dateAfter": "2022-01-01", "limit": 20, "offset": 0 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 sec-filing \ --type entity \ --ticker AAPL \ --form-type 10-K \ --form-type 8-K \ --date-after 2022-01-01 \ --limit 20 \ --offset 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.secFiling({ type: 'entity', ticker: 'AAPL', formTypes: ['10-K', '8-K'], dateAfter: '2022-01-01', limit: 20, offset: 0, }); console.log(result.cik); console.log(result.filings[0].secUrl); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.sec_filing( type='entity', ticker='AAPL', form_types=['10-K', '8-K'], date_after='2022-01-01', limit=20, offset=0, ) print(result.cik) print(result.filings[0].sec_url) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.SecFiling(ctx, casedev.LegalV1SecFilingParams{ Type: casedev.F(casedev.LegalV1SecFilingParamsTypeEntity), Ticker: casedev.F("AAPL"), FormTypes: casedev.F([]string{"10-K", "8-K"}), DateAfter: casedev.F("2022-01-01"), Limit: casedev.F(int64(20)), Offset: casedev.F(int64(0)), }) ``` ## Response fields * `total`: total filings matching the request * `filings[].accessionNumber`: SEC accession number for the filing * `filings[].documents[]`: direct `sec.gov/Archives` URLs for the matched or primary filing document * `filings[].snippet`: highlighted text excerpt from the SEC full-text search result; `null` for `type: 'entity'` * `filings[].secUrl`: canonical EDGAR filing index page ## Notes * `type: 'search'` uses SEC full-text search and supports boolean queries, phrases, and exhibit matches. * `type: 'entity'` uses the filer submissions API and resolves tickers to CIKs automatically. * `formTypes` passes through directly to the SEC APIs; no restricted enum is enforced. * `limit` is capped at `100` and `offset` uses standard offset pagination. * This endpoint is free and uses only SEC-operated infrastructure. * Need financial values rather than filing documents? Use [SEC XBRL Financial Data](/legal-research/sec-xbrl) for net income, assets, shares outstanding, and other reported line items. # SEC XBRL Financial Data Source: https://docs.case.dev/legal-research/sec-xbrl Structured financial values from SEC XBRL filings — one line item over time, a company's full concept catalog, or one concept across all companies Get the numbers, not the documents. `legal.v1.secXbrl()` wraps the SEC's XBRL APIs on `data.sec.gov` and returns normalized financial facts (net income, assets, shares outstanding, and so on) with a link back to the source filing. To find and read filings, use [SEC Filings](/legal-research/sec-filings) instead. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/sec-xbrl ``` | `type` | Use it to | SEC API wrapped | | - | - | - | | `concept` | Get one line item for one company over time | `/api/xbrl/companyconcept` | | `facts` | List every concept a company reports, or pull several at once | `/api/xbrl/companyfacts` | | `frames` | Compare one concept across all reporting companies for a period | `/api/xbrl/frames` | ## One line item over time (`concept`) Provide exactly one of `cik` or `ticker`, a `tag`, and optionally a `taxonomy` (default `us-gaap`; also `ifrs-full`, `dei`, `srt`). ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/sec-xbrl \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "concept", "ticker": "AAPL", "taxonomy": "us-gaap", "tag": "NetIncomeLoss", "formTypes": ["10-K"], "limit": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 sec-xbrl \ --type concept \ --ticker AAPL \ --taxonomy us-gaap \ --tag NetIncomeLoss \ --form-type 10-K \ --limit 10 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.v1.secXbrl({ type: 'concept', ticker: 'AAPL', taxonomy: 'us-gaap', tag: 'NetIncomeLoss', formTypes: ['10-K'], limit: 10, }) console.log(result.label) const fact = result.facts?.[0] if (fact) { console.log(fact.value, fact.end) console.log(fact.secUrl) } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.sec_xbrl( type='concept', ticker='AAPL', taxonomy='us-gaap', tag='NetIncomeLoss', form_types=['10-K'], limit=10, ) print(result.label) print(result.facts[0].value, result.facts[0].end) print(result.facts[0].sec_url) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.SecXbrl(ctx, casedev.LegalV1SecXbrlParams{ Type: casedev.F(casedev.LegalV1SecXbrlParamsTypeConcept), Ticker: casedev.F("AAPL"), Taxonomy: casedev.F(casedev.LegalV1SecXbrlParamsTaxonomyUsGaap), Tag: casedev.F("NetIncomeLoss"), FormTypes: casedev.F([]string{"10-K"}), Limit: casedev.F(int64(10)), }) ``` Optional filters: `unit` (for example `USD`, `shares`, `USD/shares`), `formTypes`, `fiscalPeriods` (`FY`, `Q1`, `Q2`, `Q3`), and `dateAfter` / `dateBefore`, which filter on the fact's period end date. ## A company's concepts (`facts`) Company fact payloads can be tens of MB for large filers, so `facts` has two modes: * **Without `concepts`**, it returns a catalog only: each concept's taxonomy, tag, label, available units, fact count, and latest period end date. No values. Use `taxonomy` to narrow the catalog. * **With `concepts`** (an array of `taxonomy:tag` strings, or bare tags that default to `us-gaap`), it returns normalized facts for just those concepts. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Catalog curl -X POST https://api.case.dev/legal/v1/sec-xbrl \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "facts", "ticker": "AAPL", "taxonomy": "us-gaap", "limit": 25 }' # Values for specific concepts curl -X POST https://api.case.dev/legal/v1/sec-xbrl \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "facts", "ticker": "AAPL", "concepts": ["NetIncomeLoss", "Assets"], "fiscalPeriods": ["FY"] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Catalog casedev legal:v1 sec-xbrl --type facts --ticker AAPL --taxonomy us-gaap --limit 25 # Values for specific concepts casedev legal:v1 sec-xbrl \ --type facts \ --ticker AAPL \ --concept NetIncomeLoss \ --concept Assets \ --fiscal-period FY ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const catalog = await client.legal.v1.secXbrl({ type: 'facts', ticker: 'AAPL', taxonomy: 'us-gaap', limit: 25, }) const concept = catalog.concepts?.[0] if (concept) console.log(concept.tag, concept.factCount) const values = await client.legal.v1.secXbrl({ type: 'facts', ticker: 'AAPL', concepts: ['NetIncomeLoss', 'Assets'], fiscalPeriods: ['FY'], }) const fact = values.facts?.[0] if (fact) console.log(fact.value) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} catalog = client.legal.v1.sec_xbrl( type='facts', ticker='AAPL', taxonomy='us-gaap', limit=25, ) print(catalog.concepts[0].tag, catalog.concepts[0].fact_count) values = client.legal.v1.sec_xbrl( type='facts', ticker='AAPL', concepts=['NetIncomeLoss', 'Assets'], fiscal_periods=['FY'], ) print(values.facts[0].value) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} catalog, _ := client.Legal.V1.SecXbrl(ctx, casedev.LegalV1SecXbrlParams{ Type: casedev.F(casedev.LegalV1SecXbrlParamsTypeFacts), Ticker: casedev.F("AAPL"), Taxonomy: casedev.F(casedev.LegalV1SecXbrlParamsTaxonomyUsGaap), Limit: casedev.F(int64(25)), }) values, _ := client.Legal.V1.SecXbrl(ctx, casedev.LegalV1SecXbrlParams{ Type: casedev.F(casedev.LegalV1SecXbrlParamsTypeFacts), Ticker: casedev.F("AAPL"), Concepts: casedev.F([]string{"NetIncomeLoss", "Assets"}), FiscalPeriods: casedev.F([]casedev.LegalV1SecXbrlParamsFiscalPeriod{casedev.LegalV1SecXbrlParamsFiscalPeriodFy}), }) ``` ## One concept across companies (`frames`) `frames` returns one concept for every company that reported it in one calendar period. Provide `tag` and `period`; `taxonomy` defaults to `us-gaap` and `unit` to `USD`. `period` must match `CY####`, `CY####Q#`, or `CY####Q#I`: | Period | Meaning | | - | - | | `CY2024` | Annual duration | | `CY2024Q1` | Quarterly duration | | `CY2024Q1I` | Instantaneous point in time (balance sheet items) | Callers pass ratio units as `USD/shares`; the endpoint converts them to the SEC's `USD-per-shares` form. Use `ciks` or `tickers` to restrict the results to a peer set (CLI: repeated `--peer-cik` or `--peer-ticker` flags), and `sort` (`value_desc` default, or `value_asc`). ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/sec-xbrl \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "frames", "taxonomy": "us-gaap", "tag": "AccountsPayableCurrent", "unit": "USD", "period": "CY2019Q1I", "tickers": ["AAPL", "MSFT"], "sort": "value_desc", "limit": 10 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 sec-xbrl \ --type frames \ --taxonomy us-gaap \ --tag AccountsPayableCurrent \ --unit USD \ --period CY2019Q1I \ --peer-ticker AAPL \ --peer-ticker MSFT \ --sort value_desc \ --limit 10 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.v1.secXbrl({ type: 'frames', taxonomy: 'us-gaap', tag: 'AccountsPayableCurrent', unit: 'USD', period: 'CY2019Q1I', tickers: ['AAPL', 'MSFT'], sort: 'value_desc', limit: 10, }) console.log(result.total) const peer = result.data?.[0] if (peer) console.log(peer.entityName, peer.value, peer.loc) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.sec_xbrl( type='frames', taxonomy='us-gaap', tag='AccountsPayableCurrent', unit='USD', period='CY2019Q1I', tickers=['AAPL', 'MSFT'], sort='value_desc', limit=10, ) print(result.total) print(result.data[0].entity_name, result.data[0].value, result.data[0].loc) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.SecXbrl(ctx, casedev.LegalV1SecXbrlParams{ Type: casedev.F(casedev.LegalV1SecXbrlParamsTypeFrames), Taxonomy: casedev.F(casedev.LegalV1SecXbrlParamsTaxonomyUsGaap), Tag: casedev.F("AccountsPayableCurrent"), Unit: casedev.F("USD"), Period: casedev.F("CY2019Q1I"), Tickers: casedev.F([]string{"AAPL", "MSFT"}), Sort: casedev.F(casedev.LegalV1SecXbrlParamsSortValueDesc), Limit: casedev.F(int64(10)), }) ``` ## Response fields Every fact row has the same shape: * `taxonomy`, `tag`, `label`, `unit`: what was measured * `value`: the reported number * `start`: period start date; `null` for instantaneous facts * `end`: period end date * `fiscalYear`, `fiscalPeriod`, `form`, `filed`: the filing the fact came from (`null` on `frames` rows, which the SEC does not return these for) * `accessionNumber`: SEC accession number of the filing * `frame`: the SEC calendar frame (for example `CY2024Q1I`), `null` if not assigned * `cik`, `entityName`: the reporting company * `secUrl`: EDGAR filing index page for the source filing * `loc`: reporting company location code (`frames` only) Top level: * `total`: rows matching before pagination * `cik`, `ticker`, `entityName`: the resolved company (`concept` and `facts`) * `label`, `description`: the concept's definition (`concept` and `frames`) * `facts[]`: fact rows (`concept`, and `facts` when `concepts` is set) * `concepts[]`: the catalog, with `taxonomy`, `tag`, `label`, `units`, `factCount`, `latestPeriodEnd` (`facts` without `concepts`) * `data[]`: fact rows, one per reporting company (`frames`) ## Deduplication A value is re-reported in later filings as a prior-period comparative, so the raw SEC data contains many duplicates of the same fact. With `dedupe: true` (the default) for `concept` and `facts`, only facts that carry a `frame` are returned. The `frame` is the SEC's own canonical assignment of one fact per calendar period, so this gives you one row per period. Set `dedupe: false` to get every reported fact, including comparatives. `frames` results are already one canonical fact per company. ## Notes * Use `type: 'concept'` or `type: 'facts'` with a ticker or CIK; tickers resolve to CIKs automatically, as with SEC Filings. * An unknown ticker returns `404` with code `TICKER_NOT_FOUND`. A company with no XBRL data, or that does not report the requested concept, frame, or unit, returns `404` with code `XBRL_NOT_FOUND` and a message naming the CIK and concept. An invalid `period`, `unit`, or `taxonomy` returns `400`. * `limit` is capped at `100` and `offset` uses standard offset pagination. * Company data is cached for up to 15 minutes, since `data.sec.gov` updates throughout the day. Frames for closed periods are cached for up to 24 hours. Filters are applied after the fetch, so repeated queries are fast. * SEC rate limits are shared with the SEC Filings endpoint. * This endpoint is free and uses only SEC-operated infrastructure. ## Coverage and batch behavior The SEC XBRL APIs aggregate standard-taxonomy facts that apply to the whole filing entity. Custom-taxonomy and segment facts are outside this API. Use `sec-filing` for company metadata and filing documents. These endpoints retrieve public data; submission of Form D or other filings is a separate EDGAR workflow. A selected-concepts `facts` request is all-or-nothing: if any requested concept is missing, the response is `404 XBRL_NOT_FOUND` listing every missing concept. Query the catalog first when assembling a company's concept list. Array filters must contain non-empty strings, including CIKs (for example, `"320193"`). Invalid entries and impossible calendar dates return `400 VALIDATION_ERROR`. Raw SEC payloads are cached per process with a 20 MiB estimated parsed-memory budget and at most 12 entries. Oversized responses are served without retention; least recently used entries are evicted to make room. The budget estimates object and string storage rather than guaranteeing the worker's total heap usage. # Trademark Search Source: https://docs.case.dev/legal-research/trademark-search Look up US trademark status and details via the USPTO TSDR system Look up US trademark applications and registrations via the [USPTO Trademark Status & Document Retrieval (TSDR)](https://tsdr.uspto.gov/) system. Supports lookup by serial number or registration number. Returns mark text, owner, goods/services, Nice classes, filing/registration dates, attorney of record, and mark images. ## Look up a trademark ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /legal/v1/trademark-search ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/trademark-search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "serialNumber": "97123456" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 trademark-search \ --serial-number 97123456 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Look up by serial number const result = await client.legal.trademarkSearch({ serialNumber: '97123456', }); console.log(`${result.markText} — ${result.status}`); console.log(`Owner: ${result.owner?.name}`); console.log(`Classes: ${result.niceClasses.join(', ')}`); for (const gs of result.goodsAndServices) { console.log(` Class ${gs.classNumber}: ${gs.description}`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Look up by serial number result = client.legal.v1.trademark_search( serial_number='97123456' ) print(f'{result.mark_text} — {result.status}') print(f'Owner: {result.owner.name}') print(f'Classes: {", ".join(str(c) for c in result.nice_classes)}') for gs in result.goods_and_services: print(f' Class {gs.class_number}: {gs.description}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.TrademarkSearch(ctx, casedev.LegalV1TrademarkSearchParams{ SerialNumber: casedev.F("97123456"), }) fmt.Printf("%s — %s\n", result.MarkText, result.Status) fmt.Printf("Owner: %s\n", result.Owner.Name) for _, gs := range result.GoodsAndServices { fmt.Printf(" Class %s: %s\n", gs.ClassNumber, gs.Description) } ``` You can also look up by registration number: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/legal/v1/trademark-search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"registrationNumber": "6789012"}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev legal:v1 trademark-search \ --registration-number 6789012 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.legal.trademarkSearch({ registrationNumber: '6789012', }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.legal.v1.trademark_search( registration_number='6789012' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Legal.V1.TrademarkSearch(ctx, casedev.LegalV1TrademarkSearchParams{ RegistrationNumber: casedev.F("6789012"), }) ``` ### Key parameters | Parameter | Type | Description | | - | - | - | | `serialNumber` | string | USPTO serial number (e.g. "97123456") | | `registrationNumber` | string | USPTO registration number (e.g. "6789012") | > [!NOTE] > > Provide either `serialNumber` or `registrationNumber`. If both are provided, `serialNumber` takes precedence. ### Response fields | Field | Type | Description | | - | - | - | | `serialNumber` | string | USPTO serial number | | `registrationNumber` | string \| null | Registration number (if registered) | | `markText` | string \| null | Text of the trademark | | `markType` | string \| null | Type (Standard Character Mark, Design Mark, etc.) | | `status` | string \| null | Current status (Registered, Pending, Abandoned, etc.) | | `statusDate` | string \| null | Date of most recent status update | | `filingDate` | string \| null | Filing date | | `registrationDate` | string \| null | Registration date | | `owner` | object \| null | Owner name, address, and entity type | | `attorney` | string \| null | Attorney of record | | `goodsAndServices` | array | Goods/services with class numbers | | `niceClasses` | number\[] | Nice classification class numbers | | `imageUrl` | string \| null | URL to the mark image | | `usptoUrl` | string | Canonical TSDR link | See the [API reference](/api-reference/legal/look-up-uspto-trademark-status) for the full response schema. # Events and messages Source: https://docs.case.dev/linc/events Stream live Linc activity and replay durable session history. Session creation returns three event URLs: * `streamUrl` for the live native event stream * `turnStreamUrl` for turn-oriented live delivery * `replayUrl` for durable event recovery Use the live stream for responsive interfaces. Persist the latest sequence number and use the router replay endpoints after reconnecting. ## Replay native events ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/linc/v1/sessions/$SESSION_ID/events?cursor=120&limit=500" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` `cursor` is exclusive: the response contains events with a sequence number greater than the cursor. `afterSeq` is an alias, and `excludeEventTypes` accepts a comma-separated list. ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "sessionId": "linc_123", "cursor": 120, "lastSeq": 123, "events": [ { "seq": 121, "type": "message_update", "data": {}, "createdAt": "2026-07-28T14:00:00.000Z" } ] } ``` ## Replay completed messages Use the stable message read model when you need conversation history rather than every native runtime event: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/linc/v1/sessions/$SESSION_ID/messages?cursor=0&limit=5000" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` The response includes completed messages, their source sequence numbers, the native session ID, and the resumable session-file path. Both events and messages remain available after a session ends. ## Reconnect safely 1. Track the highest processed `seq`. 2. Reconnect the live stream when possible. 3. Replay from the stored cursor to fill any gap. 4. De-duplicate by sequence number. This keeps clients correct across network interruptions, sandbox idle stops, and process restarts. ## Provisioning webhooks Subscribe a unified webhook endpoint to both provisioning outcomes: * `linc.session.ready` fires once when the session atomically enters `active` and includes runtime, replay, and exact vault/object scope metadata. * `linc.session.provisioning_failed` fires once when the session atomically enters `failed` and includes a stable failure code plus a bounded, content-safe error message. Both events use stable event IDs. Redelivery therefore resumes missing delivery attempts without creating a second logical transition. Verify their signatures using the same raw-body workflow as all Case.dev events; see [Events quickstart](/events/quickstart). ## Passage evidence Vault-search tool results retain the existing document-level `details.sources` array for C3 and other citation consumers. They also include bounded `details.passages` entries with the exact retrieved object ID, title, chunk index, page or media-time range, OCR word range, and passage text. Delegated subagent results preserve the same passage records in their durable parent tool event. # Linc Overview Source: https://docs.case.dev/linc/index Run durable, stateful legal agent sessions in an isolated sandbox. Linc is the Case.dev API for intensive agent work. A Linc session keeps its own sandbox, conversation history, installed skills, scoped Case.dev credentials, and resumable runtime state. Use it for work that needs tools, files, multiple turns, or long-running legal analysis. > [!NOTE] > > Linc replaces the former Agent Chat and Agent Run APIs. New integrations should use only the > `/linc/v1/sessions` endpoints. ## Session lifecycle 1. Create a session with `POST /linc/v1/sessions`. 2. Poll `GET /linc/v1/sessions/{id}/state` until the status is `active`. 3. Send native Linc commands with `POST /linc/v1/sessions/{id}/rpc`. 4. Follow live events at the `streamUrl` returned during creation, or replay durable events and messages through the API. 5. Cancel the current turn without ending the session, or delete the session when the work is complete. | Endpoint | Purpose | | - | - | | `POST /linc/v1/sessions` | Create and provision a session | | `GET /linc/v1/sessions/{id}/state` | Read provisioning and live runtime state | | `POST /linc/v1/sessions/{id}/rpc` | Send a prompt or another native Linc command | | `GET /linc/v1/sessions/{id}/events` | Replay durable native events | | `GET /linc/v1/sessions/{id}/messages` | Replay completed messages | | `POST /linc/v1/sessions/{id}/cancel` | Abort the current turn while keeping the session | | `DELETE /linc/v1/sessions/{id}` | End the session and stop its runtime | ## Quickstart ```bash title="Create a session" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/linc/v1/sessions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "title": "Review the acquisition agreement", "vaultIds": ["vault_123"], "skillSlugs": ["contract-review"] }' ``` Creation returns `202 Accepted` while the sandbox is provisioning. Save the returned `id` and event URLs, then [send a prompt](/linc/sessions) after the session becomes active. ## Authentication and scope Linc requires a Case.dev API key with `agent:read` and `agent:write` permissions. When you attach vaults, the sandbox receives a short-lived, session-scoped credential instead of your original key. A session can access only the resources included in its resolved scope. The full request and response schemas are available in the [API Reference](/api-reference). # Sessions and commands Source: https://docs.case.dev/linc/sessions Create a Linc session, send prompts, cancel work, and end the runtime. ## Create a session `POST /linc/v1/sessions` starts asynchronous provisioning and returns `202 Accepted`. ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/linc/v1/sessions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "title": "Privilege review", "model": "casemark/core-large", "idleTimeoutMs": 900000, "vaultScopes": [{ "vaultId": "vault_123", "objectIds": ["obj_deposition", "obj_exhibit_12"] }], "skillSlugs": ["privilege-review"], "documentTemplateSlugs": ["privilege-log"] }' ``` The response includes the session ID, provisioning status, exact `vaultScopes`, installed-skill report, and URLs for state, replay, and live event streams. Missing requested skills are reported explicitly. Use `vaultScopes` when the runtime must see only selected objects. Every entry requires an `objectIds` array; an empty array grants no object access in that vault. The older `vaultIds` field explicitly grants whole-vault access and is mutually exclusive with `vaultScopes`. Omitting both preserves the legacy organization-level session behavior. ## Wait for activation Create a signed webhook endpoint filtered to `linc.session.ready` and `linc.session.provisioning_failed`, then wait for the event matching the returned session ID. See [Events quickstart](/events/quickstart) for endpoint creation and signature verification. Use `GET /linc/v1/sessions/$SESSION_ID/state` only to recover after a missed delivery or inspect a session; do not poll it for normal provisioning. A runtime that has idle-stopped remains resumable—the next prompt wakes it and restores its session file. ## Send a prompt Commands use the native Linc RPC envelope. Prompt IDs are idempotency keys, so retry the same request with the same ID if delivery is uncertain. ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/linc/v1/sessions/$SESSION_ID/rpc \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "type": "prompt", "id": "prompt_01", "message": "Review the agreement and produce a risk-ranked issue list." }' ``` The endpoint returns `202 Accepted` after Linc accepts or rejects the command. Read results from the event stream or durable replay endpoints. ## Cancel or end Abort only the current turn while preserving the session: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/linc/v1/sessions/$SESSION_ID/cancel \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{"clearQueue": true}' ``` End the session and stop its sandbox: ```bash theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X DELETE https://api.case.dev/linc/v1/sessions/$SESSION_ID \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` Deletion revokes the managed session credential and marks the durable session record as ended. # Chat completions Source: https://docs.case.dev/llms/chat-completions Send messages to AI models and get responses This is the core endpoint for all AI-powered features — summarization, extraction, analysis, drafting. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /llm/v1/chat/completions ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [ {"role": "user", "content": "Summarize this deposition in 3 bullet points."} ] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Summarize this deposition in 3 bullet points."}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'user', content: 'Summarize this deposition in 3 bullet points.' } ] }); console.log(response.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ {'role': 'user', 'content': 'Summarize this deposition in 3 bullet points.'} ] ) print(response.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{{ Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Summarize this deposition in 3 bullet points."), }}), }) fmt.Println(resp.Choices[0].Message.Content) ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "gen_01K972J7KV4Y0MJZ3SRTA6YYMH", "object": "chat.completion", "model": "openai/gpt-6-sol", "choices": [ { "index": 0, "message": { "role": "assistant", "content": "Here are the key points:\n\n• Witness testified that...\n• Documents reviewed include...\n• Timeline established from..." }, "finish_reason": "stop" } ], "usage": { "prompt_tokens": 245, "completion_tokens": 87, "total_tokens": 332, "cost": 0.000105 } } ``` ## Parameters ### Required | Parameter | Type | Description | | - | - | - | | `messages` | array | The conversation. Each message has a `role` and `content`. | ### Optional | Parameter | Type | Default | Description | | - | - | - | - | | `model` | string | `casemark/core-large` | Which model to use. [Browse all models →](https://case.dev/models) | | `max_tokens` | number | 4096 | Maximum tokens to generate | | `temperature` | number | 1 | Randomness (0-2). Use 0 for factual tasks. | | `stream` | boolean | false | Stream response token-by-token | | `stop` | array | null | Stop generation when these strings appear | ## Messages Each message in the `messages` array: | Field | Type | Description | | - | - | - | | `role` | string | `system`, `user`, or `assistant` | | `content` | string | The message text | ### System prompts Set the AI's behavior with a system message: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "You are a legal assistant. Be concise. Cite case law when relevant."}' \ --message '{role: user, content: "What are the elements of negligence?"}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'You are a legal assistant. Be concise. Cite case law when relevant.' }, { role: 'user', content: 'What are the elements of negligence?' } ] }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'You are a legal assistant. Be concise. Cite case law when relevant.' }, { 'role': 'user', 'content': 'What are the elements of negligence?' } ] ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a legal assistant. Be concise. Cite case law when relevant."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("What are the elements of negligence?"), }, }), }) fmt.Println(resp.Choices[0].Message.Content) ``` ### Multi-turn conversations Include previous messages to maintain context: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "What is a deposition?"}' \ --message '{role: assistant, content: "A deposition is sworn testimony taken outside of court..."}' \ --message '{role: user, content: "How long do they typically last?"}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'user', content: 'What is a deposition?' }, { role: 'assistant', content: 'A deposition is sworn testimony taken outside of court...' }, { role: 'user', content: 'How long do they typically last?' } ] }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ {'role': 'user', 'content': 'What is a deposition?'}, {'role': 'assistant', 'content': 'A deposition is sworn testimony taken outside of court...'}, {'role': 'user', 'content': 'How long do they typically last?'} ] ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ {Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("What is a deposition?")}, {Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleAssistant), Content: casedev.F("A deposition is sworn testimony taken outside of court...")}, {Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("How long do they typically last?")}, }), }) fmt.Println(resp.Choices[0].Message.Content) ``` ## Streaming Get responses token-by-token as they're generated: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Write a case summary."}' \ --stream ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const stream = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [{ role: 'user', content: 'Write a case summary.' }], stream: true }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ''); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} stream = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[{'role': 'user', 'content': 'Write a case summary.'}], stream=True ) for chunk in stream: print(chunk.choices[0].delta.content or '', end='') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} package main import ( "context" "net/http" casedev "github.com/CaseMark/casedev-go" "github.com/CaseMark/casedev-go/option" ) func main() { client := casedev.NewClient() var httpResp *http.Response client.Llm.V1.Chat.NewCompletion(context.TODO(), casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{{ Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Write a case summary."), }}), Stream: casedev.F(true), }, option.WithResponseInto(&httpResp)) // Read httpResp.Body as SSE stream } ``` ## Streaming HTTP failures When an upstream provider rejects a streaming request before streaming begins, Case.dev returns a non-2xx JSON error instead of opening an SSE stream. The response preserves the upstream HTTP status and includes `data.code: "UPSTREAM_PROVIDER_ERROR"` with a generic message. Check this machine-readable code before interpreting the HTTP status. In particular, a `401` or `403` carrying `UPSTREAM_PROVIDER_ERROR` describes an upstream failure, not an invalid Case.dev API key. Do not automatically revoke or rotate the caller's key based on that status alone. Provider response bodies are not returned. This describes pre-stream failures; failures after SSE has started follow the stream's error handling. ## Vision Send images to models that support vision (GPT and Gemini): ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'user', content: [ { type: 'text', text: 'What medical equipment is visible in this image?' }, { type: 'image_url', image_url: { url: 'https://example.com/exhibit-a.jpg' } } ] } ] }); ``` ## Usage and costs Every response includes token counts and cost: ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "usage": { "prompt_tokens": 1245, "completion_tokens": 387, "total_tokens": 1632, "cost": 0.004896 } } ``` > [!NOTE] > > **Reduce costs:** Use `temperature: 0` for factual extraction. Try cheaper models like `openai/gpt-6-luna` or `google/gemini-3.1-flash-lite` for simpler tasks. ## Common patterns ### Deposition summary ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Summarize depositions with: 1. Key admissions 2. Timeline of events 3. Credibility issues 4. Contradictions with other testimony"}' \ --message '{role: user, content: ""}' \ --temperature 0.3 \ --max-tokens 2000 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: `Summarize depositions with: 1. Key admissions 2. Timeline of events 3. Credibility issues 4. Contradictions with other testimony` }, { role: 'user', content: depositionText } ], temperature: 0.3, max_tokens: 2000 }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Summarize depositions with:\n1. Key admissions\n2. Timeline of events\n3. Credibility issues\n4. Contradictions with other testimony' }, {'role': 'user', 'content': deposition_text} ], temperature=0.3, max_tokens=2000 ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Summarize depositions with:\n1. Key admissions\n2. Timeline of events\n3. Credibility issues\n4. Contradictions with other testimony"), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(depositionText), }, }), Temperature: casedev.F(0.3), MaxTokens: casedev.F(int64(2000)), }) fmt.Println(resp.Choices[0].Message.Content) ``` ### Contract clause extraction ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: system, content: "Extract all indemnification clauses. Return JSON: [{clause_text, page, party_protected}]"}' \ --message '{role: user, content: ""}' \ --temperature 0 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Extract all indemnification clauses. Return JSON: [{clause_text, page, party_protected}]' }, { role: 'user', content: contractText } ], temperature: 0 }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ { 'role': 'system', 'content': 'Extract all indemnification clauses. Return JSON: [{clause_text, page, party_protected}]' }, {'role': 'user', 'content': contract_text} ], temperature=0 ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Extract all indemnification clauses. Return JSON: [{clause_text, page, party_protected}]"), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(contractText), }, }), Temperature: casedev.F(0.0), }) fmt.Println(resp.Choices[0].Message.Content) ``` ### Medical record review ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-astra \ --message '{role: system, content: "You are a medical-legal expert. Identify standard-of-care deviations and timeline inconsistencies."}' \ --message '{role: user, content: ""}' \ --max-tokens 5000 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-astra', messages: [ { role: 'system', content: 'You are a medical-legal expert. Identify standard-of-care deviations and timeline inconsistencies.' }, { role: 'user', content: medicalRecords } ], max_tokens: 5000 }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} response = client.llm.v1.chat.create_completion( model='openai/gpt-6-astra', messages=[ { 'role': 'system', 'content': 'You are a medical-legal expert. Identify standard-of-care deviations and timeline inconsistencies.' }, {'role': 'user', 'content': medical_records} ], max_tokens=5000 ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-astra"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("You are a medical-legal expert. Identify standard-of-care deviations and timeline inconsistencies."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(medicalRecords), }, }), MaxTokens: casedev.F(int64(5000)), }) fmt.Println(resp.Choices[0].Message.Content) ``` # Embeddings Source: https://docs.case.dev/llms/embeddings Convert text into numerical vectors for semantic search, similarity comparison, and clustering ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /llm/v1/embeddings ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/embeddings \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/text-embedding-3-small", "input": "Plaintiff alleges negligence in post-operative care" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 create-embedding \ --model openai/text-embedding-3-small \ --input "Plaintiff alleges negligence in post-operative care" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const result = await client.llm.v1.createEmbedding({ model: 'openai/text-embedding-3-small', input: 'Plaintiff alleges negligence in post-operative care' }); console.log(result.data[0].embedding); // [0.016, -0.022, ...] ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') result = client.llm.v1.create_embedding( model='openai/text-embedding-3-small', input='Plaintiff alleges negligence in post-operative care' ) print(result.data[0].embedding) # [0.016, -0.022, ...] ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Llm.V1.NewEmbedding(ctx, casedev.LlmV1NewEmbeddingParams{ Model: casedev.F("openai/text-embedding-3-small"), Input: casedev.F("Plaintiff alleges negligence in post-operative care"), }) fmt.Println(result.Data[0].Embedding) ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": [-0.016, 0.022, -0.011, ...] } ], "model": "openai/text-embedding-3-small", "usage": { "prompt_tokens": 12, "total_tokens": 12 } } ``` ## Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `model` | string | **Yes** | Embedding model ID | | `input` | string or array | **Yes** | Text(s) to embed | ## Embedding models | Model | Dimensions | Best for | \$/1K tokens | | - | - | - | - | | `openai/text-embedding-3-small` | 1536 | General purpose | \$0.00002 | | `openai/text-embedding-3-large` | 3072 | Higher quality | \$0.00013 | | `voyage/voyage-law-2` | 1024 | **Legal documents** | \$0.00012 | | `voyage/voyage-3.5` | 1536 | General purpose | \$0.00006 | > [!NOTE] > > **For legal documents,** use `voyage/voyage-law-2`. It's specifically trained on legal text. ## Batch embeddings Embed multiple texts in one request: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 create-embedding \ --model openai/text-embedding-3-small \ --input "Plaintiff alleges negligence in post-operative care" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.llm.v1.createEmbedding({ model: 'openai/text-embedding-3-small', input: [ 'Medical record from January 2024', 'Deposition transcript page 45', 'Expert witness report summary' ] }); // result.data[0].embedding, result.data[1].embedding, ... ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.llm.v1.create_embedding( model='openai/text-embedding-3-small', input=[ 'Medical record from January 2024', 'Deposition transcript page 45', 'Expert witness report summary' ] ) # result.data[0].embedding, result.data[1].embedding, ... ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Llm.V1.NewEmbedding(ctx, casedev.LlmV1NewEmbeddingParams{ Model: casedev.F("openai/text-embedding-3-small"), Input: casedev.F([]string{ "Text one", "Text two", "Text three", }), }) // result.Data[0].Embedding, result.Data[1].Embedding, ... ``` ## Use cases ### Semantic search ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Embed your query casedev llm:v1 create-embedding \ --model voyage/voyage-law-2 \ --input "negligence in surgical procedure" # 2. Compare to document embeddings (cosine similarity) # 3. Return most similar documents ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Embed your query const queryResult = await client.llm.v1.createEmbedding({ model: 'voyage/voyage-law-2', input: 'negligence in surgical procedure' }); // 2. Compare to document embeddings (cosine similarity) // 3. Return most similar documents ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # 1. Embed your query query_result = client.llm.v1.create_embedding( model='voyage/voyage-law-2', input='negligence in surgical procedure' ) # 2. Compare to document embeddings (cosine similarity) # 3. Return most similar documents ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Embed your query queryResult, _ := client.Llm.V1.NewEmbedding(ctx, casedev.LlmV1NewEmbeddingParams{ Model: casedev.F("voyage/voyage-law-2"), Input: casedev.F("negligence in surgical procedure"), }) // 2. Compare to document embeddings (cosine similarity) // 3. Return most similar documents ``` ### Document similarity ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Compare two documents (embed each separately, then compute similarity) casedev llm:v1 create-embedding \ --model voyage/voyage-law-2 \ --input "Plaintiff expert testimony on standard of care" casedev llm:v1 create-embedding \ --model voyage/voyage-law-2 \ --input "Defense expert rebuttal on treatment protocols" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Compare two documents const result = await client.llm.v1.createEmbedding({ model: 'voyage/voyage-law-2', input: [ 'Plaintiff expert testimony on standard of care', 'Defense expert rebuttal on treatment protocols' ] }); // Calculate cosine similarity: // ~1.0 = very similar, ~0.5 = somewhat related, ~0.0 = unrelated ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Compare two documents result = client.llm.v1.create_embedding( model='voyage/voyage-law-2', input=[ 'Plaintiff expert testimony on standard of care', 'Defense expert rebuttal on treatment protocols' ] ) # Calculate cosine similarity: # ~1.0 = very similar, ~0.5 = somewhat related, ~0.0 = unrelated ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Compare two documents result, _ := client.Llm.V1.NewEmbedding(ctx, casedev.LlmV1NewEmbeddingParams{ Model: casedev.F("voyage/voyage-law-2"), Input: casedev.F([]string{ "Plaintiff expert testimony on standard of care", "Defense expert rebuttal on treatment protocols", }), }) // Calculate cosine similarity: // ~1.0 = very similar, ~0.5 = somewhat related, ~0.0 = unrelated ``` > [!NOTE] > > **Tip:** Use the same model for indexing and querying. Mixing models produces poor results. # LLMs Overview Source: https://docs.case.dev/llms/index Access OpenAI, Anthropic, Gemini, and CaseMark models through one API A unified, compliance-ready gateway for the world's best models. Integrate GPT, Gemini, and CaseMark models with built-in PII redaction, rate limiting, and audit trails. > [card] [Browse All Models](https://case.dev/models) > > Explore every model with pricing, context windows, and capabilities in our interactive catalog. ## Why use the Gateway? You could call Anthropic or OpenAI directly. But then you have to build the compliance layer yourself. * **Zero-Retention Agreements**: We hold BAAs with major providers—pass this through to your users. * **Unified Audit Log**: Every prompt and completion logged for compliance (optional). * **PII Redaction**: Automatically strip names, SSNs, and dates before they hit the model. * **Provider Fallback**: If OpenAI is down, we route to Azure or Bedrock automatically. ## Quick example ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Summarize this deposition in 3 bullet points."}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Process a request from your user const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'user', content: userPrompt } ] }); // Return the response to your user console.log(response.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Process a request from your user response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ {'role': 'user', 'content': user_prompt} ] ) # Return the response to your user print(response.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Process a request from your user resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{{ Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F(userPrompt), }}), }) // Return the response to your user fmt.Println(resp.Choices[0].Message.Content) ``` ## Specialized Models Choose the right model for your feature: | Provider | Models | Best for | | - | - | - | | **CaseMark** | Core Large, Core Titanium, Core Mini, Embed V1 | **Legal reasoning and retrieval**. Tuned for legal workflows, with zero-retention hosting. | | **OpenAI** | GPT-6.1 Sol, GPT-6 Sol, GPT-6 Luna, GPT-5.6 family | **Agents and extraction**. Frontier reasoning, tool use, reliable structured output. | | **Anthropic** | Claude Opus 5.5, Sonnet 5.5, Haiku 5.5 | **Drafting and review**. Served on a zero-data-retention workspace; strong instruction following and tool use. | | **Google** | Gemini 3.8 Flash, Gemini 3.1 Flash Lite, Gemini 3.1 Pro | **Large documents**. 1M-token context for whole case files at low cost. | See [Models](/llms/models) for API details or [browse the visual catalog](https://case.dev/models) for the full list. ## Endpoints > [card] [Models](/llms/models) > > `GET /llm/v1/models` — List available models > [card] [Chat completions](/llms/chat-completions) > > `POST /llm/v1/chat/completions` — Generate AI responses > [card] [Embeddings](/llms/embeddings) > > `POST /llm/v1/embeddings` — Generate vector embeddings ## Related services > [card] [Vault](/vault) > > Combine LLMs with semantic search for RAG-powered document Q\&A > [card] [Web Search](/web-search) > > Ground LLM responses with real-time web research and citations # Model Catalog Source: https://docs.case.dev/llms/model-catalog Browse all available AI models with pricing, capabilities, and context windows Access a curated catalog of OpenAI, Gemini, and CaseMark models through a single API. All models support the OpenAI-compatible chat completions format. > [card] [Browse Models](https://case.dev/models) > > **Visual Model Catalog** — Search, filter, and compare every model with real-time pricing, context windows, and capabilities. *** ## Using a Model To use any model, pass its ID to the chat completions endpoint: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/llm/v1/chat/completions \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "model": "openai/gpt-6-sol", "messages": [{"role": "user", "content": "Hello!"}] }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Hello!"}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [{ role: 'user', content: 'Hello!' }] }); console.log(response.choices[0].message.content); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[{'role': 'user', 'content': 'Hello!'}] ) print(response.choices[0].message.content) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{{ Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Hello!"), }}), }) fmt.Println(resp.Choices[0].Message.Content) ``` *** ## Programmatic Access Get the complete model list via API: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/llm/v1/models \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 list-models ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const { data: models } = await client.llm.v1.listModels(); for (const model of models) { console.log(`${model.id}: $${model.pricing.input}/input, $${model.pricing.output}/output`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') result = client.llm.v1.list_models() for model in result.data: print(f'{model.id}: ${model.pricing.input}/input, ${model.pricing.output}/output') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Llm.V1.ListModels(ctx) for _, model := range result.Data { fmt.Printf("%s: $%s/input, $%s/output\n", model.ID, model.Pricing.Input, model.Pricing.Output) } ``` Response includes all models with current pricing, context windows, and capabilities. ## Meta Muse Spark Contributor `meta/muse-spark-1.3-contributor` is an opt-in, direct Meta model. It is not zero-data-retention: Meta may use submitted prompts, files, context, and model responses to train its models. Applications must not infer permission to send customer content merely from the absence of a BAA. The model record explicitly includes `zdr: false`, `compliance: { zdr: false, baa: false, hipaa: false }`, and `data_policy: { training: true, zero_data_retention: false }`. Clients must inspect these fields rather than assuming every catalog model is ZDR. Case.dev prices per million tokens are **$0.20 input**, **$0.004 cached input**, and **\$0.40 output**. Each is twice Meta's provider rate; cached tokens are subtracted from ordinary input before billing. The same customer charge is returned in `usage.cost` and recorded in billable usage for both streaming and non-streaming requests. Downstream applications need no additional multiplier. The route rejects policies requiring ZDR, BAA, or HIPAA, honors provider restrictions, and fails closed when policy lookup is unavailable. The model is listed only where `META_AI_API_KEY` is configured on the router. It is never a automatic fallback for another model. Existing models and prices are unchanged. Provider references: [Meta model documentation](https://dev.meta.ai/docs/models) and [pricing and Contributor data use](https://dev.meta.ai/docs/pricing-rate-limits). # List models Source: https://docs.case.dev/llms/models Get all available AI models with pricing, context windows, and capabilities > [!TIP] > > **Visual Model Browser:** Prefer a visual interface? [Browse all models](https://case.dev/models) with filtering, search, and comparison. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /llm/v1/models ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/llm/v1/models \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1 list-models ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const { data: models } = await client.llm.v1.listModels(); for (const model of models) { console.log(`${model.id}: $${model.pricing.input}/input, $${model.pricing.output}/output`); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') result = client.llm.v1.list_models() for model in result.data: print(f'{model.id}: ${model.pricing.input}/input, ${model.pricing.output}/output') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Llm.V1.ListModels(ctx) for _, model := range result.Data { fmt.Printf("%s: $%s/input, $%s/output\n", model.ID, model.Pricing.Input, model.Pricing.Output) } ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "object": "list", "data": [ { "id": "casemark/core-large", "name": "CaseMark Core Large", "description": "CaseMark's flagship legal reasoning model powered by Kimi K2.6", "owned_by": "casemark", "context_window": 200000, "max_tokens": 128000, "tags": ["reasoning", "legal", "tool-use"], "pricing": { "input": "0.0000015", "output": "0.0000035" } }, { "id": "openai/gpt-6-sol", "name": "GPT-6 Sol", "description": "OpenAI's current frontier model with vision, reasoning, and tool use", "owned_by": "openai", "context_window": 1050000, "max_tokens": 128000, "tags": ["vision", "reasoning", "tool-use"], "pricing": { "input": "0.000002", "output": "0.00001" } } ] } ``` ## Popular models | Model | Context | Best for | Input \$/MTok | | - | - | - | - | | `casemark/core-large` | 200K | Legal reasoning, workflows | \$1.50 | | `openai/gpt-6.1-sol` | 1M | Newest frontier model, agents | \$2.00 | | `openai/gpt-6.1-terra` | 1M | Visual reasoning, writing, computer use | \$1.00 | | `openai/gpt-6-sol` | 1M | Complex analysis, vision, tool use | \$2.00 | | `openai/gpt-6-astra` | 1M | Hardest tasks | \$10.00 | | `openai/gpt-6-luna` | 1M | Fast, cheap | \$0.10 | | `anthropic/claude-opus-5.5` | 1M | Deepest reasoning, long agent runs | \$4.00 | | `anthropic/claude-sonnet-5.5` | 1M | Balanced analysis, drafting, tool use | \$2.00 | | `anthropic/claude-haiku-5.5` | 1M | Fast, cheap | \$0.10 | | `google/gemini-4-argon` | 1M | Multimodal reasoning, document analysis | \$2.00 | | `google/gemini-3.8-flash` | 1M | Long documents, multimodal | \$0.75 | | `google/gemini-3.5-flash-lite` | 1M | Subagents, high-volume tool use | \$0.30 | | `google/gemini-3.1-flash-lite` | 1M | Very long documents at lowest cost | \$0.25 | ## Model capabilities | Tag | Meaning | | - | - | | `vision` | Can process images | | `tool-use` | Supports function calling | | `reasoning` | Enhanced reasoning | | `fast` | Optimized for low latency | | `legal` | Fine-tuned for legal tasks | > [!NOTE] > > **Prices are per token.** Multiply by 1,000,000 for price per million tokens (MTok). # Matters Overview Source: https://docs.case.dev/matters/index Matter-native operator primitives for legal work. Matters are the workspace primitive for legal work on Case.dev. A matter owns the operating context: metadata, its primary vault, work items, parties, audit logs, and sharing. [Open API](/api-reference) [All Services](/services) Create `POST /matters/v1` Track `POST /matters/v1/{id}/work-items` Decide `POST /matters/v1/{id}/work-items/{workItemId}/decision` ## What a matter owns * Primary vault linkage * Work items and decision history * Reusable parties and matter-specific roles * Optional playbook (matter type) for agent instructions * Audit logs, exports, events, and shares ## Core resources | Resource | Endpoint family | Purpose | | - | - | - | | Matter | `/matters/v1` | Create, update, and inspect legal workspaces | | Matter types | `/matters/v1/types` | Optional playbooks with agent instructions | | Agent types | `/matters/v1/agent-types` | Reusable agent role definitions | | Parties | `/matters/v1/parties` | Reusable people and organizations | | Matter parties | `/matters/v1/{id}/parties` | Attach parties to a matter with roles | | Work items | `/matters/v1/{id}/work-items` | Create and manage legal tasks | | Decisions | `/matters/v1/{id}/work-items/{workItemId}/decision` | Approve or block work | | Logs | `/matters/v1/{id}/log` | Operational history and exports | | Shares | `/matters/v1/{id}/shares` | Cross-org matter access | ## How it works The matters API is a task board and system of record for legal work. 1. **Create a work item** to describe and track a unit of work. 2. **Perform intensive agent work in Linc** and attach the results to your application workflow. 3. **Update the work item** as its state changes. 4. **Record a decision** to approve or block the work. Work items can keep application-specific dependencies and result references in metadata. ## Quickstart ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Create a matter curl https://api.case.dev/matters/v1 \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "title": "Doe v. Example Corp.", "practice_area": "litigation" }' ``` ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Create a work item curl https://api.case.dev/matters/v1/$MATTER_ID/work-items \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "title": "Review demand letter", "type": "review", "instructions": "Check all citations and verify damages calculations against the medical records." }' ``` ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Block a work item with a reason curl https://api.case.dev/matters/v1/$MATTER_ID/work-items/$WORK_ITEM_ID/decision \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "decision": "block", "reason": "Citation on page 3 was overturned in 2024." }' ``` ## Listing matters `GET /matters/v1` supports cursor pagination, newest update first. **Pagination is opt-in:** pass `limit` to receive a bounded page. A request with neither `limit` nor `cursor` still returns every matter. | Parameter | Type | Description | | - | - | - | | `limit` | integer | Matters per page, `1`–`200`. Omit to receive every matter. | | `cursor` | string | Opaque continuation cursor from the previous page's `next_cursor`. | Every response carries a `pagination` object. Unpaginated requests report `limit: null` and `has_more: false`: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "data": [{ "id": "matter_...", "title": "Doe v. Example Corp." }], "pagination": { "limit": 50, "has_more": true, "next_cursor": "eyJ1IjoiMjAyNi0wMS0wMVQwMDowMDowMC4wMDBaIi..." } } ``` > [!WARNING] > > **The unpaginated default is going away.** A request without `limit` currently returns every > matter. A future release will bound it to a default page size. Start passing `limit` and following > `next_cursor` now and that change will be a no-op for you. To read the whole list, keep requesting while `has_more` is true, passing the previous `next_cursor` as `?cursor=`: ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} CURSOR="" while :; do PAGE=$(curl -s "https://api.case.dev/matters/v1?limit=100&cursor=$CURSOR" \ -H "Authorization: Bearer $CASEDEV_API_KEY") echo "$PAGE" | jq -r '.data[].id' [ "$(echo "$PAGE" | jq -r '.pagination.has_more')" = "true" ] || break CURSOR=$(echo "$PAGE" | jq -r '.pagination.next_cursor') done ``` ### Cursor rules Cursors are opaque: do not parse, construct, or persist them. They encode the sort position of the last row on a page (`updated_at` **and** `id`, so matters sharing a timestamp are never skipped or repeated) together with the filters they were issued under. * Replay a cursor with **exactly the same** `status`, `matter_type`, `practice_area`, and `query` values that produced it. Changing a filter mid-pagination returns `400 INVALID_CURSOR` rather than silently blending two result sets. * Cursors are scoped to the organization and API key that minted them. Another tenant's cursor returns `400 INVALID_CURSOR`. * A `limit` outside `1`–`200`, or a non-integer, returns `400 INVALID_LIMIT`. Out-of-range values are rejected, not clamped. * Passing a `cursor` without a `limit` pages at the default size of `50`. Matters are ordered by `updated_at` descending. Because that column changes as matters are edited, a matter updated during a traversal can move between pages. Pin `status` or a narrow `query` when you need a more stable window. ### Other paginated matter lists The same opt-in `limit` + `cursor` contract, and the same `pagination` object, apply to: | Endpoint | Ordered by | Cursor is bound to | | - | - | - | | `GET /matters/v1/parties` | `updated_at` desc | org + `query`, `type`, `email` | | `GET /matters/v1/{id}/work-items` | `updated_at` desc | matter + `status`, `assignee_id` | Each returns everything when called without `limit` or `cursor`, and each will gain a bounded default in a future release. The full schema and every tagged operation live in the [API Reference](/api-reference). # Media Overview Source: https://docs.case.dev/media/index Create captioned media clips and retrieve transcript text or word timing data. Media endpoints help applications turn transcript-backed audio or video into reviewable outputs. Use them to create captioned clips from vault media, retrieve transcript text, and search timestamped transcript words for clip assembly or evidence review. > [card] Captioned clips > > Generate short captioned video clips from source media and transcript word ranges. > [card] Transcript utilities > > Retrieve transcript text or search transcript words with timing metadata. ## Create a clip ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/media/v1/clips \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "source": { "vault_id": "vault_abc123", "object_id": "obj_media123" }, "transcript": { "object_id": "obj_transcript123" }, "selection": { "type": "word_range", "start_word": 120, "end_word": 260 } }' ``` Clip creation is asynchronous. The response returns a job ID that you can poll until the clip is complete. ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/media/v1/clips/{id}" \ -H "Authorization: Bearer $CASE_API_KEY" ``` ## Work with transcripts Use transcript retrieval when you need the full text for display, export, or downstream analysis. ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/media/v1/transcripts/retrieve \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "vault_id": "vault_abc123", "object_id": "obj_media123" }' ``` Use transcript word search when you need exact word ranges and timing for clip selection. ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/media/v1/transcripts/search \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "transcript": { "vault_id": "vault_abc123", "object_id": "obj_transcript123" }, "query": "contract termination" }' ``` See the [API Reference](/api-reference) for full request and response schemas. # Memory Overview Source: https://docs.case.dev/memory/index Persistent memory for AI agents ## The problem Your AI agent forgets everything between conversations. Users repeat themselves, context is lost, and the experience feels broken. ## The solution Memory gives your agent **persistent, searchable storage** for facts extracted from conversations. When a user says "I prefer dark mode" or "The client is risk-averse," those facts are stored and can be retrieved later. ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart TD A["Conversation
User shares a durable fact"] --> B["Extraction
Memory turns the message into discrete facts"] B --> C["Storage
Facts are saved with your tags and category"] C --> D["Later retrieval
A semantic search surfaces the right fact at the right time"] ``` ## How it works 1. **Add memories** - Pass conversation messages, we extract discrete facts 2. **Search memories** - Query by meaning, not just keywords 3. **Filter by tags** - Scope memories using 12 generic indexed tag fields The API handles: * Fact extraction (turning "I like X but hate Y" into separate facts) * Deduplication (updating existing facts instead of creating duplicates) * Semantic search (finding "investment preferences" when you stored "conservative strategies") ## Quick start ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Add a memory curl -X POST https://api.case.dev/memory/v1 \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "Remember that this client prefers conservative investments."} ], "tag_1": "client_123", "tag_2": "matter_456", "category": "preference" }' # Search memories curl -X POST https://api.case.dev/memory/v1/search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "investment preferences", "tag_1": "client_123", "top_k": 5 }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Add a memory casedev memory:v1 create \ --message '{"role": "user", "content": "Remember that this client prefers conservative investments."}' \ --tag-1 client_123 \ --tag-2 matter_456 \ --category preference # Search memories casedev memory:v1 search \ --query "investment preferences" \ --tag-1 client_123 \ --top-k 5 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // 1. Store memories from a conversation const result = await client.memory.add({ messages: [ { role: 'user', content: 'Remember that this client prefers conservative investments and is risk-averse.' } ], tag_1: 'client_123', // Your client ID tag_2: 'matter_456', // Your matter/case ID category: 'preference' }); console.log(result.results); // [ // { id: 'mem_abc', memory: 'Client prefers conservative investments', event: 'ADD' }, // { id: 'mem_def', memory: 'Client is risk-averse', event: 'ADD' } // ] // 2. Later, search for relevant memories const memories = await client.memory.search({ query: 'investment preferences', tag_1: 'client_123', top_k: 5 }); console.log(memories.results[0].memory); // "Client prefers conservative investments" ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # 1. Store memories from a conversation result = client.memory.v1.create( messages=[ {'role': 'user', 'content': 'Remember that this client prefers conservative investments and is risk-averse.'} ], tag_1='client_123', # Your client ID tag_2='matter_456', # Your matter/case ID category='preference' ) print(result.results) # [ # {'id': 'mem_abc', 'memory': 'Client prefers conservative investments', 'event': 'ADD'}, # {'id': 'mem_def', 'memory': 'Client is risk-averse', 'event': 'ADD'} # ] # 2. Later, search for relevant memories memories = client.memory.v1.search( query='investment preferences', tag_1='client_123', top_k=5 ) print(memories.results[0].memory) # "Client prefers conservative investments" ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Store memories from a conversation result, _ := client.Memory.V1.New(ctx, casedev.MemoryV1NewParams{ Messages: casedev.F([]casedev.MemoryV1NewParamsMessage{{ Role: casedev.F("user"), Content: casedev.F("Remember that this client prefers conservative investments and is risk-averse."), }}), Tag1: casedev.F("client_123"), Tag2: casedev.F("matter_456"), Category: casedev.F("preference"), }) fmt.Println(result.Results) // Later, search for relevant memories memories, _ := client.Memory.V1.Search(ctx, casedev.MemoryV1SearchParams{ Query: casedev.F("investment preferences"), Tag1: casedev.F("client_123"), TopK: casedev.F(int64(5)), }) fmt.Println(memories.Results[0].Memory) ``` ## Tag fields Memory provides **12 generic indexed tag fields** (`tag_1` through `tag_12`) for filtering. You decide what each tag means for your application: | Use Case | tag\_1 | tag\_2 | tag\_3 | tag\_4 | | - | - | - | - | - | | **Legal** | client\_id | matter\_id | attorney\_id | session\_id | | **Healthcare** | patient\_id | encounter\_id | provider\_id | department | | **E-commerce** | customer\_id | order\_id | product\_id | session\_id | | **Support** | user\_id | ticket\_id | agent\_id | channel | > [!NOTE] > > All tag fields are indexed for fast filtering. Use them for any dimension you need to query by. ### Example: Legal application ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Store a memory scoped to client + matter curl -X POST https://api.case.dev/memory/v1 \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "messages": [ {"role": "user", "content": "The patent filing deadline is March 15th, 2026."} ], "tag_1": "client_acme_corp", "tag_2": "matter_patent_2026_001", "tag_3": "atty_jane_smith", "category": "deadline" }' # Search only this client's deadlines curl -X POST https://api.case.dev/memory/v1/search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "upcoming deadlines", "tag_1": "client_acme_corp", "category": "deadline", "top_k": 10 }' # List all memories for a specific matter curl "https://api.case.dev/memory/v1?tag_1=client_acme_corp&tag_2=matter_patent_2026_001" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Store a memory scoped to client + matter casedev memory:v1 create \ --message '{role: user, content: "The patent filing deadline is March 15th, 2026."}' \ --tag-1 client_acme_corp \ --tag-2 matter_patent_2026_001 \ --tag-3 atty_jane_smith \ --category deadline # Search only this client's deadlines casedev memory:v1 search \ --query "upcoming deadlines" \ --tag-1 client_acme_corp \ --category deadline \ --top-k 10 # List all memories for a specific matter casedev memory:v1 list \ --tag-1 client_acme_corp \ --tag-2 matter_patent_2026_001 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Store a memory scoped to client + matter await client.memory.add({ messages: [ { role: 'user', content: 'The patent filing deadline is March 15th, 2026.' } ], tag_1: 'client_acme_corp', // Client ID tag_2: 'matter_patent_2026_001', // Matter ID tag_3: 'atty_jane_smith', // Attorney ID category: 'deadline' }); // Search only this client's deadlines const deadlines = await client.memory.search({ query: 'upcoming deadlines', tag_1: 'client_acme_corp', category: 'deadline', top_k: 10 }); // List all memories for a specific matter const matterMemories = await client.memory.list({ tag_1: 'client_acme_corp', tag_2: 'matter_patent_2026_001' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Store a memory scoped to client + matter result = client.memory.v1.create( messages=[ {'role': 'user', 'content': 'The patent filing deadline is March 15th, 2026.'} ], tag_1='client_acme_corp', # Client ID tag_2='matter_patent_2026_001', # Matter ID tag_3='atty_jane_smith', # Attorney ID category='deadline' ) # Search only this client's deadlines deadlines = client.memory.v1.search( query='upcoming deadlines', tag_1='client_acme_corp', category='deadline', top_k=10 ) # List all memories for a specific matter matter_memories = client.memory.v1.list( tag_1='client_acme_corp', tag_2='matter_patent_2026_001' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Store a memory scoped to client + matter result, _ := client.Memory.V1.New(ctx, casedev.MemoryV1NewParams{ Messages: casedev.F([]casedev.MemoryV1NewParamsMessage{{ Role: casedev.F(casedev.MemoryV1NewParamsMessagesRoleUser), Content: casedev.F("The patent filing deadline is March 15th, 2026."), }}), Tag1: casedev.F("client_acme_corp"), // Client ID Tag2: casedev.F("matter_patent_2026_001"), // Matter ID Tag3: casedev.F("atty_jane_smith"), // Attorney ID Category: casedev.F("deadline"), }) // Search only this client's deadlines deadlines, _ := client.Memory.V1.Search(ctx, casedev.MemoryV1SearchParams{ Query: casedev.F("upcoming deadlines"), Tag1: casedev.F("client_acme_corp"), Category: casedev.F("deadline"), TopK: casedev.F(int64(10)), }) // List all memories for a specific matter matterMemories, _ := client.Memory.V1.List(ctx, casedev.MemoryV1ListParams{ Tag1: casedev.F("client_acme_corp"), Tag2: casedev.F("matter_patent_2026_001"), }) ``` ## Categories The `category` field is **free-form text** - you define your own categories. Here are suggested categories for different domains: ### Legal categories | Category | Description | Example | | - | - | - | | `fact` | General facts about client/matter | "Client founded company in 2019" | | `preference` | Communication or work preferences | "Client prefers email updates" | | `deadline` | Filing deadlines, court dates | "Motion due March 15th" | | `decision` | Decisions made by client/court | "Client approved settlement terms" | | `contact` | Contact information | "Client's assistant is Jane ([jane@acme.com](mailto:jane@acme.com))" | | `relationship` | Relationships between parties | "Defendant is client's former business partner" | | `court_ruling` | Court rulings and precedents | "Judge denied motion to dismiss" | | `procedural` | Procedural information | "Case assigned to Judge Thompson" | ### Healthcare categories | Category | Description | | - | - | | `allergy` | Patient allergies | | `medication` | Current medications | | `preference` | Treatment preferences | | `history` | Medical history | | `family_history` | Family medical history | | `social` | Social/lifestyle factors | ### Filtering by category ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Get only deadline memories for a client curl "https://api.case.dev/memory/v1?tag_1=client_123&category=deadline" \ -H "Authorization: Bearer $CASEDEV_API_KEY" # Search preferences only curl -X POST https://api.case.dev/memory/v1/search \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "query": "communication method", "tag_1": "client_123", "category": "preference" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Get only deadline memories for a client casedev memory:v1 list --tag-1 client_123 --category deadline # Search preferences only casedev memory:v1 search --query "communication method" --tag-1 client_123 --category preference ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Get only deadline memories for a client const deadlines = await client.memory.list({ tag_1: 'client_123', category: 'deadline' }); // Search preferences only const prefs = await client.memory.search({ query: 'communication method', tag_1: 'client_123', category: 'preference' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Get only deadline memories for a client deadlines = client.memory.v1.list(tag_1='client_123', category='deadline') # Search preferences only prefs = client.memory.v1.search( query='communication method', tag_1='client_123', category='preference' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Get only deadline memories for a client deadlines, _ := client.Memory.V1.List(ctx, casedev.MemoryV1ListParams{ Tag1: casedev.F("client_123"), Category: casedev.F("deadline"), }) // Search preferences only prefs, _ := client.Memory.V1.Search(ctx, casedev.MemoryV1SearchParams{ Query: casedev.F("communication method"), Tag1: casedev.F("client_123"), Category: casedev.F("preference"), }) ``` ## Listing memories ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # List all memories for a client curl "https://api.case.dev/memory/v1?tag_1=client_123&limit=50" \ -H "Authorization: Bearer $CASEDEV_API_KEY" # List with multiple filters curl "https://api.case.dev/memory/v1?tag_1=client_123&tag_2=matter_456&category=deadline&limit=20&offset=0" \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # List all memories for a client casedev memory:v1 list --tag-1 client_123 --limit 50 # List with multiple filters casedev memory:v1 list \ --tag-1 client_123 \ --tag-2 matter_456 \ --category deadline \ --limit 20 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // List all memories for a client const all = await client.memory.list({ tag_1: 'client_123', limit: 50 }); // List with multiple filters const filtered = await client.memory.list({ tag_1: 'client_123', tag_2: 'matter_456', category: 'deadline', limit: 20, offset: 0 }); console.log(filtered.results); // Array of memories console.log(filtered.count); // Total count matching filters ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # List all memories for a client all_memories = client.memory.v1.list(tag_1='client_123', limit=50) # List with multiple filters filtered = client.memory.v1.list( tag_1='client_123', tag_2='matter_456', category='deadline', limit=20, offset=0 ) print(filtered.results) # Array of memories print(filtered.count) # Total count matching filters ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // List all memories for a client all, _ := client.Memory.V1.List(ctx, casedev.MemoryV1ListParams{ Tag1: casedev.F("client_123"), Limit: casedev.F(int64(50)), }) // List with multiple filters filtered, _ := client.Memory.V1.List(ctx, casedev.MemoryV1ListParams{ Tag1: casedev.F("client_123"), Tag2: casedev.F("matter_456"), Category: casedev.F("deadline"), Limit: casedev.F(int64(20)), Offset: casedev.F(int64(0)), }) fmt.Println(filtered.Results) // Array of memories fmt.Println(filtered.Count) // Total count matching filters ``` ## Deleting memories ### Delete a single memory ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X DELETE https://api.case.dev/memory/v1/mem_abc123 \ -H "Authorization: Bearer $CASEDEV_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev memory:v1 delete --id mem_abc123 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.memory.delete('mem_abc123'); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.memory.v1.delete('mem_abc123') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.Memory.V1.Delete(ctx, "mem_abc123") ``` ### Bulk delete by tags ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/memory/v1/delete-many \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Delete all memories for a client casedev memory:v1 delete-all --tag-1 client_123 # Delete memories for a specific matter casedev memory:v1 delete-all --tag-1 client_123 --tag-2 matter_456 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Delete all memories for a client await client.memory.deleteMany({ tag_1: 'client_123' }); // Delete memories for a specific matter await client.memory.deleteMany({ tag_1: 'client_123', tag_2: 'matter_456' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Delete all memories for a client client.memory.v1.delete_all(tag_1='client_123') # Delete memories for a specific matter client.memory.v1.delete_all(tag_1='client_123', tag_2='matter_456') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Delete all memories for a client client.Memory.V1.DeleteAll(ctx, casedev.MemoryV1DeleteAllParams{ Tag1: casedev.F("client_123"), }) // Delete memories for a specific matter client.Memory.V1.DeleteAll(ctx, casedev.MemoryV1DeleteAllParams{ Tag1: casedev.F("client_123"), Tag2: casedev.F("matter_456"), }) ``` > [!WARNING] > > Bulk delete removes all matching memories. Use with caution. ## Memory events When you add memories, the API returns what happened to each extracted fact: | Event | Description | | - | - | | `ADD` | New memory created | | `UPDATE` | Existing memory was updated/merged | | `DELETE` | Contradicting info caused memory deletion | | `NONE` | Duplicate - memory already exists | ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/memory/v1/add \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev memory:v1 create \ --message '{role: user, content: "Actually, the client now prefers phone calls instead of email."}' \ --tag-1 client_123 # Result might show event: UPDATE # (merged with existing email preference) ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.memory.add({ messages: [ { role: 'user', content: 'Actually, the client now prefers phone calls instead of email.' } ], tag_1: 'client_123' }); // Result might show: // { id: 'mem_xyz', memory: 'Client prefers phone calls', event: 'UPDATE' } // (merged with existing email preference) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.memory.v1.create( messages=[ {'role': 'user', 'content': 'Actually, the client now prefers phone calls instead of email.'} ], tag_1='client_123' ) # Result might show: # {'id': 'mem_xyz', 'memory': 'Client prefers phone calls', 'event': 'UPDATE'} # (merged with existing email preference) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Memory.V1.New(ctx, casedev.MemoryV1NewParams{ Messages: casedev.F([]casedev.MemoryV1NewParamsMessage{{ Role: casedev.F(casedev.MemoryV1NewParamsMessagesRoleUser), Content: casedev.F("Actually, the client now prefers phone calls instead of email."), }}), Tag1: casedev.F("client_123"), }) // Result might show: // {ID: "mem_xyz", Memory: "Client prefers phone calls", Event: "UPDATE"} // (merged with existing email preference) ``` ## Direct storage (skip extraction) To store a fact directly without LLM extraction, set `infer: false`: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/memory/v1/add \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev memory:v1 create \ --message '{role: user, content: "Client SSN: 123-45-6789"}' \ --tag-1 client_123 \ --category contact \ --infer false ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.memory.add({ messages: [ { role: 'user', content: 'Client SSN: 123-45-6789' } ], tag_1: 'client_123', category: 'contact', infer: false // Store as-is, no extraction }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.memory.v1.create( messages=[{'role': 'user', 'content': 'Client SSN: 123-45-6789'}], tag_1='client_123', category='contact', infer=False # Store as-is, no extraction ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Memory.V1.New(ctx, casedev.MemoryV1NewParams{ Messages: casedev.F([]casedev.MemoryV1NewParamsMessage{{ Role: casedev.F(casedev.MemoryV1NewParamsMessagesRoleUser), Content: casedev.F("Client SSN: 123-45-6789"), }}), Tag1: casedev.F("client_123"), Category: casedev.F("contact"), Infer: casedev.F(false), // Store as-is, no extraction }) ``` ## Custom extraction prompts For domain-specific extraction, provide a custom prompt: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/memory/v1/add \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev memory:v1 create \ --message '{role: user, content: "Patient reports headaches and nausea."}' \ --tag-1 patient_123 \ --extraction-prompt "You are a medical memory extraction system. Extract discrete facts about the patient." ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.memory.add({ messages: conversation, tag_1: 'patient_123', extraction_prompt: `You are a medical memory extraction system. Extract discrete facts about the patient, focusing on: - Symptoms and conditions - Medications and dosages - Allergies and reactions - Treatment preferences Output ONLY a valid JSON array with this structure: [{"content": "fact", "category": "allergy|medication|symptom|preference", "confidence": 0.9}]` }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.memory.v1.create( messages=conversation, tag_1='patient_123', extraction_prompt="""You are a medical memory extraction system. Extract discrete facts about the patient, focusing on: - Symptoms and conditions - Medications and dosages - Allergies and reactions - Treatment preferences Output ONLY a valid JSON array with this structure: [{"content": "fact", "category": "allergy|medication|symptom|preference", "confidence": 0.9}]""" ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Memory.V1.New(ctx, casedev.MemoryV1NewParams{ Messages: casedev.F(conversation), Tag1: casedev.F("patient_123"), ExtractionPrompt: casedev.F(`You are a medical memory extraction system. Extract discrete facts about the patient, focusing on: - Symptoms and conditions - Medications and dosages - Allergies and reactions - Treatment preferences Output ONLY a valid JSON array with this structure: [{"content": "fact", "category": "allergy|medication|symptom|preference", "confidence": 0.9}]`), }) ``` ## Pricing | Operation | Cost | | - | - | | Add memory | \$0.001 per operation | | Search | \$0.001 per operation | | List/Get/Delete | Free | > [!NOTE] > > LLM usage for fact extraction and embeddings is billed separately through the LLM service at standard rates. ## Related services > [card] [LLMs](/llms) > > Use memories as context for chat completions > [card] [Vault](/vault) > > Store documents, use Memory for extracted facts # Download results Source: https://docs.case.dev/ocr/download Download OCR results as text, JSON, or searchable PDF ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /ocr/v1/:id/download/:type ``` ## Output formats | Type | Description | | - | - | | `text` | Plain text extraction | | `json` | Structured data with word coordinates and confidence | | `pdf` | Searchable PDF with invisible text layer | ## Download text ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/ocr/v1/JOB_ID/download/text \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -o extracted.txt ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 download --id $JOB_ID --type text ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const text = await client.ocr.v1.download(jobId, 'text'); console.log(text); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') text = client.ocr.v1.download(job_id, 'text') print(text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} text, _ := client.Ocr.V1.Download(ctx, jobID, casedev.OcrV1DownloadParamsTypeText) // text is *http.Response with content body ``` ## Download searchable PDF The searchable PDF looks identical to the original but has an invisible text layer. Users can Ctrl+F to search. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/ocr/v1/JOB_ID/download/pdf \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -o searchable.pdf ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 download --id $JOB_ID --type pdf ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const pdf = await client.ocr.v1.download(jobId, 'pdf'); // Save to file fs.writeFileSync('searchable.pdf', Buffer.from(pdf)); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} pdf = client.ocr.v1.download(job_id, 'pdf') with open('searchable.pdf', 'wb') as f: f.write(pdf) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} pdf, _ := client.Ocr.V1.Download(ctx, jobID, casedev.OcrV1DownloadParamsTypePdf) // pdf is *http.Response with content body ``` ## Download structured JSON JSON includes word-level bounding boxes, confidence scores, and table structures. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/ocr/v1/JOB_ID/download/json \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -o ocr-data.json ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 download --id $JOB_ID --type json ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const data = await client.ocr.v1.download(jobId, 'json'); // Access word-level data for (const page of data.pages) { for (const block of page.blocks) { console.log(block.text, block.confidence); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} data = client.ocr.v1.download(job_id, 'json') # Access word-level data for page in data['pages']: for block in page['blocks']: print(block['text'], block['confidence']) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} jsonData, _ := client.Ocr.V1.Download(ctx, jobID, casedev.OcrV1DownloadParamsTypeJson) // jsonData is *http.Response with content body ``` ```json title="JSON structure" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "pages": [ { "page_number": 1, "width": 612, "height": 792, "blocks": [ { "type": "text", "text": "DEPOSITION OF JOHN SMITH", "confidence": 0.98, "bbox": {"x": 72, "y": 72, "width": 468, "height": 24}, "words": [ { "text": "DEPOSITION", "confidence": 0.99, "bbox": {"x": 72, "y": 72, "width": 120, "height": 24} } ] } ] } ], "tables": [...], "metadata": { "page_count": 150, "engine": "doctr" } } ``` ## Complete workflow ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Summarize this deposition."}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // 1. Submit document const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/deposition.pdf' }); // 2. Wait for completion let result = await client.ocr.v1.retrieve(job.id); while (result.status !== 'completed') { await new Promise(r => setTimeout(r, 5000)); result = await client.ocr.v1.retrieve(job.id); } // 3. Download results const text = await client.ocr.v1.download(job.id, 'text'); const pdf = await client.ocr.v1.download(job.id, 'pdf'); // 4. Use with LLM const analysis = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'system', content: 'Summarize this deposition.' }, { role: 'user', content: text } ] }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time # 1. Submit document job = client.ocr.v1.process( document_url='https://storage.example.com/deposition.pdf' ) # 2. Wait for completion result = client.ocr.v1.retrieve(job.id) while result.status != 'completed': time.sleep(5) result = client.ocr.v1.retrieve(job.id) # 3. Download results text = client.ocr.v1.download(job.id, 'text') pdf = client.ocr.v1.download(job.id, 'pdf') # 4. Use with LLM analysis = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[ {'role': 'system', 'content': 'Summarize this deposition.'}, {'role': 'user', 'content': text} ] ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} resp, _ := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleSystem), Content: casedev.F("Summarize this deposition."), }, { Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Summarize this deposition."), }, }), }) fmt.Println(resp.Choices[0].Message.Content) ``` # OCR Overview Source: https://docs.case.dev/ocr/index Extract text from PDFs, images, and scanned documents Specialized OCR for the messy reality of legal documents. We handle what generic providers can't: handwriting, poor scans, fax headers, and complex tables. ## Quick example ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/ocr/v1/process \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{}' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/document.pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Submit your user's document for processing const job = await client.ocr.v1.process({ document_url: uploadedDocumentUrl }); // Poll for completion let result = await client.ocr.v1.retrieve(job.id); while (result.status === 'pending' || result.status === 'processing') { await new Promise(r => setTimeout(r, 2000)); result = await client.ocr.v1.retrieve(job.id); } // Return extracted text to your user const text = await client.ocr.v1.download(job.id, 'text'); console.log(text); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import time client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Submit your user's document for processing job = client.ocr.v1.process( document_url=uploaded_document_url ) # Poll for completion result = client.ocr.v1.retrieve(job.id) while result.status in ['pending', 'processing']: time.sleep(2) result = client.ocr.v1.retrieve(job.id) # Return extracted text to your user text = client.ocr.v1.download(job.id, 'text') print(text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/document.pdf"), }) fmt.Println(job.ID) ``` ## Optimized for Legal | Feature | Why it matters for your app | | - | - | | **Handwriting Recognition** | Extract notes and annotations from uploaded documents | | **Table Reconstruction** | Preserve structure for financial statements and forms | | **Bates Stamp Handling** | Identify and index reference numbers separately | | **Searchable PDF (HOCR)** | Return documents with text layers your users can search | ## Engine Selection Choose based on your users' document types: | Engine | Best for | Speed | | - | - | - | | `doctr` | **Standard documents**. High speed, good accuracy for typed text. | Fast | | `paddleocr` | **Tables and forms**. Best-in-class table structure recognition. | Slower | ## Output formats | Format | Description | | - | - | | `text` | Plain text extraction | | `json` | Structured output with coordinates, confidence scores | | `pdf` | Searchable PDF (original with text layer) | ## Endpoints > [card] [Process](/ocr/process) > > `POST /ocr/v1/process` — Submit a document for OCR > [card] [Status](/ocr/status) > > `GET /ocr/v1/:id` — Check processing status > [card] [Download](/ocr/download) > > `GET /ocr/v1/:id/download/:type` — Download results ## Common patterns ### With webhooks (recommended for large files) ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "$DOCUMENT_URL" \ --callback-url "https://your-app.com/webhooks/ocr-complete" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: uploadedDocumentUrl, callback_url: 'https://your-app.com/webhooks/ocr-complete' }); // We POST results to your callback when done ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url=uploaded_document_url, callback_url='https://your-app.com/webhooks/ocr-complete' ) # We POST results to your callback when done ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F(uploadedDocumentURL), CallbackURL: casedev.F("https://your-app.com/webhooks/ocr-complete"), }) // We POST results to your callback when done ``` ### From a vault object Pass the `s3://` path of an object in one of your vaults: the vault's `filesBucket` and the object's `s3Key`. Paths outside your organization's vaults are rejected with `404`. For files in your own S3 bucket, presign them yourself and pass the HTTPS URL. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "s3:///" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 's3:///' }); // We handle presigning automatically ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='s3:///' ) # We handle presigning automatically ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("s3:///"), }) // We handle presigning automatically ``` ### With table extraction ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "$DOCUMENT_URL" \ --engine paddleocr \ --features.tables '{"format": "csv"}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: uploadedDocumentUrl, engine: 'paddleocr', features: { tables: { format: 'csv' } } }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url=uploaded_document_url, engine='paddleocr', features={ 'tables': {'format': 'csv'} } ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F(uploadedDocumentURL), Engine: casedev.F(casedev.OcrV1ProcessParamsEnginePaddleocr), Features: casedev.F(casedev.OcrV1ProcessParamsFeatures{ Tables: casedev.F(casedev.OcrV1ProcessParamsFeaturesTables{Format: casedev.F("csv")}), }), }) ``` ## Related services > [card] [Vault](/vault) > > Store OCR'd documents and make them searchable with semantic search > [card] [LLMs](/llms) > > Analyze extracted text with AI—summarize, classify, and extract entities # Process document Source: https://docs.case.dev/ocr/process Extract text from PDFs, images, and scanned documents Submit a document for OCR. We extract text, detect tables, and optionally generate a searchable PDF. Processing is async — you get a job ID immediately, then poll for results or use webhooks. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /ocr/v1/process ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/ocr/v1/process \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "document_url": "https://storage.example.com/scanned-deposition.pdf" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/document.pdf" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/scanned-deposition.pdf' }); console.log(job.id); // 1f4a195e-026b-41ff-b367-c61089f5f367 ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') job = client.ocr.v1.process( document_url='https://storage.example.com/scanned-deposition.pdf' ) print(job.id) # 1f4a195e-026b-41ff-b367-c61089f5f367 ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/document.pdf"), }) fmt.Println(job.ID) ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "1f4a195e-026b-41ff-b367-c61089f5f367", "status": "pending", "document_url": "https://storage.example.com/scanned-deposition.pdf", "engine": "doctr", "created_at": "2025-11-04T09:30:12Z", "links": { "self": "https://api.case.dev/ocr/v1/1f4a195e-026b-41ff-b367-c61089f5f367", "text": "https://api.case.dev/ocr/v1/1f4a195e-026b-41ff-b367-c61089f5f367/download/text", "json": "https://api.case.dev/ocr/v1/1f4a195e-026b-41ff-b367-c61089f5f367/download/json" } } ``` ## Parameters ### Required | Parameter | Type | Description | | - | - | - | | `document_url` | string | HTTP/HTTPS URL to your document, or the `s3://` path of an object in one of your vaults | ### Optional | Parameter | Type | Default | Description | | - | - | - | - | | `document_id` | string | auto-generated | Your internal reference ID | | `engine` | string | `doctr` | OCR engine (see below) | | `callback_url` | string | — | Webhook URL for completion notification | | `features` | object | `{}` | Additional processing options | ### OCR engines | Engine | Best for | Speed | | - | - | - | | `doctr` | Clean printed text, typed documents | Fast | | `paddleocr` | Tables, forms, complex layouts, handwriting | Medium | > [!NOTE] > > **For legal documents:** Start with `doctr`. If you're getting poor results on forms or tables, try `paddleocr`. ### Features Enable additional processing: ```json title="JSON" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "features": { "embed": {}, // Generate searchable PDF "tables": { // Extract tables as CSV "format": "csv" } } } ``` ## Checking status Poll the job to check if processing is complete: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 retrieve --id $JOB_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.ocr.v1.retrieve(job.id); if (result.status === 'completed') { // Download the extracted text const text = await client.ocr.v1.download(job.id, 'text'); console.log(text); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.ocr.v1.retrieve(job.id) if result.status == 'completed': # Download the extracted text text = client.ocr.v1.download(job.id, 'text') print(text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Ocr.V1.Get(ctx, jobID) fmt.Println(result.Status) ``` ## Using webhooks For large documents, use webhooks instead of polling: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/500-page-discovery.pdf" \ --callback-url "https://your-app.com/api/ocr-complete" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/500-page-discovery.pdf', callback_url: 'https://your-app.com/api/ocr-complete' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='https://storage.example.com/500-page-discovery.pdf', callback_url='https://your-app.com/api/ocr-complete' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/500-page-discovery.pdf"), CallbackURL: casedev.F("https://your-app.com/api/ocr-complete"), }) ``` We POST the completed job to your callback URL when processing finishes. ## Vault objects (`s3://`) If the document is already in one of your vaults, pass its `s3://` path: the vault's `filesBucket` followed by the object's `s3Key`. The API key must have read access to that vault and object. Any other `s3://` path returns `404`. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "s3:///" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 's3:///' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='s3:///' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("s3:///"), }) ``` We generate a short-lived presigned URL for the OCR service. For files in your own S3 bucket, presign them yourself and pass the HTTPS URL. ## Examples ### Scanned deposition ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/deposition-smith.pdf" \ --document-id smith-depo-2024 \ --engine doctr \ --features.embed '{}' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/deposition-smith.pdf', document_id: 'smith-depo-2024', engine: 'doctr', features: { embed: {} } // Generate searchable PDF }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='https://storage.example.com/deposition-smith.pdf', document_id='smith-depo-2024', engine='doctr', features={'embed': {}} # Generate searchable PDF ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/deposition-smith.pdf"), DocumentID: casedev.F("smith-depo-2024"), Engine: casedev.F(casedev.OcrV1ProcessParamsEngineDoctr), Features: casedev.F(casedev.OcrV1ProcessParamsFeatures{ Embed: casedev.F(casedev.OcrV1ProcessParamsFeaturesEmbed{}), }), }) ``` ### Medical records with tables ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/patient-records.pdf" \ --engine paddleocr \ --features.tables '{"format": "csv"}' \ --features.embed '{}' \ --callback-url "https://your-app.com/webhooks/ocr" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/patient-records.pdf', engine: 'paddleocr', // Better for tables and forms features: { tables: { format: 'csv' }, embed: {} }, callback_url: 'https://your-app.com/webhooks/ocr' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='https://storage.example.com/patient-records.pdf', engine='paddleocr', # Better for tables and forms features={ 'tables': {'format': 'csv'}, 'embed': {} }, callback_url='https://your-app.com/webhooks/ocr' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/patient-records.pdf"), Engine: casedev.F(casedev.OcrV1ProcessParamsEnginePaddleocr), Features: casedev.F(casedev.OcrV1ProcessParamsFeatures{ Tables: casedev.F(casedev.OcrV1ProcessParamsFeaturesTables{Format: casedev.F("csv")}), Embed: casedev.F(casedev.OcrV1ProcessParamsFeaturesEmbed{}), }), CallbackURL: casedev.F("https://your-app.com/webhooks/ocr"), }) ``` ### Handwritten notes ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 process \ --document-url "https://storage.example.com/witness-notes.jpg" \ --engine paddleocr ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const job = await client.ocr.v1.process({ document_url: 'https://storage.example.com/witness-notes.jpg', engine: 'paddleocr' // Better for handwriting }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job = client.ocr.v1.process( document_url='https://storage.example.com/witness-notes.jpg', engine='paddleocr' # Better for handwriting ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} job, _ := client.Ocr.V1.Process(ctx, casedev.OcrV1ProcessParams{ DocumentURL: casedev.F("https://storage.example.com/witness-notes.jpg"), Engine: casedev.F(casedev.OcrV1ProcessParamsEnginePaddleocr), }) ``` # Check status Source: https://docs.case.dev/ocr/status Get OCR job status and progress ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /ocr/v1/:id ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/ocr/v1/JOB_ID \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 retrieve --id $JOB_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const job = await client.ocr.v1.retrieve(jobId); console.log(job.status); // 'pending' | 'processing' | 'completed' | 'failed' console.log(job.chunks_completed); // Progress console.log(job.page_count); // Total pages ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') job = client.ocr.v1.retrieve(job_id) print(job.status) # 'pending' | 'processing' | 'completed' | 'failed' print(job.chunks_completed) # Progress print(job.page_count) # Total pages ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Ocr.V1.Get(ctx, jobID) fmt.Println(result.Status) ``` ## Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `include_text` | boolean | `false` | Include the full extracted text in a completed status response. | ```json title="Response (processing)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "1f4a195e-026b-41ff-b367-c61089f5f367", "status": "processing", "page_count": 245, "chunk_count": 50, "chunks_completed": 23, "chunks_processing": 15, "created_at": "2025-11-04T09:30:12Z" } ``` ```json title="Response (completed)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "1f4a195e-026b-41ff-b367-c61089f5f367", "status": "completed", "page_count": 245, "confidence": 0.96, "processing_time_ms": 1091000, "links": { "text": "https://api.case.dev/ocr/v1/.../download/text", "json": "https://api.case.dev/ocr/v1/.../download/json", "pdf": "https://api.case.dev/ocr/v1/.../download/pdf" } } ``` > [!NOTE] > > Status responses omit full OCR text by default. Download the `text` result when processing completes, or pass `include_text=true` when inline text is required. ## Status values | Status | Meaning | | - | - | | `pending` | Queued, not started | | `processing` | OCR in progress | | `completed` | Done, results ready | | `failed` | Processing failed | ## Failure details Failed jobs retain the readable `error` string and add `error_code`, `error_stage`, and `retryable`. Codes distinguish source download, document validation, engine, and output failures. `retryable: false` means the input or request needs attention before another attempt; it does not schedule a retry. Older jobs may have unclassified diagnostics. ```json title="Response (failed)" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "id": "1f4a195e-026b-41ff-b367-c61089f5f367", "status": "failed", "error": "1 of 3 OCR chunks failed.", "error_code": "chunks_failed", "error_stage": "chunk_processing", "retryable": false, "chunks_failed": 1, "chunk_count": 3, "failed_chunks": [ { "chunk_id": "chunk-2", "page_start": 11, "page_end": 20, "error": "The OCR engine ran out of memory. The document needs smaller processing chunks.", "error_code": "gpu_out_of_memory", "error_stage": "inference", "retryable": false } ] } ``` `failed_chunks` contains at most 20 samples with one-based inclusive page ranges. Use `chunks_failed` and `chunk_count` for exact totals. New Vision terminal callbacks include the same failure fields as status polling. Submission HTTP errors can carry safe diagnostics in the response's `data` object, alongside the original HTTP status. Match failures using `error_code`, rather than the human-readable `error` message, which may change. Failed-job responses retain validated identity, timing, and progress fields; they exclude upstream debug fields, traces, source URLs, and result links. ## Polling example ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev ocr:v1 retrieve --id $JOB_ID ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function waitForOCR(jobId: string) { while (true) { const job = await client.ocr.v1.retrieve(jobId); if (job.status === 'completed') { return job; } if (job.status === 'failed') { throw new Error('OCR failed'); } // Wait 5 seconds before checking again await new Promise(r => setTimeout(r, 5000)); } } const result = await waitForOCR(jobId); const text = await client.ocr.v1.download(jobId, 'text'); console.log(text); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import time def wait_for_ocr(job_id: str): while True: job = client.ocr.v1.retrieve(job_id) if job.status == 'completed': return job if job.status == 'failed': raise Exception('OCR failed') # Wait 5 seconds before checking again time.sleep(5) result = wait_for_ocr(job_id) text = client.ocr.v1.download(job_id, 'text') print(text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Ocr.V1.Get(ctx, jobID) fmt.Println(result.Status) ``` > [!NOTE] > > **Use webhooks for large documents.** Set `callback_url` when submitting to avoid polling. # Privilege Detection Overview Source: https://docs.case.dev/privilege/index Detect attorney-client privilege and work product protection in documents for e-discovery ## The Problem E-discovery teams review thousands of documents manually to identify privileged content. Miss one privileged document in production, and you've waived protection. Over-designate, and you face sanctions for obstruction. ## The Solution An AI-powered privilege detection API that analyzes documents for attorney-client privilege, work product doctrine, and other protected communications. Get confidence scores, category breakdowns, and actionable recommendations for each document. ```mermaid theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} flowchart TD A["Ingest
Upload documents to Vault or send content directly"] --> B["Analyze
privilege.detect(...) scores privilege and rationale"] B --> C["Triage
Act on the recommendation: withhold, redact, produce, or review"] ``` ## Quick start ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Analyze content for privilege curl -X POST https://api.case.dev/privilege/v1/detect \ -H "Authorization: Bearer $CASEDEV_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "content": "Attorney memo: Confidential legal advice regarding...", "categories": ["attorney_client", "work_product"], "include_rationale": true }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev privilege:v1 detect \ --content "Attorney memo: Confidential legal advice regarding..." \ --category attorney_client,work_product \ --include-rationale ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Analyze document content for privilege const result = await client.privilege.detect({ content: 'Attorney memo: Confidential legal advice regarding...', categories: ['attorney_client', 'work_product'], include_rationale: true, }); if (result.privileged) { console.log(`Privileged (${result.confidence * 100}% confidence)`); console.log(`Recommendation: ${result.recommendation}`); // Review detected categories for (const cat of result.categories) { if (cat.detected) { console.log(` ${cat.type}: ${cat.rationale}`); } } } else { console.log('No privilege detected - safe to produce'); } // Or analyze a document already in your Vault const vaultResult = await client.privilege.detect({ document_id: 'doc_abc123', vault_id: 'vault_xyz789', }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Analyze document content for privilege result = client.privilege.v1.detect( content='Attorney memo: Confidential legal advice regarding...', categories=['attorney_client', 'work_product'], include_rationale=True, ) if result.privileged: print(f'Privileged ({result.confidence * 100}% confidence)') print(f'Recommendation: {result.recommendation}') # Review detected categories for cat in result.categories: if cat.detected: print(f' {cat.type}: {cat.rationale}') else: print('No privilege detected - safe to produce') # Or analyze a document already in your Vault vault_result = client.privilege.v1.detect( document_id='doc_abc123', vault_id='vault_xyz789', ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Privilege.V1.Detect(ctx, casedev.PrivilegeV1DetectParams{ Content: casedev.F("Attorney memo: Confidential legal advice regarding..."), Categories: casedev.F([]string{"attorney_client", "work_product"}), IncludeRationale: casedev.F(true), }) if result.Privileged { fmt.Printf("Privileged (%0.f%% confidence)\n", result.Confidence*100) fmt.Printf("Recommendation: %s\n", result.Recommendation) for _, cat := range result.Categories { if cat.Detected { fmt.Printf(" %s: %s\n", cat.Type, cat.Rationale) } } } else { fmt.Println("No privilege detected - safe to produce") } ``` ## Endpoints > [card] [detect](/api-reference/privilege/detect-privileged-content) > > Analyze document content for privilege indicators across multiple categories ## Privilege categories | Category | Description | | - | - | | `attorney_client` | Communications between attorney and client for legal advice | | `work_product` | Materials prepared in anticipation of litigation | | `common_interest` | Shared communications under joint defense agreements | | `litigation_hold` | Documents subject to preservation obligations | ## Recommendations The API returns one of four recommendations based on analysis: | Recommendation | When returned | Suggested action | | - | - | - | | `withhold` | High confidence privilege detected | Do not produce; log for privilege log | | `redact` | Partial privilege or mixed content | Redact privileged portions before production | | `produce` | No privilege indicators found | Safe for production | | `review` | Ambiguous or borderline cases | Requires attorney review | ## Vault integration When you provide a `document_id` and `vault_id`, the API: 1. Retrieves the document content from your Vault 2. Analyzes it for privilege indicators 3. Stores the analysis results in the document's `privilege_analysis` metadata field This enables bulk privilege review workflows where results are persisted alongside documents. ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Analyze and store results in Vault metadata casedev privilege:v1 detect \ --document-id doc_abc123 \ --vault-id vault_xyz789 # Retrieve the document with stored analysis casedev vault:objects retrieve --id vault_xyz789 --object-id doc_abc123 ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Analyze and store results in Vault metadata const result = await client.privilege.detect({ document_id: 'doc_abc123', vault_id: 'vault_xyz789', }); // Results are now stored in the document metadata // Retrieve later with vault.get() const doc = await client.vault.get({ vault_id: 'vault_xyz789', object_id: 'doc_abc123' }); console.log(doc.metadata.privilege_analysis); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Analyze and store results in Vault metadata result = client.privilege.v1.detect( document_id='doc_abc123', vault_id='vault_xyz789', ) # Results are now stored in the document metadata # Retrieve later with vault.get() doc = client.vault.get(vault_id='vault_xyz789', object_id='doc_abc123') print(doc.metadata.privilege_analysis) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Analyze and store results in Vault metadata result, _ := client.Privilege.V1.Detect(ctx, casedev.PrivilegeV1DetectParams{ DocumentID: casedev.F("doc_abc123"), VaultID: casedev.F("vault_xyz789"), }) // Results are now stored in the document metadata // Retrieve later with vault.get() doc, _ := client.Vault.Get(ctx, "vault_xyz789", "doc_abc123") fmt.Println(doc.Metadata.PrivilegeAnalysis) ``` ## Permissions | Input Type | Required Permissions | | - | - | | Raw text (`content`) | `chat` | | Vault document (`document_id`) | `chat` + `vault` | ## Limits * **Maximum document size:** 200,000 characters * For larger documents, split into logical sections and analyze separately ## Supported jurisdictions Currently supports **US-Federal** privilege standards. Additional jurisdictions coming soon. ## Related services > [card] [Vault](/vault) > > Store documents and run bulk privilege detection workflows > [card] [Legal Research](/legal-research) > > Verify citations in privileged documents before logging > [card] [OCR](/ocr) > > Extract text from scanned documents before privilege analysis # Rate Limits & Usage Source: https://docs.case.dev/rate-limits Understanding Case.dev rate limits and usage tiers ## How Rate Limits Work * **Requests Per Minute (RPM)** - Each service has its own rate limit * **Per-Organization** - Limits apply to your entire organization, not individual API keys * **Tier-Based** - Your tier determines your limits (see below) * **Automatic Upgrades** - Tiers increase automatically based on spend and account age ## Rate Limit Headers Every API response includes rate limit information: ```http theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} x-ratelimit-limit-requests: 600 x-ratelimit-remaining-requests: 599 x-ratelimit-reset-requests: 45s x-ratelimit-tier: tier_1 ``` | Header | Description | | - | - | | `x-ratelimit-limit-requests` | Maximum requests per minute for this service | | `x-ratelimit-remaining-requests` | Requests remaining in current window | | `x-ratelimit-reset-requests` | Time until limit resets | | `x-ratelimit-tier` | Your current tier | ## Tier System Your tier is determined by **lifetime spend** and **account age**: | Tier | Spend Required | Account Age | Example Limits | | - | - | - | - | | **Free** | \$0 | Any | 100 LLM RPM, 50 OCR RPM | | **Tier 1** | \$10+ | Any | 600 LLM RPM, 200 OCR RPM | | **Tier 2** | \$50+ | 7+ days | 2,000 LLM RPM, 600 OCR RPM | | **Tier 3** | \$100+ | 14+ days | 5,000 LLM RPM, 1,500 OCR RPM | | **Tier 4** | \$500+ | 30+ days | 20,000 LLM RPM, 5,000 OCR RPM | | **Enterprise** | Custom | Contract | 100,000+ LLM RPM | ## Rate Limits by Service | Service | Free | Tier 1 | Tier 2 | Tier 3 | Tier 4 | Enterprise | | - | - | - | - | - | - | - | | **LLMs** | 100 | 600 | 2,000 | 5,000 | 20,000 | 100,000 | | **OCR** | 50 | 200 | 600 | 1,500 | 5,000 | 50,000 | | **Voice** | 50 | 300 | 1,000 | 3,000 | 10,000 | 50,000 | | **Search** | 200 | 1,000 | 3,000 | 10,000 | 50,000 | 200,000 | | **Vaults** | 200 | 600 | 2,000 | 5,000 | 20,000 | 100,000 | | **Convert** | 30 | 100 | 300 | 1,000 | 3,000 | 20,000 | | **Workflows** | 50 | 200 | 600 | 2,000 | 5,000 | 50,000 | *All values are requests per minute (RPM)* ## Rate Limit Errors When you exceed your rate limit, you'll receive a `429 Too Many Requests` response: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "error": { "message": "Rate limit exceeded. You have made too many requests to the llm API. Please retry after 45 seconds.", "type": "rate_limit_error", "code": "rate_limit_exceeded" }, "tier": "tier_1", "limit": 600, "reset_at": "2024-01-15T12:00:45Z" } ``` ### Handling Rate Limits ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Errors are printed to stderr with status codes casedev llm:v1:chat create-completion \ --model openai/gpt-6-sol \ --message '{role: user, content: "Hello!"}' # On rate limit: {"error": {"message": "...", "type": "rate_limit_error", "code": 429}} ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_...' }); try { const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [{ role: 'user', content: 'Hello!' }] }); } catch (error) { if (error.status === 429) { // Wait and retry const resetTime = error.headers['x-ratelimit-reset-requests']; console.log(`Rate limited. Retry after ${resetTime}`); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} from casedev import Casedev, RateLimitError client = Casedev() try: response = client.llm.v1.chat.create_completion( model='openai/gpt-6-sol', messages=[{'role': 'user', 'content': 'Hello!'}] ) except RateLimitError as e: print(f'Rate limited. Retry after: {e.response.headers.get("retry-after")}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev "github.com/CaseMark/casedev-go" client := casedev.NewClient() resp, err := client.Llm.V1.Chat.NewCompletion(ctx, casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{ {Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Hello!")}, }), }) if err != nil { var apiErr *casedev.Error if errors.As(err, &apiErr) { fmt.Printf("Status: %d, Message: %s\n", apiErr.StatusCode, apiErr.Message) } } ``` All our SDKs (TypeScript, Python, Go) and the CLI automatically handle rate limits with exponential backoff retries. See the [SDKs page](/sdks) for details. *** ## Prepaid Credits Case.dev uses a prepaid credit system. You must have a positive credit balance to make API calls. ### Credit Balance * **Add Credits** - Purchase credits from the [billing dashboard](https://console.case.dev/billing) * **Auto Top-Up** - Configure automatic top-up when balance drops below a threshold * **Balance Check** - Every API call checks your balance (cached, sub-millisecond) ### Insufficient Balance When your credit balance is zero, you'll receive a `402 Payment Required` response: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "error": { "message": "Insufficient credit balance. Please add credits to continue using the API.", "type": "insufficient_balance", "code": "payment_required", "balance_cents": 0 } } ``` ### Auto Top-Up Enable automatic credit purchases when your balance drops low: 1. Go to [Billing → Prepaid Credits](https://console.case.dev/billing) 2. Toggle **Auto Top-Up** on 3. Set your threshold (e.g., \$10) 4. Set your top-up amount (e.g., \$50) When your balance drops below $10, we'll automatically charge your card for $50. *** ## Best Practices ### 1. Implement Retries with Backoff ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function withRetry(fn, maxRetries = 3) { for (let i = 0; i < maxRetries; i++) { try { return await fn(); } catch (error) { if (error.status === 429 && i < maxRetries - 1) { const delay = Math.pow(2, i) * 1000; // 1s, 2s, 4s await new Promise(r => setTimeout(r, delay)); continue; } throw error; } } } ``` ### 2. Monitor Your Usage Check rate limit headers on every response to monitor your usage: ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const response = await fetch('https://api.case.dev/llm/v1/chat/completions', { method: 'POST', headers: { 'Authorization': 'Bearer sk_case_...' }, body: JSON.stringify({ ... }) }); const remaining = response.headers.get('x-ratelimit-remaining-requests'); if (parseInt(remaining) < 10) { console.warn('Approaching rate limit!'); } ``` ### 3. Use Batch Operations When processing many items, use batch endpoints where available to reduce request count. ### 4. Cache Results Cache API responses when appropriate to reduce duplicate requests. *** ## Increasing Your Limits ### Automatic Tier Upgrades Your tier upgrades automatically as you: * Add more credits * Maintain account history ### Enterprise Plans Need higher limits? [Contact us](mailto:support@casemark.com) for: * Custom rate limits (100K+ RPM) * Dedicated infrastructure * SLA guarantees * Priority support *** ## FAQ ### How are rate limits counted? Rate limits are counted per organization, per service. A request to `/llm/v1/chat/completions` counts against your LLM limit, while `/ocr/v1/process` counts against OCR. ### Do rate limits apply to webhooks? No, incoming webhooks to `/billing/stripe/webhook` and similar endpoints are not rate limited. ### What happens if I hit a rate limit? You'll receive a `429` response with retry information. Our SDKs handle this automatically with exponential backoff. ### Can I see my current tier? Yes, check the `x-ratelimit-tier` header on any API response, or visit the [billing dashboard](https://console.case.dev/billing). ### How quickly do tier upgrades take effect? Tier upgrades are calculated in real-time. As soon as your lifetime spend crosses a threshold, your new limits apply. *** ## Next Steps > [card] [Services Catalog](/services) > > Explore all available services > [card] [Billing Dashboard](https://console.case.dev/billing) > > Manage your credits and view usage > [card] [Cookbooks](/cookbooks) > > See real-world integration examples # SDKs Source: https://docs.case.dev/sdks Official client libraries for the Case.dev API Official client libraries for integrating Case.dev into your application. ## Available SDKs We provide official SDKs for the following languages: * **[TypeScript / JavaScript](#typescript)** - For Node.js, Deno, Bun, and browsers * **[Python](#python)** - Synchronous and async support * **[Go](#go)** - Full type-safe Go SDK All SDKs are type-safe, well-documented, and maintained automatically from our OpenAPI specification. *** ## TypeScript [![npm](https://img.shields.io/npm/v/casedev.svg)](https://npmjs.org/package/casedev) ### Installation ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} npm install casedev ``` ### Quick Start ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY, environment: 'production' // or 'local' for development }); // Create a vault const vault = await client.vault.create({ name: 'My Documents', description: 'Legal document repository' }); // Chat with an LLM const response = await client.llm.v1.chat.createCompletion({ model: 'openai/gpt-6-sol', messages: [ { role: 'user', content: 'Summarize this contract...' } ] }); ``` ### Features * Full TypeScript support with type inference * Promise-based async API * Automatic retries with exponential backoff * Streaming support for real-time responses * Works in Node.js, Deno, Bun, and browsers ### Repository [github.com/CaseMark/casedev-typescript](https://github.com/CaseMark/casedev-typescript) *** ## Python [![PyPI](https://img.shields.io/pypi/v/casedev.svg)](https://pypi.org/project/casedev/) ### Installation ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} pip install casedev ``` ### Quick Start ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} from casedev import Casedev client = Casedev( api_key="sk_case_...", environment="production" # or "local" ) # Create a vault vault = client.vault.create( name="My Documents", description="Legal document repository" ) # Chat with an LLM response = client.llm.v1.chat.create_completion( model="openai/gpt-6-sol", messages=[ {"role": "user", "content": "Summarize this contract..."} ] ) print(response.choices[0].message.content) ``` ### Async Support ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} from casedev import AsyncCasedev import asyncio async def main(): async with AsyncCasedev(api_key="sk_case_...") as client: response = await client.llm.v1.chat.create_completion( messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) asyncio.run(main()) ``` ### Features * Full type hints with modern Python * Synchronous and asynchronous clients * aiohttp support for better async performance * Automatic retries and error handling * Python 3.9+ support ### Repository [github.com/CaseMark/casedev-python](https://github.com/CaseMark/casedev-python) *** ## Go ### Installation ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} go get -u github.com/CaseMark/casedev-go ``` Requires Go 1.22+. ### Quick Start ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} package main import ( "context" "fmt" casedev "github.com/CaseMark/casedev-go" "github.com/CaseMark/casedev-go/option" ) func main() { client := casedev.NewClient( option.WithAPIKey("sk_case_YOUR_API_KEY"), // or set CASEDEV_API_KEY env var option.WithEnvironmentProduction(), // default ) // Create a vault vault, _ := client.Vault.New(context.TODO(), casedev.VaultNewParams{ Name: casedev.F("My Documents"), Description: casedev.F("Legal document repository"), }) // Chat with an LLM resp, _ := client.Llm.V1.Chat.NewCompletion(context.TODO(), casedev.LlmV1ChatNewCompletionParams{ Model: casedev.F("openai/gpt-6-sol"), Messages: casedev.F([]casedev.LlmV1ChatNewCompletionParamsMessage{{ Role: casedev.F(casedev.LlmV1ChatNewCompletionParamsMessagesRoleUser), Content: casedev.F("Summarize this contract..."), }}), }) fmt.Println(resp.Choices[0].Message.Content) } ``` ### Features * Full type safety with Go generics * Automatic retries with exponential backoff (2 retries by default) * Configurable via `option.With*` helpers * Environment variable auto-detection (`CASEDEV_API_KEY`) * Raw HTTP response access via `option.WithResponseInto` ### Repository [github.com/CaseMark/casedev-go](https://github.com/CaseMark/casedev-go) *** ## Authentication All SDKs require an API key from the [Case.dev dashboard](https://app.case.dev). ```bash title="Shell" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Set as environment variable export CASEDEV_API_KEY=sk_case_... ``` The Go SDK automatically reads the `CASEDEV_API_KEY` environment variable. No additional configuration is needed. API keys starting with `sk_case_` are production keys. Development keys are available for testing. ### Scoped Permissions API keys can be scoped to specific services with read or write access. If your key lacks permission for a service, you'll receive a `403 Forbidden` error. Check your key's permissions in the dashboard. ## Error Handling All SDKs provide typed error classes for handling API errors: ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} try { await client.vault.retrieve('invalid-id'); } catch (error) { if (error instanceof Casedev.NotFoundError) { console.log('Vault not found:', error.status); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} from casedev import NotFoundError try: client.vault.retrieve('invalid-id') except NotFoundError as e: print(f'Vault not found: {e.status}') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import ( "errors" casedev "github.com/CaseMark/casedev-go" ) vault, err := client.Vault.Get(context.TODO(), "invalid-id") if err != nil { var apierr *casedev.Error if errors.As(err, &apierr) { fmt.Println("Status:", apierr.StatusCode) // 404 } } ``` ## Rate Limits All API requests are subject to rate limits based on your plan. SDKs automatically handle rate limit responses with exponential backoff retries. ## Support * **Documentation:** [docs.case.dev](https://docs.case.dev) * **Email:** [support@casemark.com](mailto:support@casemark.com) * **Community:** [case.dev/slack](https://case.dev/slack) * **GitHub Issues:** Report SDK bugs in the respective repository ## Open Source All SDKs are open source under the Apache 2.0 license. Contributions are welcome! *** ## Next Steps > [card] [Getting Started](/getting-started) > > Integration tutorials with step-by-step examples > [card] [Services Catalog](/services) > > Browse all available services > [card] [Cookbooks](/cookbooks) > > Reference implementations and architecture patterns # All Services Source: https://docs.case.dev/services Complete reference for all Case.dev platform services Case.dev provides a unified platform of composable services for building legal AI applications. Every service is API-first, SOC 2 Type II compliant, and designed to work together seamlessly in your app. > [card] [Matters](/matters/index) > > Matter-native orchestration, work items, parties, logs, shares, and human review. > [card] [Linc](/linc/index) > > Durable legal agent sessions with sandboxed tools, files, skills, and resumable state. > [card] [Vault](/vault/index) > > Zero-trust document storage with built-in RAG. Your users upload PDFs, you get queryable vector > indexes instantly. > [card] [Connectors](/connectors/index) > > Move documents between provider folders and vaults. Clio Manage and Google Drive. > [card] [LLMs](/llms/index) > > Unified gateway to a curated catalog of GPT, Claude, Gemini, and CaseMark models. [Browse models > →](https://case.dev/models) > [card] [OCR](/ocr/index) > > Specialized OCR for legal documents. Handles handwriting, stamps, tables, and low-quality scans. > [card] [Compute](/compute/index) > > On-demand GPU instances for AI workloads. Mount your vaults as a filesystem, SSH in, run. > [card] [Voice](/voice/index) > > Legal-grade transcription with speaker diarization and timestamping. Perfect for depositions and > meetings. > [card] [Search](/web-search/index) > > Programmatic web search. Let your users retrieve web content with AI-generated answers and > citations. > [card] [Legal Research](/legal-research/index) > > Verify legal citations against authoritative case law. Catch AI hallucinations before they reach > court. > [card] [Privilege Detection](/privilege/index) > > AI-assisted privilege review for attorney-client, work product, and common interest analysis. > Supports e-discovery triage without replacing attorney judgment. > [card] [Memory](/memory/index) > > Persistent memory for AI agents. Store and retrieve context across sessions. > [card] [Media](/media/index) > > Captioned clips, transcript retrieval, and word-level transcript search for media evidence. > [card] [Translation](/translation/index) > > Neural machine translation for 100+ languages. Auto-detect source language and preserve > formatting. > [card] [Usage](/usage/index) > > Customer-facing usage snapshots and usage event webhooks. > [card] [Skills](/skills) > > 870+ curated legal skills plus org-scoped custom skills. Semantic search, CRUD API, and MCP > integration for AI agents. > [!NOTE] > > **Sovereign Legal AI** — Dedicated model deployments for clients with specific compliance or > contractual requirements. Deploy in your own cloud or use dedicated infrastructure. [Learn more > →](/compute/sovereign-ai) *** ## Which service should you integrate? | To build... | Integrate this service | | - | - | | Intensive, stateful agent work | [Linc](/linc/index) | | Document storage and search | [Vault](/vault/index) | | Event-driven integrations | [Events](/events/index) | | AI chat and completions | [LLMs](/llms/index) | | Text extraction from scans/images | [OCR](/ocr/index) | | GPU workloads (training, OCR, inference) | [Compute](/compute/index) | | Audio transcription | [Voice](/voice/index) | | Web search and AI answers | [Search](/web-search/index) | | Citation verification | [Legal Research](/legal-research/index) | | E-discovery privilege review | [Privilege Detection](/privilege/index) | | Persistent agent context | [Memory](/memory/index) | | Captioned clips and transcript utilities | [Media](/media/index) | | Multi-language translation | [Translation](/translation/index) | | Usage reporting and event delivery | [Usage](/usage/index) | | Legal skills for AI agents | [Skills](/skills) | *** ## Security & Compliance All Case.dev services are enterprise-ready: * **SOC 2 Type II Certified** — Annual audits by independent assessors * **HIPAA Compliant** — BAAs available upon request * **Zero-Retention Agreements** — With LLM providers (no training on your data) * **Encrypted at Rest** — AES-256 encryption via AWS KMS * **Encrypted in Transit** — TLS 1.3 for all API traffic * **Audit Logging** — Complete trail of API access and operations **Data Residency:** US-based infrastructure by default. EU and sovereign options available for enterprise. **Vulnerability Reporting:** [security@casemark.com](mailto:security@casemark.com) *** ## Start Building > [card] [Quickstart Guides](/getting-started/index) > > Integration tutorials with step-by-step code examples > [card] [Cookbooks](/cookbooks/index) > > Reference implementations and architecture patterns > [card] [SDKs](/sdks) > > Official client libraries for TypeScript and Python # Custom Skills Source: https://docs.case.dev/skills/custom-skills Create org-scoped skills with embeddings that work alongside the curated library Build your own legal AI skills and make them available to your organization's Linc sessions. Custom skills are stored with vector embeddings and automatically appear in unified search alongside the 870+ curated skills. > [!NOTE] > > **Requires authentication.** All custom skills endpoints require a Case.dev API key with `skills` > permission scope. ## How It Works Custom skills live in your organization and are the canonical way to manage private skills. When your agents search for skills via `/skills/resolve`, results from your custom skills are merged with curated skills in a single ranked list. If a custom skill has the same slug as a curated skill, the custom skill takes priority for your organization. Use the `/skills` API for the full lifecycle: | Endpoint | Purpose | | - | - | | `POST /skills` | Create a custom skill, optionally with bundled files | | `GET /skills/custom` | List your organization's custom skills | | `GET /skills/:slug` | Read a custom or curated skill by slug | | `PUT /skills/:slug` | Update a custom skill and optionally replace bundled files | | `DELETE /skills/:slug` | Delete a custom skill | | `GET /skills/:slug/export` | Inspect the installable file tree for an agent runtime | | `GET /skills/resolve` | Search custom and curated skills together | Each custom skill includes: * **Content** in markdown, up to 64KB * **Vector embedding** (generated automatically) for semantic search * **Tags** for categorization and search boosting * **Metadata** for arbitrary key-value data * **Optional companion files** for Skills.sh-style `SKILL.md` bundles, scripts, templates, and references * **Version tracking** with automatic increment on updates * **Soft-delete** so deleted skills can be recreated ## Create a Skill ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/skills \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Deposition Prep Checklist", "summary": "Comprehensive checklist for deposition preparation.", "content": "# Deposition Prep Checklist\n\n## Pre-Deposition\n...", "tags": ["litigation", "deposition", "checklist"], "metadata": { "author": "Jane Smith", "practice_area": "litigation" } }' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev' const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }) const skill = await client.skills.create({ name: 'Deposition Prep Checklist', summary: 'Comprehensive checklist for deposition preparation in federal litigation.', content: '# Deposition Prep Checklist\n\n## Pre-Deposition\n- Review all relevant documents\n- Prepare witness outline', tags: ['litigation', 'deposition', 'checklist'], metadata: { author: 'Jane Smith', practice_area: 'litigation' }, }) console.log(skill.slug) // "deposition-prep-checklist" ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import os import casedev client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) skill = client.skills.create( name='Deposition Prep Checklist', summary='Comprehensive checklist for deposition preparation in federal litigation.', content='# Deposition Prep Checklist\n\n## Pre-Deposition\n- Review all relevant documents', tags=['litigation', 'deposition', 'checklist'], metadata={'author': 'Jane Smith', 'practice_area': 'litigation'}, ) print(skill.slug) # "deposition-prep-checklist" ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} package main import ( "context" "fmt" "github.com/CaseMark/casedev-go" ) func main() { client := casedev.NewClient() skill, _ := client.Skills.New(context.TODO(), casedev.SkillNewParams{ Name: casedev.F("Deposition Prep Checklist"), Summary: casedev.F("Comprehensive checklist for deposition preparation."), Content: casedev.F("# Deposition Prep Checklist\n\n## Pre-Deposition\n..."), Tags: casedev.F([]string{"litigation", "deposition", "checklist"}), }) fmt.Println(skill.Slug) } ``` **Request body:** | Field | Type | Required | Description | | - | - | - | - | | `name` | string | Yes | Skill name (max 256 chars) | | `content` | string | Yes | Full skill content in markdown (max 64KB) | | `slug` | string | No | URL-safe identifier. Auto-generated from name if omitted | | `summary` | string | No | Brief description (max 1000 chars) | | `tags` | string\[] | No | Tags for categorization and search boosting | | `metadata` | object | No | Arbitrary key-value metadata | | `files` | object\[] | No | Companion files installed under the skill directory in agent sandboxes | ### Bundled Skill Files Use `files[]` when a skill needs scripts, references, examples, or templates in addition to its root `SKILL.md` instructions. The root `content` becomes `/SKILL.md`; each companion file is installed at `/`. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/skills \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Contract Redline Review", "slug": "contract-redline-review", "summary": "Review contract redlines with a firm-specific checklist.", "content": "# Contract Redline Review\n\nUse the checklist and script before drafting comments.", "tags": ["transactional", "contracts"], "files": [ { "path": "references/checklist.md", "content": "# Checklist\n\n- Confirm governing law\n- Flag assignment restrictions" }, { "path": "scripts/clauses.ts", "content": "export const riskyClauses = [\"assignment\", \"indemnity\"];", "contentType": "text/typescript" } ] }' ``` Bundled paths must be relative, cannot contain `.` or `..` segments, and cannot be `SKILL.md`. Send `files[]` again on `PUT /skills/:slug` to replace the companion tree; omit `files` to leave companion files unchanged. Text companion files use `encoding: "utf8"` by default and may contain up to 65,536 characters. For binary companions such as fonts or images, base64-encode the original bytes, set `encoding: "base64"`, and include the file's media type. Binary files may contain up to 262,144 decoded bytes, and the complete companion tree may contain up to 12 MiB of decoded content. ```json title="Binary companion file" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "path": "assets/fonts/report.woff2", "content": "d09GMgABAAAAAA...", "encoding": "base64", "contentType": "font/woff2" } ``` Base64 content must use the canonical padded representation. Case.dev validates the decoded size and writes the original bytes into agent sandboxes. **Response** (201): ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "slug": "deposition-prep-checklist", "name": "Deposition Prep Checklist", "summary": "Comprehensive checklist for deposition preparation.", "content": "# Deposition Prep Checklist\n\n...", "tags": ["litigation", "deposition", "checklist"], "metadata": { "author": "Jane Smith", "practice_area": "litigation" }, "bundle": null, "version": 1, "created_at": "2026-03-16T20:09:59.333Z" } ``` > [!NOTE] > > **Slugs** are unique per organization. Reserved slugs (`resolve`, `custom`) cannot be used. If you > omit `slug`, one is auto-generated from the skill name. ## Read a Skill Retrieve a skill by slug. For authenticated users, custom skills are checked first, then curated skills. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/skills/deposition-prep-checklist \ -H "Authorization: Bearer $CASE_API_KEY" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const skill = await client.skills.read('deposition-prep-checklist') console.log(skill.source) // "custom" or "curated" ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} skill = client.skills.read('deposition-prep-checklist') print(skill.source) # "custom" or "curated" ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} skill, _ := client.Skills.Read(context.TODO(), "deposition-prep-checklist") fmt.Println(skill.Source) ``` The response includes a `source` field indicating whether the skill is `"custom"` (your organization's) or `"curated"` (from the open-source library). For bundled root skills, `GET /skills/:slug` also includes a `bundle` object: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "bundle": { "role": "root", "files": [ { "slug": "contract-redline-review--file--references-checklist-md-a1b2c3d4e5f6", "path": "references/checklist.md", "content_type": "text/plain; charset=utf-8", "encoding": "utf8" } ] } } ``` ## Export a Skill Tree Use `GET /skills/:slug/export` to inspect the exact files that will be installed into an agent runtime sandbox. Custom skills in your organization are resolved first; curated skills are used as a fallback. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/skills/contract-redline-review/export?target=agents" \ -H "Authorization: Bearer $CASE_API_KEY" ``` Response: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "slug": "contract-redline-review", "target": "agents", "root": "/contract-redline-review", "source": "custom", "files": [ { "path": "contract-redline-review/SKILL.md", "content": "# Contract Redline Review\n\n...", "content_type": "text/markdown; charset=utf-8", "encoding": "utf8", "sha256": "d3b07384d113edec49eaa6238ad5ff00", "size_bytes": 128 }, { "path": "contract-redline-review/references/checklist.md", "content": "# Checklist\n\n...", "content_type": "text/plain; charset=utf-8", "encoding": "utf8", "sha256": "98f13708210194c475687be6106a3b84", "size_bytes": 64 } ] } ``` Most applications do not need to call export directly. Pass `skillSlugs` when creating a Linc session and Case.dev installs the right tree for that sandbox. ## Install Skills in Linc Sessions When creating a session with `POST /linc/v1/sessions`, pass `skillSlugs` to install custom or curated skills before Linc starts. Case.dev installs the root `SKILL.md` and any companion files into the sandbox's skill directory before the runtime process starts. The session creation response reports which requested skills were loaded and which were missing. ## Search Skills Use `/skills/resolve` to search across both curated and custom skills. Results are ranked by relevance using semantic search, BM25 text matching, and tag boosting. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/skills/resolve?q=deposition+preparation&limit=5" \ -H "Authorization: Bearer $CASE_API_KEY" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const results = await client.skills.resolve({ q: 'deposition preparation', limit: 5, }) for (const skill of results.results) { console.log(skill.source + ': ' + skill.name + ' (' + skill.score + ')') } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results = client.skills.resolve(q='deposition preparation', limit=5) for skill in results.results: print(f"{skill.source}: {skill.name} ({skill.score})") ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} results, _ := client.Skills.Resolve(context.TODO(), casedev.SkillResolveParams{ Q: casedev.F("deposition preparation"), Limit: casedev.Int(5), }) for _, skill := range results.Results { fmt.Printf("%s: %s (%f)\n", skill.Source, skill.Name, skill.Score) } ``` Each result includes: | Field | Description | | - | - | | `slug` | Skill identifier | | `name` | Skill name | | `summary` | Brief description | | `tags` | Practice area tags | | `score` | Relevance score (0-1) | | `source` | `"curated"` or `"custom"` | > [!TIP] > > Custom skills with the same slug as a curated skill take priority in your organization's results. > This lets you override curated skills with org-specific versions. ## List Custom Skills List all custom skills in your organization, with optional filtering. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # List all curl "https://api.case.dev/skills/custom" \ -H "Authorization: Bearer $CASE_API_KEY" # Filter by tag curl "https://api.case.dev/skills/custom?tag=litigation" \ -H "Authorization: Bearer $CASE_API_KEY" # Paginate curl "https://api.case.dev/skills/custom?limit=10&cursor=csk_abc123" \ -H "Authorization: Bearer $CASE_API_KEY" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // List all const list = await client.skills.custom.list() // Filter by tag const filtered = await client.skills.custom.list({ tag: 'litigation' }) // Paginate const page2 = await client.skills.custom.list({ limit: 10, cursor: list.next_cursor, }) ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # List all skills_list = client.skills.custom.list() # Filter by tag filtered = client.skills.custom.list(tag='litigation') # Paginate page2 = client.skills.custom.list(limit=10, cursor=skills_list.next_cursor) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // List all list, _ := client.Skills.Custom.List(context.TODO(), casedev.SkillCustomListParams{}) // Filter by tag filtered, _ := client.Skills.Custom.List(context.TODO(), casedev.SkillCustomListParams{ Tag: casedev.String("litigation"), }) // Paginate page2, _ := client.Skills.Custom.List(context.TODO(), casedev.SkillCustomListParams{ Limit: casedev.Int(10), Cursor: list.NextCursor, }) ``` **Query parameters:** | Parameter | Type | Description | | - | - | - | | `limit` | integer | Results per page (1-100, default 50) | | `cursor` | string | Cursor from previous response for pagination | | `tag` | string | Filter by tag | **Response:** ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "skills": [ { "slug": "deposition-prep-checklist", "name": "Deposition Prep Checklist", "summary": "...", "tags": ["litigation", "deposition"], "metadata": {}, "version": 1, "created_at": "2026-03-16T20:09:59.333Z", "updated_at": "2026-03-16T20:09:59.333Z" } ], "next_cursor": "csk_abc123", "has_more": true } ``` ## Update a Skill Update one or more fields. The version is automatically incremented. If you change content-related fields (name, summary, or content), the embedding is regenerated. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X PUT https://api.case.dev/skills/deposition-prep-checklist \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "name": "Updated Deposition Prep Checklist", "tags": ["litigation", "deposition", "checklist", "federal"], "content": "# Updated content..." }' ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const updated = await client.skills.update('deposition-prep-checklist', { name: 'Updated Deposition Prep Checklist', tags: ['litigation', 'deposition', 'checklist', 'federal'], content: '# Updated content...', }) console.log(updated.version) // 2 ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} updated = client.skills.update( 'deposition-prep-checklist', name='Updated Deposition Prep Checklist', tags=['litigation', 'deposition', 'checklist', 'federal'], content='# Updated content...', ) print(updated.version) # 2 ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} updated, _ := client.Skills.Update(context.TODO(), "deposition-prep-checklist", casedev.SkillUpdateParams{ Name: casedev.String("Updated Deposition Prep Checklist"), Tags: casedev.F([]string{"litigation", "deposition", "checklist", "federal"}), Content: casedev.String("# Updated content..."), }) fmt.Println(updated.Version) ``` You can also rename a skill's slug: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X PUT https://api.case.dev/skills/deposition-prep-checklist \ -H "Authorization: Bearer $CASE_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "slug": "depo-prep-v2" }' ``` After renaming, the old slug returns 404 and the new slug is active. ## Delete a Skill Soft-deletes a skill. It will no longer appear in search results or be accessible by slug. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X DELETE https://api.case.dev/skills/deposition-prep-checklist \ -H "Authorization: Bearer $CASE_API_KEY" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} await client.skills.delete('deposition-prep-checklist') ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.skills.delete('deposition-prep-checklist') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} client.Skills.Delete(context.TODO(), "deposition-prep-checklist") ``` **Response** (200): ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "slug": "deposition-prep-checklist", "deleted": true } ``` > [!NOTE] > > Deletion frees the slug. You can create a new skill with the same slug after deleting. ## Permissions Custom skills require the `skills` permission scope on your API key. | Endpoint | Permission | | - | - | | `GET /skills/resolve` | `skills` (read) | | `GET /skills/:slug` | `skills` (read) | | `GET /skills/custom` | `skills` (read) | | `POST /skills` | `skills` (write) | | `PUT /skills/:slug` | `skills` (write) | | `DELETE /skills/:slug` | `skills` (write) | | `GET /skills/:slug/export` | `skills` (read) | Configure permissions when creating API keys in the [Console](https://console.case.dev). ## Limits | Limit | Value | | - | - | | Content size | 64KB per skill | | Companion files | 100 per skill | | Companion file size | 64KB per file | | Name length | 256 characters | | Summary length | 1,000 characters | | Tag length | 100 characters per tag | | Slug length | 128 characters | | Slugs per org | Unlimited | ## What's Next? > [card] [Browse Curated Skills](https://agentskills.legal/skills) > > Explore 870+ open-source legal skills > [card] [API Reference](/api-reference) > > Full endpoint documentation > [card] [Skills Overview](/skills/index) > > Learn about the curated skills library and MCP setup > [card] [Rate Limits](/rate-limits) > > Understand request limits and pricing # Skills Overview Source: https://docs.case.dev/skills/index Curated library of legal prompts, document templates, and research methodologies for AI agents A comprehensive library of structured legal skills that power AI-driven legal work — from research summaries to court filings. > [!NOTE] > > **Using Case.dev agents?** Agent Skills is already baked in. Just start using it — no setup > required. ## Open Source & Community-Driven > [card] [Browse, Edit & Contribute Skills](https://agentskills.legal/skills) > > The entire Legal Agent Skills library is **open source under the MIT License**. You can browse all > 870+ skills, suggest edits to existing skills, or contribute your own legal expertise to the > community. > [card] [Browse Skills](https://agentskills.legal/skills) > > Explore the full library of legal AI skills > [card] [Contribute](https://agentskills.legal/contribute) > > Submit your own skills to help the community > [card] [Agent Skills Protocol](https://agentskills.io/home) > > Learn about the underlying standard ## What are Legal Agent Skills? Anthropic recently standardized a protocol for progressive disclosure called [Agent Skills](https://agentskills.io/home). We've extended this approach beyond writing code and into Legal. Legal Agent Skills is a curated, [open-source library](https://agentskills.legal/skills) of professional-grade prompts, document templates, and research methodologies designed specifically for legal work. Each skill includes: * **Structured prompts** — Battle-tested instructions for generating legal documents * **Installable bundles** — Optional companion files for scripts, templates, and references * **Practice area tags** — Categorized by litigation, transactional, corporate, regulatory, and 14 more practice areas * **Rich metadata** — Version tracking, authorship, and licensing information Skills cover the full spectrum of legal practice: | Category | Examples | | - | - | | **Research** | Legal research summaries, case analysis, article summaries | | **Litigation** | Complaints, motions, appellate briefs, judgment summaries | | **Transactional** | Lease agreements, dissolution reports, client memos | | **Billing** | Legal billing summaries, matter tracking | ## Free MCP Installation Install Agent Skills on any MCP-compatible AI application for free. ### Server Details | Property | Value | | - | - | | **URL** | `https://skills.case.dev/api/mcp` | | **Protocol** | Streamable HTTP | | **Auth** | None required (free tier) | ### Setup Guides > [accordion] Cursor > > 1. Open **Settings** → **MCP** > 2. Click **Add new MCP server** > 3. Add this configuration: > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > { > "mcpServers": { > "legal-skills": { > "url": "https://skills.case.dev/api/mcp", > "headers": {} > } > } > } > ``` > > 4. Restart Cursor > > **Test it:** Ask Cursor to "search for legal research skills" > [accordion] Claude Desktop > > 1. Open your Claude Desktop config file: > * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` > * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` > 2. Add the Agent Skills server: > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > { > "mcpServers": { > "legal-skills": { > "command": "npx", > "args": ["-y", "mcp-remote", "https://skills.case.dev/api/mcp"] > } > } > } > ``` > > 3. Restart Claude Desktop > > **Test it:** Ask Claude to "find skills for drafting appellate briefs" > [accordion] Windsurf > > 1. Open **Settings** → **MCP Servers** > > 2. Add a new server with: > * **Name**: `legal-skills` > * **URL**: `https://skills.case.dev/api/mcp` > > 3. Restart Windsurf > [accordion] Add to Existing Config > > Already have MCP servers configured? Just add this entry inside your `"mcpServers"` object: > > **Cursor** (URL-based): > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > > { > "legal-skills": { > "url": "https://skills.case.dev/api/mcp", > "headers": {} > } > > ``` > > **Claude Desktop** (command-based): > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > > { > "legal-skills": { > "command": "npx", > "args": ["-y", "mcp-remote", "https://skills.case.dev/api/mcp"] > } > ``` ## Available Tools Once connected, your AI assistant can use these tools: | Tool | Description | | - | - | | `resolve_skill` | Search for legal skills by query (semantic search) | | `read_skill` | Read the full content of a skill by slug | ### resolve\_skill Search the skills library by topic or practice area. ```text theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} "Find skills for drafting employment complaints" "Search for appellate brief templates" "What skills are available for corporate governance?" ``` **Parameters:** * `query` (required) — What you're looking for **Returns:** Ranked list of matching skills with name, summary, and relevance score. ### read\_skill Retrieve the full content of a specific skill. ```text theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} "Read the legal-research-summaries skill" "Get the judgment-summaries skill content" ``` **Parameters:** * `slug` (required) — The skill identifier (e.g., `legal-research-summaries`) **Returns:** Complete skill including prompt content, tags, and metadata. ## Skill Metadata Each skill includes structured metadata for intelligent routing: ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "slug": "legal-research-summaries", "name": "Legal Research Summaries", "summary": "Comprehensive research synthesis with statutes, case law, and regulatory guidance", "tags": ["litigation", "regulatory"], "version": 1, "author_name": "CaseMark", "license": "MIT" } ``` | Field | Description | | - | - | | `slug` | Unique skill identifier used for lookups | | `name` | Display name of the skill | | `summary` | Brief description of what the skill does | | `tags` | Practice area tags from a controlled vocabulary (see below) | | `version` | Skill version number | | `author_name` | Skill author (nullable) | | `license` | License type (e.g., MIT) | ### Practice Area Tags Skills are tagged with one or more practice areas from a controlled vocabulary: | Tag | Covers | | - | - | | `litigation` | Lawsuits, motions, pleadings, briefs, court filings | | `transactional` | Contracts, agreements, mergers, acquisitions, leases | | `regulatory` | Compliance, FDA, SEC, HIPAA | | `corporate` | Governance, board matters, shareholders, bylaws | | `ip` | Patents, trademarks, copyrights | | `tax` | Tax law and planning | | `labor` | Employment and labor law | | `immigration` | Immigration law | | `real-estate` | Property and real estate law | | `family` | Divorce, custody, family law | | `criminal` | Criminal law | | `bankruptcy` | Bankruptcy proceedings | | `estate-planning` | Probate, trusts, estate planning | | `environmental` | Environmental law | | `healthcare` | Healthcare law | | `privacy` | Privacy and data protection | | `adr` | Arbitration, mediation, alternative dispute resolution | | `constitutional` | Constitutional law | ## Unlimited Requests with API Key For production use or high-volume applications, authenticate with a Case.dev API key. > [accordion] Cursor > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > { > "mcpServers": { > "legal-skills": { > "url": "https://skills.case.dev/api/mcp", > "headers": { > "Authorization": "Bearer YOUR_API_KEY" > } > } > } > } > ``` > [accordion] Claude Desktop > > ```json theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} > { > "mcpServers": { > "legal-skills": { > "command": "npx", > "args": ["-y", "mcp-remote", "https://skills.case.dev/api/mcp"], > "env": { > "CASE_API_KEY": "YOUR_API_KEY" > } > } > } > } > ``` Get your API key at [console.case.dev](https://console.case.dev). ## Example Skills Here are just a few of the 870+ skills available in the [open-source library](https://agentskills.legal/skills): > [card] Legal Research Summaries > > Comprehensive research synthesis with statutes, case law, and regulatory guidance > [card] Judgment Summaries > > Structured court decision analysis with holdings, precedent, and implications > [card] Appellate Briefs > > Response briefs that systematically address appellant arguments > [card] Client Memos > > Clear, accessible memoranda for non-lawyer audiences > [card] Complaints > > Court-ready pleadings with proper factual and legal allegations > [card] Lease Agreements > > Jurisdictionally compliant residential and commercial leases > [!NOTE] > > **Want to see more?** [Browse all 870+ skills →](https://agentskills.legal/skills) or [contribute > your own →](https://agentskills.legal/contribute) ## What's Next? > [card] [Browse All Skills](https://agentskills.legal/skills) > > Explore the full open-source library of 870+ legal AI skills > [card] [Contribute a Skill](https://agentskills.legal/contribute) > > Share your legal expertise with the community (MIT License) > [card] [MCP Integration](https://docs.case.dev/casedev-mcp) > > Connect to Case.dev documentation and services > [card] [Linc](/linc/index) > > Run intensive legal work with Agent Skills built-in > [card] [LLMs Guide](/llms) > > Use AI models for legal intelligence > [card] [Agent Skills Protocol](https://agentskills.io/home) > > Learn about the underlying open standard # Detect Language Source: https://docs.case.dev/translation/detect Detect the language of text Identify the language of text with confidence scores. Useful for routing multilingual content or determining if translation is needed. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} POST /translate/v1/detect ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/translate/v1/detect \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "q": "Bonjour, comment allez-vous?" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 detect --q "Bonjour, comment allez-vous?" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const result = await client.translate.v1.detect({ q: 'Bonjour, comment allez-vous?' }); const detection = result.data.detections[0][0]; console.log(detection.language); // "fr" console.log(detection.confidence); // 0.98 ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') result = client.translate.v1.detect( q='Bonjour, comment allez-vous?' ) detection = result.data.detections[0][0] print(detection.language) # "fr" print(detection.confidence) # 0.98 ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F("Bonjour, comment allez-vous?"), }) fmt.Println(result.Data.Detections[0][0].Language) ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "data": { "detections": [ [ { "language": "fr", "confidence": 0.98, "isReliable": true } ] ] } } ``` ## Parameters | Parameter | Type | Required | Description | | - | - | - | - | | `q` | string or string\[] | **Yes** | Text to detect language for. Can be a single string or array for batch detection. | ## Response The response contains an array of detections. Each detection includes: | Field | Type | Description | | - | - | - | | `language` | string | Detected language code (ISO 639-1) | | `confidence` | number | Confidence score from 0 to 1 | | `isReliable` | boolean | Whether the detection is considered reliable | ## Batch detection Detect languages for multiple texts in a single request: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 detect --q "Bonjour, comment allez-vous?" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.translate.v1.detect({ q: [ 'Hello, how are you?', 'Hola, como estas?', 'Bonjour, comment ca va?', 'Guten Tag, wie geht es Ihnen?' ] }); result.data.detections.forEach((detection, i) => { console.log(`Text ${i + 1}: ${detection[0].language}`); }); // Text 1: en // Text 2: es // Text 3: fr // Text 4: de ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.translate.v1.detect( q=[ 'Hello, how are you?', 'Hola, como estas?', 'Bonjour, comment ca va?', 'Guten Tag, wie geht es Ihnen?' ] ) for i, detection in enumerate(result.data.detections): print(f'Text {i + 1}: {detection[0].language}') # Text 1: en # Text 2: es # Text 3: fr # Text 4: de ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F("Bonjour, comment allez-vous?"), }) fmt.Println(result.Data.Detections[0][0].Language) ``` ## Examples ### Route content by language ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Detect the language casedev translate:v1 detect --q "Your text here" # Then translate if needed casedev translate:v1 translate --q "Your text here" --target en --source fr ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async function routeByLanguage(text: string) { const result = await client.translate.v1.detect({ q: text }); const lang = result.data.detections[0][0].language; switch (lang) { case 'en': return processEnglish(text); case 'es': return processSpanish(text); default: // Translate to English first const translated = await client.translate.v1.translate({ q: text, target: 'en', source: lang }); return processEnglish(translated.data.translations[0].translatedText); } } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} async def route_by_language(text: str): result = client.translate.v1.detect(q=text) lang = result.data.detections[0][0].language if lang == 'en': return process_english(text) elif lang == 'es': return process_spanish(text) else: # Translate to English first translated = client.translate.v1.translate( q=text, target='en', source=lang ) return process_english(translated.data.translations[0].translated_text) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Detect the language detectResult, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F(text), }) lang := detectResult.Data.Detections[0][0].Language switch lang { case "en": processEnglish(text) case "es": processSpanish(text) default: // Translate to English first translated, _ := client.Translate.V1.Translate(ctx, casedev.TranslateV1TranslateParams{ Q: casedev.F(text), Target: casedev.F("en"), Source: casedev.F(lang), }) processEnglish(translated.Data.Translations[0].TranslatedText) } ``` ### Filter by language confidence ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 detect --q "Text to check confidence for" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.translate.v1.detect({ q: foreignText }); const detection = result.data.detections[0][0]; if (detection.confidence > 0.9 && detection.isReliable) { console.log(`Confident detection: ${detection.language}`); } else { console.log('Low confidence, may need manual review'); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.translate.v1.detect(q=foreign_text) detection = result.data.detections[0][0] if detection.confidence > 0.9 and detection.is_reliable: print(f'Confident detection: {detection.language}') else: print('Low confidence, may need manual review') ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F(foreignText), }) detection := result.Data.Detections[0][0] if detection.Confidence > 0.9 && detection.IsReliable { fmt.Printf("Confident detection: %s\n", detection.Language) } else { fmt.Println("Low confidence, may need manual review") } ``` ### Identify mixed-language documents ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Detect each paragraph separately casedev translate:v1 detect --q "First paragraph text" casedev translate:v1 detect --q "Second paragraph text" ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Split document into paragraphs and detect each const paragraphs = document.split('\n\n'); const result = await client.translate.v1.detect({ q: paragraphs }); const languages = new Set( result.data.detections.map(d => d[0].language) ); if (languages.size > 1) { console.log('Mixed-language document detected'); console.log('Languages found:', [...languages].join(', ')); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # Split document into paragraphs and detect each paragraphs = document.split('\n\n') result = client.translate.v1.detect(q=paragraphs) languages = set(d[0].language for d in result.data.detections) if len(languages) > 1: print('Mixed-language document detected') print('Languages found:', ', '.join(languages)) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // Split document into paragraphs and detect each paragraphs := strings.Split(document, "\n\n") result, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F(paragraphs), }) languages := make(map[string]bool) for _, d := range result.Data.Detections { languages[d[0].Language] = true } if len(languages) > 1 { fmt.Println("Mixed-language document detected") } ``` > [!NOTE] > > **Pricing:** \$0.05 per 1,000 characters, same as translation. # Translate a Document Source: https://docs.case.dev/translation/document Translate TXT, DOCX, and searchable PDF documents while retaining their source format Translate one document into a target language. The response is a downloadable file in the same format as the upload: TXT returns TXT, DOCX returns DOCX, and PDF returns PDF. ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/translate/v1/document \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -F "file=@statement.docx" \ -F "target=es" \ --output statement-es.docx ``` ## Request Send a `multipart/form-data` request with these fields: | Field | Type | Required | Description | | - | - | - | - | | `file` | file | Yes | One TXT, DOCX, or searchable PDF file, up to 20MB. | | `target` | string | Yes | Target BCP-47 language code, such as `es` or `fr-CA`. | | `source` | string | No | Source language code. When omitted, the source language is detected automatically. | ## Response The response body contains the translated file bytes. Use the `Content-Type` and `Content-Disposition` headers to store the result. When the source language was detected, the response also includes `X-Detected-Source-Language`. ```typescript title="TypeScript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const form = new FormData() form.append('file', file) form.append('target', 'es') const response = await fetch('https://api.case.dev/translate/v1/document', { method: 'POST', headers: { Authorization: `Bearer ${process.env.CASEDEV_API_KEY}` }, body: form, }) if (!response.ok) throw new Error(`Translation failed: ${response.status}`) const translatedDocument = await response.blob() ``` ## Pricing Pricing is passed through at the Google Cloud Translation provider rate with no Case.dev markup. TXT files are billed by source character. DOCX and PDF files are billed at \$0.08 per source page. ## Format behavior * TXT content is translated as UTF-8 text. The TXT limit is 100,000 characters. * DOCX and PDF files use Google Cloud Document Translation to retain much of the source layout and formatting. * PDF input must contain searchable, selectable text. Scanned PDFs are not accepted by this endpoint. * Photos and other non-text document elements are retained, but text embedded inside an image is not translated. * Complex PDF layouts, overlapping text, and DOCX text boxes may not translate or render perfectly. Review the output before relying on it. > [!NOTE] > > Machine translation can contain errors and is not a certified legal translation. # Translation Overview Source: https://docs.case.dev/translation/index Translate text and formatted documents between 100+ languages Neural machine translation powered by Google Cloud Translation. Add translation capabilities to your app—translate documents, communications, and evidence across 100+ languages with automatic language detection. ## Quick start ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl -X POST https://api.case.dev/translate/v1/translate \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "q": "The deposition will be held on Monday at 10:00 AM.", "target": "es" }' ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 translate \ --q "The deposition will be held on Monday." \ --target es ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: process.env.CASEDEV_API_KEY }); // Translate text to Spanish const result = await client.translate.v1.translate({ q: 'The deposition will be held on Monday at 10:00 AM.', target: 'es' }); console.log(result.data.translations[0].translatedText); // "La deposición se llevará a cabo el lunes a las 10:00 AM." ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev import os client = casedev.Casedev(api_key=os.environ['CASEDEV_API_KEY']) # Translate text to Spanish result = client.translate.v1.translate( q='The deposition will be held on Monday at 10:00 AM.', target='es' ) print(result.data.translations[0].translated_text) # "La deposición se llevará a cabo el lunes a las 10:00 AM." ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.Translate(ctx, casedev.TranslateV1TranslateParams{ Q: casedev.F("The deposition will be held on Monday at 10:00 AM."), Target: casedev.F("es"), }) fmt.Println(result.Data.Translations[0].TranslatedText) ``` ## Endpoints > [card] [Translate a Document](/translation/document) > > `POST /translate/v1/document` — Translate TXT, DOCX, or searchable PDF files > [card] [Translate](/translation/translate) > > `POST /translate/v1/translate` — Translate text to target language > [card] [Detect Language](/translation/detect) > > `POST /translate/v1/detect` — Detect the language of text > [card] [Supported Languages](/translation/languages) > > `GET /translate/v1/languages` — List all supported languages ## Features * **100+ Languages** — Support for all major world languages including Chinese, Spanish, Arabic, Hindi, and more. * **Auto-Detection** — Automatically detect source language when not specified. * **Batch Translation** — Translate multiple strings in a single request for efficiency. * **HTML Preservation** — Preserve HTML formatting during translation. * **Document Layout Preservation** — Retain the source format and much of the layout in DOCX and searchable PDF files. * **Neural Machine Translation** — State-of-the-art NMT models for high-quality translations. ## Pricing | Service | Cost | | - | - | | Translation | \$0.03 per 1,000 characters | | Language Detection | \$0.03 per 1,000 characters | | Supported Languages | Free | > [!NOTE] > > **Example:** A 10,000 character legal document costs \$0.30 to translate. ## Common use cases ### Multilingual discovery Translate foreign-language documents discovered during litigation: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 translate --q "Foreign document text" --target en --format text ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const foreignDoc = await fetchDocumentText(); const result = await client.translate.v1.translate({ q: foreignDoc, target: 'en', // Translate to English format: 'text' }); ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} foreign_doc = fetch_document_text() result = client.translate.v1.translate( q=foreign_doc, target='en', format='text' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} foreignDoc := fetchDocumentText() result, _ := client.Translate.V1.Translate(ctx, casedev.TranslateV1TranslateParams{ Q: casedev.F(foreignDoc), Target: casedev.F("en"), Format: casedev.F(casedev.TranslateV1TranslateParamsFormatText), }) ``` ### Client communications Translate client correspondence in their preferred language: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 translate --q "Email content" --target es casedev translate:v1 translate --q "Email content" --target zh casedev translate:v1 translate --q "Email content" --target ar ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const languages = ['es', 'zh', 'ar']; // Spanish, Chinese, Arabic for (const lang of languages) { const translated = await client.translate.v1.translate({ q: emailContent, target: lang }); // Send localized email } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} languages = ['es', 'zh', 'ar'] # Spanish, Chinese, Arabic for lang in languages: translated = client.translate.v1.translate( q=email_content, target=lang ) # Send localized email ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} languages := []string{"es", "zh", "ar"} // Spanish, Chinese, Arabic for _, lang := range languages { translated, _ := client.Translate.V1.Translate(ctx, casedev.TranslateV1TranslateParams{ Q: casedev.F(emailContent), Target: casedev.F(lang), }) // Send localized email _ = translated } ``` ### Evidence processing Detect and translate multilingual evidence: ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # First detect the language casedev translate:v1 detect --q "Evidence text here" # Then translate if not English casedev translate:v1 translate --q "Evidence text here" --target en --source fr ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // First detect the language const detection = await client.translate.v1.detect({ q: evidenceText }); const sourceLanguage = detection.data.detections[0][0].language; // Then translate if not English if (sourceLanguage !== 'en') { const translated = await client.translate.v1.translate({ q: evidenceText, source: sourceLanguage, target: 'en' }); } ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} # First detect the language detection = client.translate.v1.detect(q=evidence_text) source_language = detection.data.detections[0][0].language # Then translate if not English if source_language != 'en': translated = client.translate.v1.translate( q=evidence_text, source=source_language, target='en' ) ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} // First detect the language detection, _ := client.Translate.V1.Detect(ctx, casedev.TranslateV1DetectParams{ Q: casedev.F(evidenceText), }) sourceLanguage := detection.Data.Detections[0][0].Language // Then translate if not English if sourceLanguage != "en" { translated, _ := client.Translate.V1.Translate(ctx, casedev.TranslateV1TranslateParams{ Q: casedev.F(evidenceText), Source: casedev.F(sourceLanguage), Target: casedev.F("en"), }) _ = translated } ``` ## Related services > [card] [Vault](/vault) > > Store translated documents alongside originals for searchable archives > [card] [OCR](/ocr) > > Extract text from scanned documents before translation # Supported Languages Source: https://docs.case.dev/translation/languages List all supported translation languages Get the complete list of languages supported for translation. Optionally get language names translated into a target language. ```bash title="Endpoint" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} GET /translate/v1/languages ``` ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl https://api.case.dev/translate/v1/languages \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 list-languages ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import Casedev from 'casedev'; const client = new Casedev({ apiKey: 'sk_case_YOUR_API_KEY' }); const result = await client.translate.v1.languages(); result.data.languages.forEach(lang => { console.log(lang.language); }); // "en", "es", "fr", "de", ... ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} import casedev client = casedev.Casedev(api_key='sk_case_YOUR_API_KEY') result = client.translate.v1.list_languages() for lang in result.data.languages: print(lang.language) # "en", "es", "fr", "de", ... ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.ListLanguages(ctx, casedev.TranslateV1ListLanguagesParams{}) for _, lang := range result.Data.Languages { fmt.Printf("%s (%s)\n", lang.Name, lang.Language) } ``` ```json title="Response" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "data": { "languages": [ { "language": "af" }, { "language": "ar" }, { "language": "az" }, { "language": "be" }, { "language": "bg" }, { "language": "bn" }, ... ] } } ``` ## Query parameters | Parameter | Type | Description | | - | - | - | | `target` | string | Target language for translating language names | | `model` | string | Model to check support for: `nmt` or `base` | ## Get localized language names Include language names translated into a specific language: ```bash title="cURL" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} curl "https://api.case.dev/translate/v1/languages?target=es" \ -H "Authorization: Bearer sk_case_YOUR_API_KEY" ``` ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 list-languages ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.translate.v1.languages({ target: 'es' // Get names in Spanish }); result.data.languages.forEach(lang => { console.log(`${lang.language}: ${lang.name}`); }); // "en: Inglés" // "es: Español" // "fr: Francés" // "de: Alemán" ``` ```python title="Python" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result = client.translate.v1.list_languages(target="es") for lang in result.data.languages: print(f"{lang.language}: {lang.name}") # "en: Inglés" # "es: Español" ``` ```go title="Go" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} result, _ := client.Translate.V1.ListLanguages(ctx, casedev.TranslateV1ListLanguagesParams{}) for _, lang := range result.Data.Languages { fmt.Printf("%s (%s)\n", lang.Name, lang.Language) } ``` ```json title="Response with names" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} { "data": { "languages": [ { "language": "en", "name": "Inglés" }, { "language": "es", "name": "Español" }, { "language": "fr", "name": "Francés" }, { "language": "de", "name": "Alemán" }, { "language": "zh", "name": "Chino" }, ... ] } } ``` ## Popular languages | Code | Language | | - | - | | `en` | English | | `es` | Spanish | | `fr` | French | | `de` | German | | `it` | Italian | | `pt` | Portuguese | | `ru` | Russian | | `zh` | Chinese (Simplified) | | `zh-TW` | Chinese (Traditional) | | `ja` | Japanese | | `ko` | Korean | | `ar` | Arabic | | `hi` | Hindi | | `th` | Thai | | `vi` | Vietnamese | | `nl` | Dutch | | `pl` | Polish | | `tr` | Turkish | | `uk` | Ukrainian | | `he` | Hebrew | ## Examples ### Build a language selector ```bash title="CLI" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} casedev translate:v1 list-languages --target en ``` ```typescript title="Typescript" theme={"theme":{"light":"github-light","dark":"one-dark-pro"}} const result = await client.translate.v1.languages({ target: 'en' // Get English names }); const languageOptions = result.data.languages.map(lang => ({ value: lang.language, label: lang.name })); // Use in a dropdown component