From 06e835e66e5c7a1c9321d34620b692d6dce1074d Mon Sep 17 00:00:00 2001 From: Chris Bartholomew Date: Sun, 22 Nov 2026 11:00:37 -0500 Subject: [PATCH] feat: base URL option for Hindsight Inference (Python, Node.js, CLI 0.2.0) Iris also runs on Hindsight Inference with the same API: the same paths under the base URL (/files, /extraction, /extraction/{id}) and the same request and response bodies. The organization comes from the key, so it isn't in the path. Every client can now be pointed at it: - Python: base_url= on extract_text / extract_text_from_file (and the async versions) - Node.js: baseUrl in ExtractionOptions - CLI: --base-url, or base_url in ~/.vectorize-iris/credentials - All three: the VECTORIZE_IRIS_BASE_URL env var With a base URL, requests go to it as given and no org ID is needed: export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1" export VECTORIZE_TOKEN="hsk_..." Without one, nothing changes: https://api.vectorize.io/v1/org/{orgId}, org ID required (the CLI's hidden --api-url still replaces only the host). Versions: Python 0.2.0, Node.js 0.2.0, CLI 0.2.0. New tests (Python tests/test_base_url.py, Node tests/baseUrl.test.ts, CLI unit tests) check the URLs each call goes to and the defaults. Claude-Session: https://claude.ai/code/session_01XypsfKDtYZSmN3FFv6z5tN --- README.md | 14 ++ nodejs-api/README.md | 14 ++ nodejs-api/package.json | 2 +- nodejs-api/src/index.ts | 72 ++++++---- nodejs-api/src/types.ts | 8 +- nodejs-api/tests/baseUrl.test.ts | 94 +++++++++++++ python-api/README.md | 13 ++ python-api/pyproject.toml | 2 +- python-api/tests/test_base_url.py | 154 ++++++++++++++++++++++ python-api/uv.lock | 2 +- python-api/vectorize_iris/__init__.py | 2 +- python-api/vectorize_iris/async_client.py | 40 +++--- python-api/vectorize_iris/client.py | 40 +++--- python-api/vectorize_iris/config.py | 41 ++++++ rust-cli/Cargo.toml | 2 +- rust-cli/src/main.rs | 109 +++++++++++---- 16 files changed, 507 insertions(+), 102 deletions(-) create mode 100644 nodejs-api/tests/baseUrl.test.ts create mode 100644 python-api/tests/test_base_url.py create mode 100644 python-api/vectorize_iris/config.py diff --git a/README.md b/README.md index 72a3cc1..637f51b 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,20 @@ const result = await extractTextFromFile('document.pdf', { }); ``` +### Hindsight Inference + +Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io), with the same API. +Point any client at its base URL and use a Hindsight Inference API key; no organization ID is needed +(the key identifies it): + +```bash +export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1" +export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key +``` + +Or per call: `base_url=` (Python), `baseUrl:` (Node.js), `--base-url` (CLI, or `base_url` in +`~/.vectorize-iris/credentials`). Requires Python SDK 0.2.0, Node.js SDK 0.2.0 or CLI 0.2.0. + ## Documentation For detailed documentation, API reference, and advanced features: diff --git a/nodejs-api/README.md b/nodejs-api/README.md index d9b0822..f0c4ae9 100644 --- a/nodejs-api/README.md +++ b/nodejs-api/README.md @@ -40,6 +40,19 @@ export VECTORIZE_TOKEN="your-token" export VECTORIZE_ORG_ID="your-org-id" ``` +### Hindsight Inference + +Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io). The API is the same; +point the SDK at its base URL and use a Hindsight Inference API key. No organization ID is needed (the +key identifies it): + +```bash +export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1" +export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key +``` + +Or per call: `extractTextFromFile('document.pdf', { apiToken: 'hsk_...', baseUrl: 'https://inference.hindsight.vectorize.io/v1' })`. + ### Basic Usage ```typescript @@ -370,6 +383,7 @@ Extract text from a buffer. interface ExtractionOptions { apiToken?: string; // Override env var orgId?: string; // Override env var + baseUrl?: string; // API root (env VECTORIZE_IRIS_BASE_URL); no orgId needed pollInterval?: number; // ms between checks (default: 2000) timeout?: number; // max ms to wait (default: 300000) type?: 'iris'; // Extraction type diff --git a/nodejs-api/package.json b/nodejs-api/package.json index 628a848..5bfa48a 100644 --- a/nodejs-api/package.json +++ b/nodejs-api/package.json @@ -1,6 +1,6 @@ { "name": "@vectorize-io/iris", - "version": "0.1.3", + "version": "0.2.0", "description": "Simple text extraction from files using Vectorize Iris", "repository": { "type": "git", diff --git a/nodejs-api/src/index.ts b/nodejs-api/src/index.ts index ae6ae41..b3d74e8 100644 --- a/nodejs-api/src/index.ts +++ b/nodejs-api/src/index.ts @@ -30,6 +30,33 @@ export class VectorizeIrisError extends Error { } } +const DEFAULT_API_URL = 'https://api.vectorize.io'; + +/** + * The token and the API root requests go to. With a base URL (option or VECTORIZE_IRIS_BASE_URL) + * requests go to it as given and no organization ID is needed (Hindsight Inference takes it from + * the key); without one, to https://api.vectorize.io/v1/org/{orgId}. + */ +export function resolveEndpoint( + apiToken: string | undefined = process.env.VECTORIZE_TOKEN, + orgId: string | undefined = process.env.VECTORIZE_ORG_ID, + baseUrl: string | undefined = process.env.VECTORIZE_IRIS_BASE_URL +): { apiToken: string; baseUrl: string } { + if (baseUrl) { + if (!apiToken) { + throw new VectorizeIrisError('Missing credentials. Set VECTORIZE_TOKEN or pass apiToken in options.'); + } + return { apiToken, baseUrl: baseUrl.replace(/\/+$/, '') }; + } + if (!apiToken || !orgId) { + throw new VectorizeIrisError( + 'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' + + 'environment variables or pass them in options.' + ); + } + return { apiToken, baseUrl: `${DEFAULT_API_URL}/v1/org/${orgId}` }; +} + /** * Internal function to extract from file buffer */ @@ -37,12 +64,11 @@ async function _extractFromBuffer( fileBuffer: Buffer, fileName: string, apiToken: string, - orgId: string, + baseUrl: string, pollInterval: number, timeout: number, options: ExtractionOptions ): Promise { - const baseUrl = `https://api.vectorize.io/v1/org/${orgId}`; const headers = { 'Authorization': `Bearer ${apiToken}`, 'Content-Type': 'application/json' @@ -198,27 +224,26 @@ export async function extractText( options: ExtractionOptions = {} ): Promise { const { - apiToken = process.env.VECTORIZE_TOKEN, - orgId = process.env.VECTORIZE_ORG_ID, + apiToken, + orgId, + baseUrl, pollInterval = 2000, timeout = 300000, type = 'iris', ...extractionOptions } = options; - // Validate credentials - if (!apiToken || !orgId) { - throw new VectorizeIrisError( - 'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' + - 'environment variables or pass them in options.' - ); - } + const endpoint = resolveEndpoint( + apiToken ?? process.env.VECTORIZE_TOKEN, + orgId ?? process.env.VECTORIZE_ORG_ID, + baseUrl ?? process.env.VECTORIZE_IRIS_BASE_URL + ); return _extractFromBuffer( fileBuffer, fileName, - apiToken, - orgId, + endpoint.apiToken, + endpoint.baseUrl, pollInterval, timeout, { type, ...extractionOptions } @@ -265,21 +290,20 @@ export async function extractTextFromFile( options: ExtractionOptions = {} ): Promise { const { - apiToken = process.env.VECTORIZE_TOKEN, - orgId = process.env.VECTORIZE_ORG_ID, + apiToken, + orgId, + baseUrl, pollInterval = 2000, timeout = 300000, type = 'iris', ...extractionOptions } = options; - // Validate credentials - if (!apiToken || !orgId) { - throw new VectorizeIrisError( - 'Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID ' + - 'environment variables or pass them in options.' - ); - } + const endpoint = resolveEndpoint( + apiToken ?? process.env.VECTORIZE_TOKEN, + orgId ?? process.env.VECTORIZE_ORG_ID, + baseUrl ?? process.env.VECTORIZE_IRIS_BASE_URL + ); // Validate file exists try { @@ -295,8 +319,8 @@ export async function extractTextFromFile( return _extractFromBuffer( fileBuffer, fileName, - apiToken, - orgId, + endpoint.apiToken, + endpoint.baseUrl, pollInterval, timeout, { type, ...extractionOptions } diff --git a/nodejs-api/src/types.ts b/nodejs-api/src/types.ts index 5c462e3..7ec169c 100644 --- a/nodejs-api/src/types.ts +++ b/nodejs-api/src/types.ts @@ -68,8 +68,14 @@ export interface ExtractionResult { export interface ExtractionOptions { /** Vectorize access token (defaults to VECTORIZE_TOKEN env var) */ apiToken?: string; - /** Organization ID (defaults to VECTORIZE_ORG_ID env var) */ + /** Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with baseUrl */ orgId?: string; + /** + * API root that /files and /extraction hang off (defaults to the VECTORIZE_IRIS_BASE_URL env var, + * then https://api.vectorize.io/v1/org/{orgId}). For Hindsight Inference, where the key identifies + * the organization: https://inference.hindsight.vectorize.io/v1 + */ + baseUrl?: string; /** Milliseconds between status checks (default: 2000) */ pollInterval?: number; /** Maximum milliseconds to wait for extraction (default: 300000) */ diff --git a/nodejs-api/tests/baseUrl.test.ts b/nodejs-api/tests/baseUrl.test.ts new file mode 100644 index 0000000..decb686 --- /dev/null +++ b/nodejs-api/tests/baseUrl.test.ts @@ -0,0 +1,94 @@ +/** + * Where requests go: api.vectorize.io/v1/org/{orgId} by default, or a base URL as given (Hindsight + * Inference, where the organization comes from the key and isn't in the path). + */ + +import fetch from 'node-fetch'; +import { extractText, resolveEndpoint, VectorizeIrisError } from '../src/index'; + +jest.mock('node-fetch'); +const mockFetch = fetch as jest.MockedFunction; + +const HINDSIGHT = 'https://inference.hindsight.vectorize.io/v1'; +const UPLOAD_URL = 'https://storage.example.com/signed'; +const DONE = { + ready: true, + data: { success: true, text: 'hello', chunks: ['hello'], metadata: null, usage: { irisPages: 1 }, error: null }, +}; + +function reply(body: unknown, status = 200) { + return { ok: status < 400, status, json: async () => body, text: async () => JSON.stringify(body) } as never; +} + +function fakeApi(): Array<{ method: string; url: string; auth?: string }> { + const calls: Array<{ method: string; url: string; auth?: string }> = []; + mockFetch.mockImplementation((async (url: string, init?: { method?: string; headers?: Record }) => { + const method = init?.method ?? 'GET'; + calls.push({ method, url, auth: init?.headers?.Authorization }); + if (method === 'PUT') return reply({}); + if (url.endsWith('/files')) return reply({ fileId: 'f1', uploadUrl: UPLOAD_URL }); + if (url.endsWith('/extraction')) return reply({ message: 'Extraction started.', extractionId: 'e1' }); + return reply(DONE); + }) as never); + return calls; +} + +beforeEach(() => { + jest.clearAllMocks(); + delete process.env.VECTORIZE_TOKEN; + delete process.env.VECTORIZE_ORG_ID; + delete process.env.VECTORIZE_IRIS_BASE_URL; +}); + +describe('resolveEndpoint', () => { + it('defaults to api.vectorize.io with the org', () => { + expect(resolveEndpoint('t', 'org-1', undefined)).toEqual({ + apiToken: 't', + baseUrl: 'https://api.vectorize.io/v1/org/org-1', + }); + }); + + it('uses a base URL as given, with no org', () => { + expect(resolveEndpoint('hsk_x', undefined, `${HINDSIGHT}/`)).toEqual({ apiToken: 'hsk_x', baseUrl: HINDSIGHT }); + }); + + it('still needs the org without a base URL', () => { + expect(() => resolveEndpoint('t', undefined, undefined)).toThrow(/VECTORIZE_ORG_ID/); + }); + + it('always needs a token', () => { + expect(() => resolveEndpoint(undefined, undefined, HINDSIGHT)).toThrow(VectorizeIrisError); + }); +}); + +describe('extractText', () => { + it('sends every call to the Hindsight base URL, without an org', async () => { + const calls = fakeApi(); + const result = await extractText(Buffer.from('%PDF'), 'a.pdf', { + apiToken: 'hsk_x', + baseUrl: HINDSIGHT, + pollInterval: 0, + }); + expect(result.text).toBe('hello'); + expect(calls.filter((c) => c.method !== 'PUT').map((c) => [c.method, c.url])).toEqual([ + ['POST', `${HINDSIGHT}/files`], + ['POST', `${HINDSIGHT}/extraction`], + ['GET', `${HINDSIGHT}/extraction/e1`], + ]); + expect(calls.filter((c) => c.method !== 'PUT').every((c) => c.auth === 'Bearer hsk_x')).toBe(true); + }); + + it('reads the base URL and key from the environment', async () => { + process.env.VECTORIZE_TOKEN = 'hsk_x'; + process.env.VECTORIZE_IRIS_BASE_URL = HINDSIGHT; + const calls = fakeApi(); + await extractText(Buffer.from('%PDF'), 'a.pdf', { pollInterval: 0 }); + expect(calls[0].url).toBe(`${HINDSIGHT}/files`); + }); + + it('is unchanged by default', async () => { + const calls = fakeApi(); + await extractText(Buffer.from('%PDF'), 'a.pdf', { apiToken: 't', orgId: 'org-1', pollInterval: 0 }); + expect(calls[0].url).toBe('https://api.vectorize.io/v1/org/org-1/files'); + }); +}); diff --git a/python-api/README.md b/python-api/README.md index 49bdb1d..8ad22ff 100644 --- a/python-api/README.md +++ b/python-api/README.md @@ -39,6 +39,19 @@ export VECTORIZE_TOKEN="your-token" export VECTORIZE_ORG_ID="your-org-id" ``` +### Hindsight Inference + +Iris also runs on [Hindsight Inference](https://inference.hindsight.vectorize.io). The API is the same; +point the SDK at its base URL and use a Hindsight Inference API key. No organization ID is needed (the +key identifies it): + +```bash +export VECTORIZE_IRIS_BASE_URL="https://inference.hindsight.vectorize.io/v1" +export VECTORIZE_TOKEN="hsk_..." # your Hindsight Inference API key +``` + +Or per call: `extract_text_from_file("document.pdf", api_token="hsk_...", base_url="https://inference.hindsight.vectorize.io/v1")`. + ### Basic Usage ```python diff --git a/python-api/pyproject.toml b/python-api/pyproject.toml index 963c3b3..fe1fc0e 100644 --- a/python-api/pyproject.toml +++ b/python-api/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "vectorize-iris" -version = "0.1.0" +version = "0.2.0" description = "Simple text extraction from files using Vectorize Iris" readme = "README.md" requires-python = ">=3.10" diff --git a/python-api/tests/test_base_url.py b/python-api/tests/test_base_url.py new file mode 100644 index 0000000..6e0d856 --- /dev/null +++ b/python-api/tests/test_base_url.py @@ -0,0 +1,154 @@ +""" +Where requests go: api.vectorize.io/v1/org/{org_id} by default, or a base URL as given (Hindsight +Inference, where the organization comes from the key and isn't in the path). +""" + +import os +from unittest.mock import Mock, patch + +import pytest + +from vectorize_iris import VectorizeIrisError, extract_text, extract_text_async +from vectorize_iris.config import resolve + +HINDSIGHT = "https://inference.hindsight.vectorize.io/v1" +UPLOAD_URL = "https://storage.example.com/signed" +DONE = {"ready": True, "data": {"success": True, "text": "hello", "chunks": ["hello"], + "metadata": None, "usage": {"irisPages": 1}, "error": None}} + + +@pytest.fixture(autouse=True) +def clean_env(): + keys = ("VECTORIZE_TOKEN", "VECTORIZE_ORG_ID", "VECTORIZE_IRIS_BASE_URL") + with patch.dict(os.environ, {}, clear=False): + for k in keys: + os.environ.pop(k, None) + yield + + +def response(status, body=None): + r = Mock() + r.status_code = status + r.json.return_value = body or {} + r.text = str(body) + return r + + +def fake_requests(): + calls = [] + + def post(url, **kw): + calls.append(("POST", url, kw.get("headers"))) + if url.endswith("/files"): + return response(200, {"fileId": "f1", "uploadUrl": UPLOAD_URL}) + return response(200, {"message": "Extraction started.", "extractionId": "e1"}) + + def put(url, **kw): + calls.append(("PUT", url, kw.get("headers"))) + return response(200) + + def get(url, **kw): + calls.append(("GET", url, kw.get("headers"))) + return response(200, DONE) + + m = Mock(post=post, put=put, get=get) + return m, calls + + +class TestResolve: + def test_default_is_api_vectorize_io_with_the_org(self): + assert resolve("t", "org-1", None) == ("t", "https://api.vectorize.io/v1/org/org-1") + + def test_base_url_is_used_as_given_and_needs_no_org(self): + assert resolve("hsk_x", None, HINDSIGHT + "/") == ("hsk_x", HINDSIGHT) + + def test_base_url_from_the_environment(self): + os.environ.update(VECTORIZE_TOKEN="hsk_x", VECTORIZE_IRIS_BASE_URL=HINDSIGHT) + assert resolve(None, None, None) == ("hsk_x", HINDSIGHT) + + def test_argument_beats_the_environment(self): + os.environ.update(VECTORIZE_IRIS_BASE_URL="https://other.example/v1") + assert resolve("t", None, HINDSIGHT)[1] == HINDSIGHT + + def test_without_a_base_url_the_org_is_still_required(self): + with pytest.raises(VectorizeIrisError, match="VECTORIZE_ORG_ID"): + resolve("t", None, None) + + def test_a_token_is_always_required(self): + with pytest.raises(VectorizeIrisError, match="Missing credentials"): + resolve(None, None, HINDSIGHT) + + +class TestSyncClient: + def test_hindsight_base_url_gets_every_call_without_an_org(self): + fake, calls = fake_requests() + with patch("vectorize_iris.client.requests", fake): + result = extract_text(b"%PDF", "a.pdf", api_token="hsk_x", base_url=HINDSIGHT, poll_interval=0) + assert result.text == "hello" + api = [(m, u) for m, u, _ in calls if m != "PUT"] + assert api == [("POST", f"{HINDSIGHT}/files"), ("POST", f"{HINDSIGHT}/extraction"), + ("GET", f"{HINDSIGHT}/extraction/e1")] + assert all(h["Authorization"] == "Bearer hsk_x" for m, _, h in calls if m != "PUT") + + def test_default_is_unchanged(self): + fake, calls = fake_requests() + with patch("vectorize_iris.client.requests", fake): + extract_text(b"%PDF", "a.pdf", api_token="t", org_id="org-1", poll_interval=0) + assert calls[0][1] == "https://api.vectorize.io/v1/org/org-1/files" + + +class FakeAiohttpResponse: + def __init__(self, status, body=None): + self.status = status + self._body = body or {} + + async def json(self): + return self._body + + async def text(self): + return str(self._body) + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + +class FakeSession: + calls = [] + + def __init__(self, *a, **kw): + pass + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + return False + + def post(self, url, **kw): + FakeSession.calls.append(("POST", url)) + if url.endswith("/files"): + return FakeAiohttpResponse(200, {"fileId": "f1", "uploadUrl": UPLOAD_URL}) + return FakeAiohttpResponse(200, {"message": "Extraction started.", "extractionId": "e1"}) + + def put(self, url, **kw): + FakeSession.calls.append(("PUT", url)) + return FakeAiohttpResponse(200) + + def get(self, url, **kw): + FakeSession.calls.append(("GET", url)) + return FakeAiohttpResponse(200, DONE) + + +@pytest.mark.asyncio +class TestAsyncClient: + async def test_hindsight_base_url_from_the_environment(self): + FakeSession.calls = [] + os.environ.update(VECTORIZE_TOKEN="hsk_x", VECTORIZE_IRIS_BASE_URL=HINDSIGHT) + with patch("vectorize_iris.async_client.aiohttp.ClientSession", FakeSession): + result = await extract_text_async(b"%PDF", "a.pdf", poll_interval=0) + assert result.text == "hello" + assert [c for c in FakeSession.calls if c[0] != "PUT"] == [ + ("POST", f"{HINDSIGHT}/files"), ("POST", f"{HINDSIGHT}/extraction"), ("GET", f"{HINDSIGHT}/extraction/e1")] diff --git a/python-api/uv.lock b/python-api/uv.lock index 4686020..41a56a2 100644 --- a/python-api/uv.lock +++ b/python-api/uv.lock @@ -1220,7 +1220,7 @@ wheels = [ [[package]] name = "vectorize-iris" -version = "0.1.0" +version = "0.2.0" source = { editable = "." } dependencies = [ { name = "aiohttp" }, diff --git a/python-api/vectorize_iris/__init__.py b/python-api/vectorize_iris/__init__.py index c3a7f85..cafb411 100644 --- a/python-api/vectorize_iris/__init__.py +++ b/python-api/vectorize_iris/__init__.py @@ -29,4 +29,4 @@ "MetadataExtractionStrategy", ] -__version__ = "0.1.0" +__version__ = "0.2.0" diff --git a/python-api/vectorize_iris/async_client.py b/python-api/vectorize_iris/async_client.py index 2251118..6b113dc 100644 --- a/python-api/vectorize_iris/async_client.py +++ b/python-api/vectorize_iris/async_client.py @@ -8,6 +8,7 @@ from typing import Optional from pathlib import Path +from vectorize_iris.config import resolve from vectorize_iris.exceptions import VectorizeIrisError from vectorize_iris.models import ( StartFileUploadRequest, @@ -24,7 +25,7 @@ async def _extract_from_bytes_async( file_content: bytes, file_name: str, api_token: str, - org_id: str, + base_url: str, poll_interval: int, timeout: int, options: Optional[ExtractionOptions] = None @@ -32,7 +33,6 @@ async def _extract_from_bytes_async( """ Internal async function to extract from file bytes. """ - base_url = f"https://api.vectorize.io/v1/org/{org_id}" headers = { "Authorization": f"Bearer {api_token}", "Content-Type": "application/json" @@ -135,6 +135,7 @@ async def extract_text_async( file_name: str = "document.pdf", api_token: Optional[str] = None, org_id: Optional[str] = None, + base_url: Optional[str] = None, poll_interval: int = 2, timeout: int = 300, options: Optional[ExtractionOptions] = None @@ -146,7 +147,10 @@ async def extract_text_async( file_bytes: File content as bytes file_name: Name of the file (default: "document.pdf") api_token: Vectorize access token (defaults to VECTORIZE_TOKEN env var) - org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var) + org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with base_url + base_url: API root that /files and /extraction hang off (defaults to the + VECTORIZE_IRIS_BASE_URL env var, then https://api.vectorize.io/v1/org/{org_id}). + For Hindsight Inference: https://inference.hindsight.vectorize.io/v1 poll_interval: Seconds to wait between status checks (default: 2) timeout: Maximum seconds to wait for extraction (default: 300) options: Extraction options (chunking, metadata, etc.) @@ -157,18 +161,10 @@ async def extract_text_async( Raises: VectorizeIrisError: If extraction fails or times out """ - # Get credentials from environment if not provided - api_token = api_token or os.getenv('VECTORIZE_TOKEN') - org_id = org_id or os.getenv('VECTORIZE_ORG_ID') - - if not api_token or not org_id: - raise VectorizeIrisError( - "Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID " - "environment variables or pass them as parameters." - ) + api_token, base_url = resolve(api_token, org_id, base_url) return await _extract_from_bytes_async( - file_bytes, file_name, api_token, org_id, poll_interval, timeout, options + file_bytes, file_name, api_token, base_url, poll_interval, timeout, options ) @@ -176,6 +172,7 @@ async def extract_text_from_file_async( file_path: str, api_token: Optional[str] = None, org_id: Optional[str] = None, + base_url: Optional[str] = None, poll_interval: int = 2, timeout: int = 300, options: Optional[ExtractionOptions] = None @@ -186,7 +183,10 @@ async def extract_text_from_file_async( Args: file_path: Path to the file to extract text from api_token: Vectorize access token (defaults to VECTORIZE_TOKEN env var) - org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var) + org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with base_url + base_url: API root that /files and /extraction hang off (defaults to the + VECTORIZE_IRIS_BASE_URL env var, then https://api.vectorize.io/v1/org/{org_id}). + For Hindsight Inference: https://inference.hindsight.vectorize.io/v1 poll_interval: Seconds to wait between status checks (default: 2) timeout: Maximum seconds to wait for extraction (default: 300) options: Extraction options (chunking, metadata, etc.) @@ -198,15 +198,7 @@ async def extract_text_from_file_async( VectorizeIrisError: If extraction fails or times out FileNotFoundError: If the file doesn't exist """ - # Get credentials from environment if not provided - api_token = api_token or os.getenv('VECTORIZE_TOKEN') - org_id = org_id or os.getenv('VECTORIZE_ORG_ID') - - if not api_token or not org_id: - raise VectorizeIrisError( - "Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID " - "environment variables or pass them as parameters." - ) + api_token, base_url = resolve(api_token, org_id, base_url) # Validate file exists and read content file_path_obj = Path(file_path) @@ -219,5 +211,5 @@ async def extract_text_from_file_async( file_name = file_path_obj.name return await _extract_from_bytes_async( - file_content, file_name, api_token, org_id, poll_interval, timeout, options + file_content, file_name, api_token, base_url, poll_interval, timeout, options ) diff --git a/python-api/vectorize_iris/client.py b/python-api/vectorize_iris/client.py index 97cf64c..f960333 100644 --- a/python-api/vectorize_iris/client.py +++ b/python-api/vectorize_iris/client.py @@ -8,6 +8,7 @@ from typing import Optional from pathlib import Path +from vectorize_iris.config import resolve from vectorize_iris.exceptions import VectorizeIrisError from vectorize_iris.models import ( StartFileUploadRequest, @@ -24,7 +25,7 @@ def _extract_from_bytes( file_content: bytes, file_name: str, api_token: str, - org_id: str, + base_url: str, poll_interval: int, timeout: int, options: Optional[ExtractionOptions] = None @@ -32,7 +33,6 @@ def _extract_from_bytes( """ Internal function to extract from file bytes. """ - base_url = f"https://api.vectorize.io/v1/org/{org_id}" headers = { "Authorization": f"Bearer {api_token}", "Content-Type": "application/json" @@ -130,6 +130,7 @@ def extract_text( file_name: str = "document.pdf", api_token: Optional[str] = None, org_id: Optional[str] = None, + base_url: Optional[str] = None, poll_interval: int = 2, timeout: int = 300, options: Optional[ExtractionOptions] = None @@ -141,7 +142,10 @@ def extract_text( file_bytes: File content as bytes file_name: Name of the file (default: "document.pdf") api_token: Vectorize access token (defaults to VECTORIZE_TOKEN env var) - org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var) + org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with base_url + base_url: API root that /files and /extraction hang off (defaults to the + VECTORIZE_IRIS_BASE_URL env var, then https://api.vectorize.io/v1/org/{org_id}). + For Hindsight Inference: https://inference.hindsight.vectorize.io/v1 poll_interval: Seconds to wait between status checks (default: 2) timeout: Maximum seconds to wait for extraction (default: 300) options: Extraction options (chunking, metadata, etc.) @@ -159,18 +163,10 @@ def extract_text( >>> print(result.text) >>> print(result.chunks) # If chunking was requested """ - # Get credentials from environment if not provided - api_token = api_token or os.getenv('VECTORIZE_TOKEN') - org_id = org_id or os.getenv('VECTORIZE_ORG_ID') - - if not api_token or not org_id: - raise VectorizeIrisError( - "Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID " - "environment variables or pass them as parameters." - ) + api_token, base_url = resolve(api_token, org_id, base_url) return _extract_from_bytes( - file_bytes, file_name, api_token, org_id, poll_interval, timeout, options + file_bytes, file_name, api_token, base_url, poll_interval, timeout, options ) @@ -178,6 +174,7 @@ def extract_text_from_file( file_path: str, api_token: Optional[str] = None, org_id: Optional[str] = None, + base_url: Optional[str] = None, poll_interval: int = 2, timeout: int = 300, options: Optional[ExtractionOptions] = None @@ -188,7 +185,10 @@ def extract_text_from_file( Args: file_path: Path to the file to extract text from api_token: Vectorize access token (defaults to VECTORIZE_TOKEN env var) - org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var) + org_id: Organization ID (defaults to VECTORIZE_ORG_ID env var); not needed with base_url + base_url: API root that /files and /extraction hang off (defaults to the + VECTORIZE_IRIS_BASE_URL env var, then https://api.vectorize.io/v1/org/{org_id}). + For Hindsight Inference: https://inference.hindsight.vectorize.io/v1 poll_interval: Seconds to wait between status checks (default: 2) timeout: Maximum seconds to wait for extraction (default: 300) options: Extraction options (chunking, metadata, etc.) @@ -228,15 +228,7 @@ def extract_text_from_file( >>> result = extract_text_from_file("document.pdf", options=options) >>> print(result.metadata) # JSON string """ - # Get credentials from environment if not provided - api_token = api_token or os.getenv('VECTORIZE_TOKEN') - org_id = org_id or os.getenv('VECTORIZE_ORG_ID') - - if not api_token or not org_id: - raise VectorizeIrisError( - "Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID " - "environment variables or pass them as parameters." - ) + api_token, base_url = resolve(api_token, org_id, base_url) # Validate file exists and read content file_path_obj = Path(file_path) @@ -249,5 +241,5 @@ def extract_text_from_file( file_name = file_path_obj.name return _extract_from_bytes( - file_content, file_name, api_token, org_id, poll_interval, timeout, options + file_content, file_name, api_token, base_url, poll_interval, timeout, options ) diff --git a/python-api/vectorize_iris/config.py b/python-api/vectorize_iris/config.py new file mode 100644 index 0000000..9ec74b0 --- /dev/null +++ b/python-api/vectorize_iris/config.py @@ -0,0 +1,41 @@ +""" +Where the client sends requests: the API root that /files and /extraction hang off. +""" + +import os +from typing import Optional, Tuple + +from vectorize_iris.exceptions import VectorizeIrisError + +DEFAULT_API_URL = "https://api.vectorize.io" + + +def resolve( + api_token: Optional[str], + org_id: Optional[str], + base_url: Optional[str], +) -> Tuple[str, str]: + """ + Return (api_token, base_url) from the arguments, falling back to the environment. + + With a base URL (argument or VECTORIZE_IRIS_BASE_URL), requests go to it as given and no + organization ID is needed: Hindsight Inference takes the organization from the key, e.g. + base_url="https://inference.hindsight.vectorize.io/v1". Without one, requests go to + https://api.vectorize.io/v1/org/{org_id}, which needs VECTORIZE_ORG_ID. + """ + api_token = api_token or os.getenv("VECTORIZE_TOKEN") + base_url = base_url or os.getenv("VECTORIZE_IRIS_BASE_URL") + if base_url: + if not api_token: + raise VectorizeIrisError( + "Missing credentials. Set VECTORIZE_TOKEN or pass api_token." + ) + return api_token, base_url.rstrip("/") + + org_id = org_id or os.getenv("VECTORIZE_ORG_ID") + if not api_token or not org_id: + raise VectorizeIrisError( + "Missing credentials. Set VECTORIZE_TOKEN and VECTORIZE_ORG_ID " + "environment variables or pass them as parameters." + ) + return api_token, f"{DEFAULT_API_URL}/v1/org/{org_id}" diff --git a/rust-cli/Cargo.toml b/rust-cli/Cargo.toml index 33288aa..ee1ad0b 100644 --- a/rust-cli/Cargo.toml +++ b/rust-cli/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "vectorize-iris" -version = "0.1.0" +version = "0.2.0" edition = "2021" authors = ["Vectorize"] description = "CLI tool for extracting text from files using Vectorize Iris" diff --git a/rust-cli/src/main.rs b/rust-cli/src/main.rs index d9b8282..065e27c 100644 --- a/rust-cli/src/main.rs +++ b/rust-cli/src/main.rs @@ -49,6 +49,12 @@ struct Cli { #[arg(long, global = true, hide = true)] api_url: Option, + /// API root that /files and /extraction hang off, used as given; no org ID needed. + /// For Hindsight Inference: https://inference.hindsight.vectorize.io/v1 + /// (defaults to VECTORIZE_IRIS_BASE_URL env var, then config file base_url) + #[arg(long, global = true)] + base_url: Option, + /// Output format (pretty: styled output, json: JSON format, yaml: YAML format, text: plain text only) #[arg(short = 'o', long, value_enum, default_value = "pretty")] output: OutputFormat, @@ -249,9 +255,8 @@ fn download_url(url: &str) -> Result { fn process_directory( dir_path: &PathBuf, - api_base_url: &str, + base_url: &str, api_token: &str, - org_id: &str, output_format: &OutputFormat, output_dir: Option<&PathBuf>, chunk_size: Option, @@ -310,9 +315,8 @@ fn process_directory( match extract_text( &file_path, - api_base_url, + base_url, api_token, - org_id, chunk_size, metadata_schemas.clone(), infer_metadata_schema, @@ -365,9 +369,8 @@ fn process_directory( fn extract_text( file_path: &PathBuf, - api_base_url: &str, + base_url: &str, api_token: &str, - org_id: &str, chunk_size: Option, metadata_schemas: Vec, infer_metadata_schema: bool, @@ -389,7 +392,6 @@ fn extract_text( return Err(anyhow!("File not found: {}", file_path.display())); } - let base_url = format!("{}/v1/org/{}", api_base_url, org_id); let client = Client::new(); let file_name = file_path @@ -911,11 +913,11 @@ fn get_credentials_path() -> Result { Ok(get_config_dir()?.join("credentials")) } -fn read_credentials() -> Result<(Option, Option, Option)> { +fn read_credentials() -> Result<(Option, Option, Option, Option)> { let creds_path = get_credentials_path()?; if !creds_path.exists() { - return Ok((None, None, None)); + return Ok((None, None, None, None)); } let content = fs::read_to_string(&creds_path) @@ -924,6 +926,7 @@ fn read_credentials() -> Result<(Option, Option, Option) let mut api_token = None; let mut org_id = None; let mut api_url = None; + let mut base_url = None; let mut in_default_section = false; for line in content.lines() { @@ -949,13 +952,14 @@ fn read_credentials() -> Result<(Option, Option, Option) "api_token" => api_token = Some(value.to_string()), "org_id" => org_id = Some(value.to_string()), "api_url" => api_url = Some(value.to_string()), + "base_url" => base_url = Some(value.to_string()), _ => {} } } } } - Ok((api_token, org_id, api_url)) + Ok((api_token, org_id, api_url, base_url)) } fn write_credentials(api_token: &str, org_id: &str) -> Result<()> { @@ -1263,6 +1267,25 @@ fn parse_callback(stream: std::net::TcpStream) -> Result<(String, String)> { Ok((access_token, org_id)) } +/// The API root requests go to. A base URL is used as given and needs no org ID (Hindsight +/// Inference takes the organization from the key); otherwise `{api_url}/v1/org/{org_id}`, with +/// api_url defaulting to https://api.vectorize.io. +fn resolve_base_url( + base_url: Option, + api_url: Option, + org_id: Option, +) -> Result { + if let Some(base) = base_url.filter(|b| !b.trim().is_empty()) { + return Ok(base.trim().trim_end_matches('/').to_string()); + } + let org_id = org_id.context( + "Missing org ID. Set with 'vectorize-iris configure', VECTORIZE_ORG_ID env var, or --org-id flag \ + (or set a base URL with --base-url or VECTORIZE_IRIS_BASE_URL)", + )?; + let api_url = api_url.unwrap_or_else(|| "https://api.vectorize.io".to_string()); + Ok(format!("{}/v1/org/{}", api_url.trim_end_matches('/'), org_id)) +} + fn main() -> Result<()> { let cli = Cli::parse(); @@ -1288,7 +1311,8 @@ fn main() -> Result<()> { .context("FILE argument is required for extraction. Use 'vectorize-iris configure' to set up credentials.")?; // Get credentials in order: CLI args -> env vars -> config file - let (config_api_token, config_org_id, config_api_url) = read_credentials().unwrap_or((None, None, None)); + let (config_api_token, config_org_id, config_api_url, config_base_url) = + read_credentials().unwrap_or((None, None, None, None)); let api_token = cli.api_token .or_else(|| env::var("VECTORIZE_TOKEN").ok()) @@ -1297,15 +1321,17 @@ fn main() -> Result<()> { "Missing access token. Set with 'vectorize-iris configure', VECTORIZE_TOKEN env var, or --api-token flag", )?; - let org_id = cli.org_id - .or_else(|| env::var("VECTORIZE_ORG_ID").ok()) - .or(config_org_id) - .context("Missing org ID. Set with 'vectorize-iris configure', VECTORIZE_ORG_ID env var, or --org-id flag")?; - - let api_base_url = cli.api_url - .or_else(|| env::var("VECTORIZE_API_URL").ok()) - .or(config_api_url) - .unwrap_or_else(|| "https://api.vectorize.io".to_string()); + let base_url = resolve_base_url( + cli.base_url + .or_else(|| env::var("VECTORIZE_IRIS_BASE_URL").ok()) + .or(config_base_url), + cli.api_url + .or_else(|| env::var("VECTORIZE_API_URL").ok()) + .or(config_api_url), + cli.org_id + .or_else(|| env::var("VECTORIZE_ORG_ID").ok()) + .or(config_org_id), + )?; // Automatically set infer_metadata_schema to false if metadata schemas are provided let infer_metadata_schema = if !cli.metadata_schemas.is_empty() { @@ -1328,9 +1354,8 @@ fn main() -> Result<()> { // Process all files in directory return process_directory( &file_path, - &api_base_url, + &base_url, &api_token, - &org_id, &cli.output, cli.output_file.as_ref(), cli.chunk_size, @@ -1348,9 +1373,8 @@ fn main() -> Result<()> { let result = extract_text( &file_path, - &api_base_url, + &base_url, &api_token, - &org_id, cli.chunk_size, cli.metadata_schemas, infer_metadata_schema, @@ -1365,3 +1389,40 @@ fn main() -> Result<()> { Ok(()) } + +#[cfg(test)] +mod tests { + use super::resolve_base_url; + + const HINDSIGHT: &str = "https://inference.hindsight.vectorize.io/v1"; + + #[test] + fn default_is_api_vectorize_io_with_the_org() { + assert_eq!( + resolve_base_url(None, None, Some("org-1".into())).unwrap(), + "https://api.vectorize.io/v1/org/org-1" + ); + } + + #[test] + fn api_url_still_replaces_only_the_host() { + assert_eq!( + resolve_base_url(None, Some("https://api.example/".into()), Some("org-1".into())).unwrap(), + "https://api.example/v1/org/org-1" + ); + } + + #[test] + fn base_url_is_used_as_given_and_needs_no_org() { + assert_eq!(resolve_base_url(Some(format!("{HINDSIGHT}/")), None, None).unwrap(), HINDSIGHT); + assert_eq!( + resolve_base_url(Some(HINDSIGHT.into()), Some("https://api.example".into()), Some("org-1".into())).unwrap(), + HINDSIGHT + ); + } + + #[test] + fn without_a_base_url_the_org_is_required() { + assert!(resolve_base_url(None, None, None).is_err()); + } +}