### Install Dependencies and Build Project with Yarn Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Installs project dependencies using Yarn and builds the project, outputting build files to the `dist/` directory. This is the initial setup step for the repository. ```shell $ yarn $ yarn build ``` -------------------------------- ### Add and Run TypeScript Examples Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Demonstrates how to add a new TypeScript example file to the `examples/` directory and how to make it executable and run it. This is useful for testing SDK functionality. ```typescript // add an example to examples/.ts #!/usr/bin/env -S npm run tsn -T … ``` ```shell $ chmod +x examples/.ts # run the example against your api $ yarn tsn -T examples/.ts ``` -------------------------------- ### Install SDK from Git Repository Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Installs the TypeScript SDK directly from a Git repository using npm. This is an alternative to linking a local copy. ```shell $ npm install git+ssh://git@github.com:caesar-data/typescript-sdk.git ``` -------------------------------- ### JavaScript: Import and Initialize Caesar MCP Server and Tools Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md This snippet shows how to import the Caesar MCP server, its generated endpoints, and the `init` function from the SDK. It also demonstrates importing specific tools like `createResearch`. The example covers initializing the server with default endpoints, manually starting the server with a transport, and initializing a custom server with user-defined endpoints. ```javascript // Import the server, generated endpoints, or the init function import { server, endpoints, init } from "caesar-mcp/server"; // import a specific tool import createResearch from "caesar-mcp/tools/research/create-research"; // initialize the server and all endpoints init({ server, endpoints }); // manually start server const transport = new StdioServerTransport(); await server.connect(transport); // or initialize your own server with specific tools const myServer = new McpServer(...); // define your own endpoint const myCustomEndpoint = { tool: { name: 'my_custom_tool', description: 'My custom tool', inputSchema: zodToJsonSchema(z.object({ a_property: z.string() })), }, handler: async (client: client, args: any) => { return { myResponse: 'Hello world!' }; }) }; // initialize the server with your custom endpoints init({ server: myServer, endpoints: [createResearch, myCustomEndpoint] }); ``` -------------------------------- ### Run Project Tests Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Executes all the tests within the repository. Assumes that necessary setup, such as a mock server, has been configured. ```shell $ yarn run test ``` -------------------------------- ### Set up Mock Server for Testing with Prism Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Configures a mock server using Prism against an OpenAPI specification. This is a prerequisite for running most of the repository's tests. ```shell $ npx prism mock path/to/your/openapi.yml ``` -------------------------------- ### Install Caesar Data NPM Package Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Installs the caesar-data npm package. This is the first step to using the library in your project. ```sh npm install caesar-data ``` -------------------------------- ### Publish NPM Package Manually Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Instructions for manually publishing the package to npm using a provided script. This requires setting an NPM_TOKEN environment variable. ```shell bin/publish-npm ``` -------------------------------- ### Lint and Format Code with Yarn Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Commands to perform code linting and automatic formatting using Prettier and ESLint, managed by Yarn. This ensures code quality and consistency. ```shell $ yarn lint $ yarn fix ``` -------------------------------- ### MCP Client Configuration JSON Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md Example configuration JSON for an MCP client to connect to the Caesar MCP Server. It specifies the command, arguments, and environment variables for the server. ```json { "mcpServers": { "caesar_data_api": { "command": "npx", "args": ["-y", "caesar-mcp", "--client=claude", "--tools=all"], "env": { "CAESAR_API_KEY": "My API Key" } } } } ``` -------------------------------- ### Link Local SDK Repository with Yarn and PNPM Source: https://github.com/caesar-data/typescript-sdk/blob/main/CONTRIBUTING.md Provides instructions for linking a local clone of the SDK repository to another project using Yarn or PNPM. This allows for development and testing of the SDK without publishing. ```shell # Clone $ git clone https://www.github.com/caesar-data/typescript-sdk $ cd typescript-sdk # With yarn $ yarn link $ cd ../my-package $ yarn link caesar-data # With pnpm $ pnpm link --global $ cd ../my-package $ pnpm link -—global caesar-data ``` -------------------------------- ### Install Caesar MCP Server via npx Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md Directly invoke the MCP Server using npx. This method requires setting the CAESAR_API_KEY environment variable. ```shell export CAESAR_API_KEY="My API Key" npx -y caesar-mcp@latest ``` -------------------------------- ### Configure Custom Fetch and Proxy with TypeScript Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Illustrates how to configure custom fetch implementations and proxy settings for the Caesar SDK in TypeScript. It includes examples for Node.js with `undici`, Bun, and Deno, utilizing custom `fetch` functions and proxy agents. ```typescript import Caesar from 'caesar-data'; import * as undici from 'undici'; import fetch from 'node-fetch'; // Custom fetch function const customClient = new Caesar({ fetch: fetch as any, fetchOptions: { // Additional fetch options } }); // Node.js proxy configuration with undici const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const proxiedClient = new Caesar({ fetchOptions: { dispatcher: proxyAgent, } }); // Bun proxy configuration const bunClient = new Caesar({ fetchOptions: { proxy: 'http://localhost:8888', } }); // Deno proxy configuration const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const denoClient = new Caesar({ fetchOptions: { client: httpClient, } }); // Usage remains the same const research = await proxiedClient.research.create({ query: 'Research through proxy', }); ``` -------------------------------- ### Complex MCP Server Filtering Example Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md An example of complex filtering for the MCP Server, combining multiple resource inclusions, operation types, tag filtering, and specific tool exclusions. ```bash --resource=cards,accounts --operation=read --tag=kyc --no-tool=create_cards ``` -------------------------------- ### Filter MCP Server Tools by Resource and Operation Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md Command-line arguments to filter the tools exposed by the MCP Server. This example includes read operations for 'cards'. ```bash --resource=cards --operation=read ``` -------------------------------- ### List Uploaded Files with Pagination (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates how to retrieve a list of all uploaded files using the Caesar SDK. Includes examples for both automatic pagination and manual control over page navigation. Requires the 'caesar-data' package. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); async function listAllFiles() { try { // Automatic pagination console.log('--- All Uploaded Files ---'); for await (const file of client.research.files.list({ limit: 50 })) { console.log(`ID: ${file.id}`); console.log(`Name: ${file.file_name}`); console.log(`Type: ${file.content_type}`); console.log('---'); } // Manual pagination let page = await client.research.files.list({ limit: 20, page: 1 }); console.log(`Found ${page.data.length} files on first page`); while (page.hasNextPage()) { page = await page.getNextPage(); console.log(`Page ${page.page}: ${page.data.length} files`); } } catch (error) { if (error instanceof Caesar.APIError) { console.error('Failed to list files:', error.message); } throw error; } } listAllFiles(); ``` -------------------------------- ### Configure Deno HTTP Client Proxy for Caesar SDK in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Provides an example of setting up a custom HTTP client with proxy support for Deno environments when using the Caesar Data SDK. This involves using `Deno.createHttpClient` to define proxy configurations. ```typescript import Caesar from 'npm:caesar-data'; const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const client = new Caesar({ fetchOptions: { client: httpClient, }, }); ``` -------------------------------- ### Initialize Caesar Client and Create Research Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Initializes the Caesar client using an API key and demonstrates how to create a research object. The API key is typically read from environment variables. This is a basic usage example. ```js import Caesar from 'caesar-data'; const client = new Caesar({ apiKey: process.env['CAESAR_API_KEY'], // This is the default and can be omitted }); const research = await client.research.create({ query: 'REPLACE_ME' }); console.log(research.id); ``` -------------------------------- ### Exclude Specific Tools and Include Others Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md Command-line arguments to configure the MCP Server to include specific resources while excluding certain tools. This example includes 'cards' but excludes 'create_cards'. ```bash --resource=cards --no-tool=create_cards ``` -------------------------------- ### List Research Jobs with Pagination (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates how to list research jobs using the Caesar SDK. It includes examples of both automatic pagination with async iteration and manual control over pagination. Requires the 'caesar-data' package. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); // Automatic pagination with async iteration async function fetchAllResearch() { const allResearch = []; try { // Automatically fetches all pages for await (const research of client.research.list({ limit: 30 })) { allResearch.push(research); console.log(`${research.id}: ${research.query} (${research.status})`); } console.log(`\nTotal research jobs: ${allResearch.length}`); return allResearch; } catch (error) { if (error instanceof Caesar.APIError) { console.error('Failed to fetch research:', error.message); } throw error; } } // Manual pagination control async function fetchResearchManually() { let page = await client.research.list({ limit: 10, page: 1 }); for (const research of page.data) { console.log(`${research.id}: ${research.query}`); } // Navigate through pages while (page.hasNextPage()) { page = await page.getNextPage(); console.log(`\n--- Page ${page.page} ---`); for (const research of page.data) { console.log(`${research.id}: ${research.query}`); } } } fetchAllResearch(); ``` -------------------------------- ### Making Custom/Undocumented Requests Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Guides users on how to make requests to undocumented endpoints or use undocumented parameters. ```APIDOC ## Making custom/undocumented requests This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used. #### Undocumented endpoints To make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs. Options on the client, such as retries, will be respected when making these requests. ```ts await client.post('/some/path', { body: { some_prop: 'foo' }, query: { some_query_arg: 'bar' }, }); ``` #### Undocumented request params To make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you send will be sent as-is. ```ts client.research.create({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` For requests with the `GET` verb, any extra params will be in the query, all other requests will send the extra param in the body. If you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request options. ``` -------------------------------- ### Access Raw Response Data with TypeScript Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates how to access raw HTTP response headers and metadata using the Caesar SDK in TypeScript. It shows how to use `asResponse()` to get the raw `Response` object and `withResponse()` to retrieve both parsed data and the raw `Response`. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); async function inspectResponse() { // Using asResponse() - returns raw Response immediately const response = await client.research.create({ query: 'Sample query' }).asResponse(); console.log('Status:', response.status); console.log('Status Text:', response.statusText); console.log('Custom Header:', response.headers.get('X-Custom-Header')); console.log('Rate Limit:', response.headers.get('X-RateLimit-Remaining')); // Parse body manually if needed const data = await response.json(); console.log('Research ID:', data.id); // Using withResponse() - returns both parsed data and raw Response const { data: research, response: raw } = await client.research .create({ query: 'Another query' }) .withResponse(); console.log('Parsed ID:', research.id); console.log('Raw Headers:', raw.headers); console.log('Request ID:', raw.headers.get('X-Request-ID')); } insp ``` -------------------------------- ### Configure Node.js Proxy with Undici for Caesar SDK in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates configuring a proxy agent for Node.js environments using the `undici` library with the Caesar Data SDK. This is essential for routing requests through a proxy server, often used in corporate or specific network setups. ```typescript import Caesar from 'caesar-data'; import * as undici from 'undici'; const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const client = new Caesar({ fetchOptions: { dispatcher: proxyAgent, }, }); ``` -------------------------------- ### Access Raw Response Data and Headers (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Shows how to access the raw HTTP `Response` object, including headers, using the `.asResponse()` method, and how to get both the parsed data and the raw response using `.withResponse()`. This is useful for inspecting response metadata or handling custom parsing logic. ```typescript const client = new Caesar(); const response = await client.research.create({ query: 'REPLACE_ME' }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object const { data: research, response: raw } = await client.research .create({ query: 'REPLACE_ME' }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(research.id); ``` -------------------------------- ### Retrieve Completed Research Job with Results and Citations (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Provides an example of retrieving a completed research job by its ID. It demonstrates accessing the research query, status, creation timestamp, synthesized content, transformed content, and iterating through ranked results with their titles, URLs, relevance scores, and citation indices. Includes specific error handling for 'Not Found' and general API errors. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); try { const researchId = 'research_abc123'; const research = await client.research.retrieve(researchId); console.log('Query:', research.query); console.log('Status:', research.status); console.log('Created:', research.created_at); // Access synthesized content if (research.content) { console.log('\n--- Research Summary ---'); console.log(research.content); } // Access transformed content (formatted version) if (research.transformed_content) { console.log('\n--- Formatted Content ---'); console.log(research.transformed_content); } // Iterate through ranked results with citations console.log('\n--- Sources ---'); research.results.forEach((result, index) => { console.log(`${index + 1}. ${result.title}`); console.log(` URL: ${result.url}`); console.log(` Relevance Score: ${result.score.toFixed(3)}`); if (result.citation_index !== undefined) { console.log(` Citation: [${result.citation_index}]`); } }); } catch (error) { if (error instanceof Caesar.NotFoundError) { console.error('Research not found:', researchId); } else if (error instanceof Caesar.APIError) { console.error('API Error:', error.status, error.message); } else { throw error; } } ``` -------------------------------- ### Retrieve Research Result Content with TypeScript Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Fetches and displays the raw content of a specific research result using the Caesar SDK. It first retrieves the research object to list available results, then targets a specific resultId to get its content. Includes basic error handling for Not Found and API errors. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); async function getResultContent(researchId: string, resultId: string) { try { // First, get the research object to see available results const research = await client.research.retrieve(researchId); console.log('Available results:'); research.results.forEach((result, idx) => { console.log(`${idx + 1}. ${result.title} (${result.id})`); }); // Retrieve content for a specific result const resultContent = await client.research.results.retrieveContent( resultId, { id: researchId } ); console.log('\n--- Raw Content ---'); console.log(resultContent.content); return resultContent.content; } catch (error) { if (error instanceof Caesar.NotFoundError) { console.error('Research or result not found'); } else if (error instanceof Caesar.APIError) { console.error('Failed to retrieve content:', error.message); } throw error; } } // Example usage const researchId = '182bd5e5-6e1a-4fe4-a799-aa6d9a6ab26e'; const resultId = '282bd5e5-6e1a-4fe4-a799-aa6d9a6ab26f'; getResultContent(researchId, resultId); ``` -------------------------------- ### Initialize Caesar Client with API Key Authentication (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates how to initialize the Caesar client using an API key. It shows default initialization using an environment variable and custom configuration with specific API key, base URL, timeout, retry, log level, and fetch options. ```typescript import Caesar from 'caesar-data'; // Using environment variable CAESAR_API_KEY const client = new Caesar({ apiKey: process.env['CAESAR_API_KEY'], // Default if not specified }); // With custom configuration const customClient = new Caesar({ apiKey: 'your-api-key-here', baseURL: 'https://api.caesar.xyz', timeout: 30000, // 30 seconds maxRetries: 3, logLevel: 'info', fetchOptions: { // Custom fetch options } }); ``` -------------------------------- ### Create a New Research Job with Query and Files (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Shows how to create a new research job using the Caesar client. It covers basic research queries and advanced options including file attachments, compute unit allocation, and system prompts. Includes error handling for API errors. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); try { // Basic research query const research = await client.research.create({ query: 'Is lithium supply a bottleneck for EV adoption?', }); console.log('Research ID:', research.id); console.log('Status:', research.status); // 'queued', 'searching', 'summarizing', etc. // Advanced research with files and custom settings const advancedResearch = await client.research.create({ query: 'Analyze quarterly financial performance trends', files: ['file_id_1', 'file_id_2'], // Previously uploaded file IDs compute_units: 5, // Allocate more compute resources system_prompt: 'Focus on financial metrics and provide numerical analysis', }); console.log('Advanced Research ID:', advancedResearch.id); } catch (error) { if (error instanceof Caesar.APIError) { console.error('API Error:', error.status, error.message); } else { throw error; } } ``` -------------------------------- ### Custom Fetch and Proxy Configuration Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates how to configure custom fetch implementations and proxy settings for the Caesar SDK client. ```APIDOC ## Caesar Client Configuration ### Description Configure custom fetch implementations or proxy settings when initializing the Caesar client. ### Method Constructor ### Endpoint N/A ### Parameters #### Request Body (Client Options) - **fetch** (Function) - Optional - A custom fetch implementation. - **fetchOptions** (object) - Optional - Options to pass to the fetch implementation. - **proxy** (string) - Optional - URL for proxy configuration (e.g., for Bun). - **dispatcher** (object) - Optional - Dispatcher for proxy configuration (e.g., for Node.js with undici). - **client** (object) - Optional - HTTP client for proxy configuration (e.g., for Deno). ### Request Example ```typescript import Caesar from 'caesar-data'; import * as undici from 'undici'; import fetch from 'node-fetch'; // Using custom fetch const customClient = new Caesar({ fetch: fetch as any, fetchOptions: { // Additional fetch options } }); // Using Node.js proxy with undici const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); const proxiedClient = new Caesar({ fetchOptions: { dispatcher: proxyAgent, } }); // Using Bun proxy const bunClient = new Caesar({ fetchOptions: { proxy: 'http://localhost:8888', } }); // Using Deno proxy const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } }); const denoClient = new Caesar({ fetchOptions: { client: httpClient, } }); ``` ### Response #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Configure Bun Proxy for Caesar SDK in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Shows how to configure proxy settings for Bun runtime when using the Caesar Data SDK. Bun provides a straightforward `proxy` option within `fetchOptions` for easy proxy integration. ```typescript import Caesar from 'caesar-data'; const client = new Caesar({ fetchOptions: { proxy: 'http://localhost:8888', }, }); ``` -------------------------------- ### Research Creation API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Creates a new research project. ```APIDOC ## POST /research ### Description Creates a new research project. ### Method POST ### Endpoint /research ### Parameters #### Request Body - **params** (object) - Required - Parameters for research creation. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **ResearchCreateResponse** (object) - Details of the created research project. #### Response Example ```json { "ResearchCreateResponse": { ... } } ``` ``` -------------------------------- ### Advanced Caesar SDK Configuration with TypeScript Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Illustrates how to configure the Caesar SDK client globally with options for API keys, retries, timeouts, and logging levels. It also shows how to override these settings for individual requests, such as adjusting the timeout and retry count for a specific operation. ```typescript import Caesar from 'caesar-data'; // Global client configuration const client = new Caesar({ apiKey: process.env['CAESAR_API_KEY'], maxRetries: 5, // Retry up to 5 times (default: 2) timeout: 120000, // 2 minutes (default: 60000) logLevel: 'debug', // 'debug', 'info', 'warn', 'error', 'off' logger: console, // Custom logger (pino, winston, etc.) }); // Per-request configuration async function configuredRequest() { try { // Override timeout and retries for specific request const research = await client.research.create( { query: 'Complex research requiring more time', compute_units: 10, }, { timeout: 180000, // 3 minutes for this request maxRetries: 3, headers: { 'X-Custom-Header': 'value', }, } ); return research; } catch (error) { if (error instanceof Caesar.APIConnectionTimeoutError) { console.error('Request exceeded 3 minute timeout'); } throw error; } } configuredRequest(); ``` -------------------------------- ### Logging Configuration Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Details how to configure logging levels and use custom loggers for the SDK. ```APIDOC ## Logging > [!IMPORTANT] > All log messages are intended for debugging only. The format and content of log messages > may change between releases. #### Log levels The log level can be configured in two ways: 1. Via the `CAESAR_LOG` environment variable 2. Using the `logLevel` client option (overrides the environment variable if set) ```ts import Caesar from 'caesar-data'; const client = new Caesar({ logLevel: 'debug', // Show all log messages }); ``` Available log levels, from most to least verbose: - `'debug'` - Show debug messages, info, warnings, and errors - `'info'` - Show info messages, warnings, and errors - `'warn'` - Show warnings and errors (default) - `'error'` - Show only errors - `'off'` - Disable all logging At the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies. Some authentication-related headers are redacted, but sensitive data in request and response bodies may still be visible. #### Custom logger By default, this library logs to `globalThis.console`. You can also provide a custom logger. Most logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). If your logger doesn't work, please open an issue. When providing a custom logger, the `logLevel` option still controls which messages are emitted, messages below the configured level will not be sent to your logger. ```ts import Caesar from 'caesar-data'; import pino from 'pino'; const logger = pino(); const client = new Caesar({ logger: logger.child({ name: 'Caesar' }), logLevel: 'debug', // Send all messages to pino, allowing it to filter }); ``` ``` -------------------------------- ### Set Default Fetch Options for Caesar SDK in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Illustrates how to provide default `fetchOptions` during the instantiation of the Caesar Data client. These options will be applied to all requests made by the client unless overridden at the individual request level. ```typescript import Caesar from 'caesar-data'; const client = new Caesar({ fetchOptions: { // `RequestInit` options }, }); ``` -------------------------------- ### Upload Files for Research Queries (TypeScript) Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Shows how to upload files using the Caesar SDK for use in research queries. Supports various input types including Node.js ReadStream, Web File API, Fetch API Response, Buffers, and Uint8Arrays. Requires 'caesar-data' and Node.js 'fs' module. ```typescript import Caesar, { toFile } from 'caesar-data'; import fs from 'fs'; const client = new Caesar(); try { // Using Node.js fs.ReadStream (recommended for Node.js) const fileFromStream = await client.research.files.create({ file: fs.createReadStream('./data/report.pdf'), }); console.log('File ID:', fileFromStream.id); console.log('Filename:', fileFromStream.file_name); console.log('Content Type:', fileFromStream.content_type); // Using web File API (browsers/Deno) const fileFromWeb = await client.research.files.create({ file: new File(['CSV data here'], 'data.csv', { type: 'text/csv' }), }); // Using fetch Response const fileFromUrl = await client.research.files.create({ file: await fetch('https://example.com/document.docx'), }); // Using toFile helper with Buffer or Uint8Array const fileFromBuffer = await client.research.files.create({ file: await toFile(Buffer.from('file content'), 'document.txt'), }); const fileFromBytes = await client.research.files.create({ file: await toFile(new Uint8Array([0, 1, 2]), 'binary.dat'), }); // Use uploaded file in research const research = await client.research.create({ query: 'Summarize the key findings in the uploaded report', files: [fileFromStream.id], }); console.log('Research created:', research.id); } catch (error) { if (error instanceof Caesar.BadRequestError) { console.error('Invalid file upload:', error.message); } else if (error instanceof Caesar.APIError) { console.error('Upload failed:', error.status, error.message); } else { throw error; } } ``` -------------------------------- ### Polyfill Global Fetch in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to replace the default global `fetch` function with a custom implementation for use with the Caesar Data SDK. This is useful when you need to use a specific fetching library or add custom logic to all outgoing requests. ```typescript import fetch from 'my-fetch'; globalThis.fetch = fetch; ``` -------------------------------- ### Pass Custom Fetch Client to Caesar SDK in TypeScript Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Shows how to instantiate the Caesar Data SDK with a custom `fetch` implementation. This allows for centralized control over HTTP requests, such as adding authentication headers or custom logging, without modifying the global scope. ```typescript import Caesar from 'caesar-data'; import fetch from 'my-fetch'; const client = new Caesar({ fetch }); ``` -------------------------------- ### Use Custom Logger with Caesar SDK (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Explains how to integrate a custom logger, such as Pino, with the Caesar SDK. This allows developers to leverage their existing logging infrastructure for SDK-generated messages, providing centralized log management and advanced filtering. ```typescript import Caesar from 'caesar-data'; import pino from 'pino'; const logger = pino(); const client = new Caesar({ logger: logger.child({ name: 'Caesar' }), logLevel: 'debug', // Send all messages to pino, allowing it to filter }); ``` -------------------------------- ### Uploading Files with Caesar SDK Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Shows various methods for uploading files using the Caesar TypeScript SDK. It supports `fs.ReadStream` from Node.js, Web `File` API, `fetch` `Response`, and a custom `toFile` helper function. ```ts import fs from 'fs'; import Caesar, { toFile } from 'caesar-data'; const client = new Caesar(); // If you have access to Node `fs` we recommend using `fs.createReadStream()`: await client.research.files.create({ file: fs.createReadStream('/path/to/file') }); // Or if you have the web `File` API you can pass a `File` instance: await client.research.files.create({ file: new File(['my bytes'], 'file') }); // You can also pass a `fetch` `Response`: await client.research.files.create({ file: await fetch('https://somesite/file') }); // Finally, if none of the above are convenient, you can use our `toFile` helper: await client.research.files.create({ file: await toFile(Buffer.from('my bytes'), 'file') }); await client.research.files.create({ file: await toFile(new Uint8Array([0, 1, 2]), 'file') }); ``` -------------------------------- ### Auto-pagination Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to iterate through all items across paginated API results using `for await...of` or by manually fetching pages. ```APIDOC ## Auto-pagination List methods in the Caesar API are paginated. You can use the `for await … of` syntax to iterate through items across all pages: ```ts async function fetchAllResearchListResponses(params) { const allResearchListResponses = []; // Automatically fetches more pages as needed. for await (const researchListResponse of client.research.list({ limit: 30, page: 2 })) { allResearchListResponses.push(researchListResponse); } return allResearchListResponses; } ``` Alternatively, you can request a single page at a time: ```ts let page = await client.research.list({ limit: 30, page: 2 }); for (const researchListResponse of page.data) { console.log(researchListResponse); } // Convenience methods are provided for manually paginating: while (page.hasNextPage()) { page = await page.getNextPage(); // ... } ``` ``` -------------------------------- ### Configure MCP Server for Cursor Client with Custom Tool Name Length Source: https://github.com/caesar-data/typescript-sdk/blob/main/packages/mcp-server/README.md Command-line arguments to set the MCP client to 'cursor' and customize the maximum tool name length. This is useful for clients with specific limitations. ```bash --client=cursor --capability=tool-name-length=40 ``` -------------------------------- ### Iterate Through All Paginated Research List Responses (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to use the `for await...of` syntax to automatically fetch and iterate through all items across multiple pages of research list responses. This is useful for retrieving complete datasets without manual pagination handling. ```typescript async function fetchAllResearchListResponses(params) { const allResearchListResponses = []; // Automatically fetches more pages as needed. for await (const researchListResponse of client.research.list({ limit: 30, page: 2 })) { allResearchListResponses.push(researchListResponse); } return allResearchListResponses; } ``` -------------------------------- ### Handling API Errors with Caesar SDK Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to catch and handle `APIError` subclasses thrown by the Caesar SDK when the API returns non-success status codes or connection issues occur. It shows how to inspect error properties like status, name, and headers. ```ts const research = await client.research.create({ query: 'REPLACE_ME' }).catch(async (err) => { if (err instanceof Caesar.APIError) { console.log(err.status); // 400 console.log(err.name); // BadRequestError console.log(err.headers); // {server: 'nginx', ...} } else { throw err; } }); ``` -------------------------------- ### Research File Creation API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Creates a new file associated with a research project. ```APIDOC ## POST /research/files ### Description Creates a new file associated with a research project. ### Method POST ### Endpoint /research/files ### Parameters #### Request Body - **params** (object) - Required - Parameters for file creation. ### Request Example ```json { "params": { ... } } ``` ### Response #### Success Response (200) - **FileCreateResponse** (object) - Details of the created file. #### Response Example ```json { "FileCreateResponse": { ... } } ``` ``` -------------------------------- ### Configure Client Logging Level (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to configure the logging level for the Caesar client using the `logLevel` option. This allows developers to control the verbosity of log messages, from detailed debug information to only critical errors. ```typescript import Caesar from 'caesar-data'; const client = new Caesar({ logLevel: 'debug', // Show all log messages }); ``` -------------------------------- ### Research Listing API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Lists research projects, with optional parameters for filtering and pagination. ```APIDOC ## GET /research ### Description Lists research projects, with optional parameters for filtering and pagination. ### Method GET ### Endpoint /research ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **ResearchListResponsesPagination** (object) - A paginated list of research projects. #### Response Example ```json { "ResearchListResponsesPagination": { ... } } ``` ``` -------------------------------- ### Configuring Request Timeouts for Caesar SDK Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Illustrates how to set the `timeout` option for requests made with the Caesar SDK. This can be configured globally when initializing the client or overridden for individual requests. Timeouts are measured in milliseconds. ```ts // Configure the default for all requests: const client = new Caesar({ timeout: 20 * 1000, // 20 seconds (default is 1 minute) }); // Override per-request: await client.research.create({ query: 'REPLACE_ME' }, { timeout: 5 * 1000, }); ``` -------------------------------- ### Accessing Raw Response Data Source: https://context7.com/caesar-data/typescript-sdk/llms.txt This section details how to access raw HTTP response headers and metadata using the `asResponse()` and `withResponse()` methods. ```APIDOC ## POST /research/create ### Description Submit a research query and access raw HTTP response data. ### Method POST ### Endpoint /research/create ### Parameters #### Request Body - **query** (string) - Required - The research query to submit. ### Request Example ```json { "query": "Sample query" } ``` ### Response #### Success Response (200) - **id** (string) - The ID of the created research job. - **status** (number) - The HTTP status code of the response. - **statusText** (string) - The status text of the response. - **headers** (Headers) - The raw response headers. #### Response Example ```json { "id": "research_12345", "status": 200, "statusText": "OK", "headers": { "content-type": "application/json", "x-custom-header": "some-value", "x-ratelimit-remaining": "100" } } ``` ``` -------------------------------- ### Using TypeScript Types for Research Creation Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to use TypeScript definitions for request parameters and response fields when creating a research object. This enhances type safety and provides better developer experience with editor autocompletion. ```ts import Caesar from 'caesar-data'; const client = new Caesar({ apiKey: process.env['CAESAR_API_KEY'], // This is the default and can be omitted }); const params: Caesar.ResearchCreateParams = { query: 'REPLACE_ME' }; const research: Caesar.ResearchCreateResponse = await client.research.create(params); ``` -------------------------------- ### Research File Listing API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Lists files associated with a research project, with optional parameters for filtering and pagination. ```APIDOC ## GET /research/files ### Description Lists files associated with a research project, with optional parameters for filtering and pagination. ### Method GET ### Endpoint /research/files ### Parameters #### Query Parameters - **params** (object) - Optional - Parameters for filtering and pagination. ### Response #### Success Response (200) - **FileListResponsesPagination** (object) - A paginated list of files. #### Response Example ```json { "FileListResponsesPagination": { ... } } ``` ``` -------------------------------- ### Manually Paginate Through Research List Responses (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Illustrates how to manually paginate through research list responses by fetching one page at a time and using convenience methods like `hasNextPage()` and `getNextPage()` to control the iteration. This provides more granular control over the pagination process. ```typescript let page = await client.research.list({ limit: 30, page: 2 }); for (const researchListResponse of page.data) { console.log(researchListResponse); } // Convenience methods are provided for manually paginating: while (page.hasNextPage()) { page = await page.getNextPage(); // ... } ``` -------------------------------- ### Robust Error Handling for Research Queries with TypeScript Source: https://context7.com/caesar-data/typescript-sdk/llms.txt Demonstrates comprehensive error handling for research queries using the Caesar SDK, including specific typed error classes for various HTTP status codes and connection issues. This function handles errors from BadRequestError to APIConnectionError. ```typescript import Caesar from 'caesar-data'; const client = new Caesar(); async function robustResearchQuery(query: string) { try { const research = await client.research.create({ query }); return research; } catch (error) { // Handle specific error types if (error instanceof Caesar.BadRequestError) { console.error('Invalid request (400):', error.message); console.error('Status:', error.status); console.error('Headers:', error.headers); } else if (error instanceof Caesar.AuthenticationError) { console.error('Authentication failed (401):', error.message); } else if (error instanceof Caesar.PermissionDeniedError) { console.error('Permission denied (403):', error.message); } else if (error instanceof Caesar.NotFoundError) { console.error('Resource not found (404):', error.message); } else if (error instanceof Caesar.UnprocessableEntityError) { console.error('Unprocessable entity (422):', error.message); } else if (error instanceof Caesar.RateLimitError) { console.error('Rate limit exceeded (429):', error.message); // Implement backoff strategy } else if (error instanceof Caesar.InternalServerError) { console.error('Server error (500+):', error.message); } else if (error instanceof Caesar.APIConnectionTimeoutError) { console.error('Request timed out'); } else if (error instanceof Caesar.APIConnectionError) { console.error('Connection failed:', error.message); } else if (error instanceof Caesar.APIError) { console.error('API error:', error.status, error.message); } else { console.error('Unexpected error:', error); } throw error; } } robustResearchQuery('What are the latest trends in renewable energy?'); ``` -------------------------------- ### Accessing Raw Response Data Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Explains how to access the raw `Response` object, including headers and status, using `.asResponse()` or `.withResponse()` methods. ```APIDOC ## Accessing raw Response data (e.g., headers) The "raw" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return. This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic. You can also use the `.withResponse()` method to get the raw `Response` along with the parsed data. Unlike `.asResponse()` this method consumes the body, returning once it is parsed. ```ts const client = new Caesar(); const response = await client.research.create({ query: 'REPLACE_ME' }).asResponse(); console.log(response.headers.get('X-My-Header')); console.log(response.statusText); // access the underlying Response object const { data: research, response: raw } = await client.research .create({ query: 'REPLACE_ME' }) .withResponse(); console.log(raw.headers.get('X-My-Header')); console.log(research.id); ``` ``` -------------------------------- ### Make Undocumented POST Request (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Shows how to make POST requests to undocumented API endpoints using `client.post()`. This method allows sending custom request bodies and query parameters, enabling interaction with non-public API functionalities while respecting client-level configurations like retries. ```typescript await client.post('/some/path', { body: { some_prop: 'foo' }, query: { some_query_arg: 'bar' }, }); ``` -------------------------------- ### Include Undocumented Parameter in Research Create Request (TypeScript) Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Demonstrates how to include undocumented parameters in SDK method calls, such as `client.research.create()`, using the `// @ts-expect-error` directive. This allows sending extra, non-type-checked values that will be included in the request body or query parameters. ```typescript client.research.create({ // ... // @ts-expect-error baz is not yet public baz: 'undocumented option', }); ``` -------------------------------- ### Configuring Automatic Retries for API Requests Source: https://github.com/caesar-data/typescript-sdk/blob/main/README.md Explains how to configure the `maxRetries` option for the Caesar client to control automatic retries for certain API errors. This can be set globally during client initialization or per-request. ```js // Configure the default for all requests: const client = new Caesar({ maxRetries: 0, // default is 2 }); // Or, configure per-request: await client.research.create({ query: 'REPLACE_ME' }, { maxRetries: 5, }); ``` -------------------------------- ### Research Retrieval API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Retrieves a specific research project by its ID. ```APIDOC ## GET /research/{id} ### Description Retrieves a specific research project by its ID. ### Method GET ### Endpoint /research/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the research project. ### Response #### Success Response (200) - **ResearchRetrieveResponse** (object) - Details of the requested research project. #### Response Example ```json { "ResearchRetrieveResponse": { ... } } ``` ``` -------------------------------- ### Research Result Content Retrieval API Source: https://github.com/caesar-data/typescript-sdk/blob/main/api.md Retrieves the content of a specific research result. ```APIDOC ## GET /research/{id}/results/{resultId}/content ### Description Retrieves the content of a specific research result. ### Method GET ### Endpoint /research/{id}/results/{resultId}/content ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the research project. - **resultId** (string) - Required - The unique identifier of the result. #### Query Parameters - **params** (object) - Optional - Additional parameters for content retrieval. ### Response #### Success Response (200) - **ResultRetrieveContentResponse** (object) - The content of the research result. #### Response Example ```json { "ResultRetrieveContentResponse": { ... } } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.