### Install Project Dependencies Source: https://github.com/corticph/corti-sdk-javascript/blob/master/CONTRIBUTING.md Run this command to install all necessary project dependencies using pnpm. ```bash pnpm install ``` -------------------------------- ### Install Corti SDK Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Install the Corti JavaScript SDK using npm. ```sh npm i -s @corti/sdk ``` -------------------------------- ### Example: Get Interaction with Request Options Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/02-interactions-api.md Demonstrates how to retrieve a specific interaction using its ID and applying custom request options like timeout and headers. ```typescript const interaction = await client.interactions.get("int_abc123", { timeoutInSeconds: 30, headers: { "X-Custom-Header": "value" } }); ``` -------------------------------- ### Client Credentials Flow Setup Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/07-auth-api.md Use this flow for server-to-server authentication. The SDK automatically manages token refresh. ```typescript const client = new CortiClient({ tenantName: "your-tenant", environment: "us", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" } }); // SDK automatically manages token refresh const result = await client.interactions.list(); ``` -------------------------------- ### Example: Using Request Options Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/09-errors-request-options.md Demonstrates how to use request options like timeout, custom headers, and max retries when fetching an interaction. ```typescript const interaction = await client.interactions.get("int_abc123", { timeoutInSeconds: 30, headers: { "X-Request-ID": "req_123", "X-Custom-Header": "value" }, maxRetries: 1 }); ``` -------------------------------- ### Example: Create Interaction with Abort Signal Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/02-interactions-api.md Shows how to create an interaction and attach an AbortSignal to the request for cancellation capabilities. ```typescript // With abort signal const controller = new AbortController(); const promise = client.interactions.create({...}, { abortSignal: controller.signal }); controller.abort(); // Cancel the request ``` -------------------------------- ### Save Binary Response to File (Deno) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Examples for saving binary responses to a file in Deno using different consumption methods. ```typescript const response = await client.recordings.get(...); const stream = response.stream(); const file = await Deno.open('path/to/file', { write: true, create: true }); await stream.pipeTo(file.writable); ``` ```typescript const response = await client.recordings.get(...); const arrayBuffer = await response.arrayBuffer(); await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer)); ``` ```typescript const response = await client.recordings.get(...); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); await Deno.writeFile('path/to/file', new Uint8Array(arrayBuffer)); ``` ```typescript const response = await client.recordings.get(...); const bytes = await response.bytes(); await Deno.writeFile('path/to/file', bytes); ``` -------------------------------- ### Audio Streaming Example Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/08-streaming-api.md Demonstrates establishing a WebSocket connection for audio streaming, sending audio chunks, and handling incoming transcript, analysis, status, and error events. ```typescript // Establish connection const ws = await client.stream.connect({ config: { format: "pcm", sampleRate: 16000 }, interaction: "int_abc123" }); // Send audio stream const audioStream = fs.createReadStream("audio.pcm"); audioStream.on("data", (chunk) => { ws.send(JSON.stringify({ type: "audio", data: chunk.toString("base64") })); }); // Receive stream events ws.on("message", (message) => { const event = JSON.parse(message.toString()); switch (event.type) { case "transcript": console.log(`Transcript: ${event.content}`); break; case "analysis": console.log(`Analysis: ${event.content}`); break; case "status": console.log(`Status: ${event.content}`); break; case "error": console.error(`Error: ${event.error.message}`); break; } }); ws.on("close", () => { console.log("Stream closed"); }); ``` -------------------------------- ### Bidirectional Chat Example Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/08-streaming-api.md Shows how to establish a WebSocket connection for chat, send a message, receive a response, and send a control command to stop the stream. ```typescript const ws = await client.stream.connect({ config: { model: "chat" } }); // Send message ws.send(JSON.stringify({ type: "message", content: "What are the key findings from the recording?" })); // Receive response ws.on("message", (message) => { const event = JSON.parse(message.toString()); if (event.type === "message") { console.log(`Response: ${event.content}`); } }); // Stop stream ws.send(JSON.stringify({ type: "control", action: "stop" })); ``` -------------------------------- ### Initialize Corti Client and Access Interactions Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/02-interactions-api.md Instantiate the CortiClient and get access to the interactions API module. ```typescript const client = new CortiClient({ ... }); const interactions = client.interactions; ``` -------------------------------- ### Save Binary Response to File (Bun) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Examples for saving binary responses to a file in Bun using different consumption methods. ```typescript const response = await client.recordings.get(...); const stream = response.stream(); await Bun.write('path/to/file', stream); ``` ```typescript const response = await client.recordings.get(...); const arrayBuffer = await response.arrayBuffer(); await Bun.write('path/to/file', arrayBuffer); ``` ```typescript const response = await client.recordings.get(...); const blob = await response.blob(); await Bun.write('path/to/file', blob); ``` ```typescript const response = await client.recordings.get(...); const bytes = await response.bytes(); await Bun.write('path/to/file', bytes); ``` -------------------------------- ### Trigger File Download (Browser) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Example for triggering a file download in the browser using a Blob. This is generally the most efficient method for browser-based downloads. ```typescript const response = await client.recordings.get(...); const blob = await response.blob(); const url = URL.createObjectURL(blob); // trigger download const a = document.createElement('a'); a.href = url; a.download = 'filename'; a.click(); URL.revokeObjectURL(url); ``` -------------------------------- ### Create Transcript from Audio URL Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Create a new transcript by providing a URL to an audio file. This example specifies the audio source, language, and transcription model. ```typescript // From URL const transcript = await client.transcripts.create({ audio: { url: "https://example.com/audio.mp3", duration: 1800 }, language: "en", model: "medical" }); ``` -------------------------------- ### Save Binary Response to File (Node.js) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Examples for saving binary responses to a file in Node.js using different consumption methods. ```typescript import { createWriteStream } from 'fs'; import { Readable } from 'stream'; import { pipeline } from 'stream/promises'; const response = await client.recordings.get(...); const stream = response.stream(); const nodeStream = Readable.fromWeb(stream); const writeStream = createWriteStream('path/to/file'); await pipeline(nodeStream, writeStream); ``` ```typescript import { writeFile } from 'fs/promises'; const response = await client.recordings.get(...); const arrayBuffer = await response.arrayBuffer(); await writeFile('path/to/file', Buffer.from(arrayBuffer)); ``` ```typescript import { writeFile } from 'fs/promises'; const response = await client.recordings.get(...); const blob = await response.blob(); const arrayBuffer = await blob.arrayBuffer(); await writeFile('output.bin', Buffer.from(arrayBuffer)); ``` ```typescript import { writeFile } from 'fs/promises'; const response = await client.recordings.get(...); const bytes = await response.bytes(); await writeFile('path/to/file', bytes); ``` -------------------------------- ### get() Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/04-documents-templates-api.md Retrieves detailed information about a specific document template, including its sections and fields. ```APIDOC ## get(id: string) ### Description Retrieves template details including sections and fields. ### Method `get` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the template to retrieve. ### Request Example ```typescript const template = await client.documents.templates.get("standard_clinical_note"); console.log(template.name); console.log(template.sections.length); for (const section of template.sections) { console.log(`Section: ${section.title}`); console.log(`Fields: ${section.fields?.length ?? 0}`); } ``` ### Response #### Success Response Returns the details of a specific document template. #### DocumentsTemplate Structure ```typescript { id: string; name: string; description?: string; created: string; modified: string; sections?: Array<{ id: string; key: string; title: string; description?: string; instructions?: string; template?: string; position?: number; fields?: Array<{ key: string; label: string; type: "text" | "textarea" | "number" | "boolean" | "date" | "select" | "multiselect"; required?: boolean; default?: unknown; options?: Array<{ label: string; value: string; }>; }>; }>; metadata?: { category?: string; specialty?: string; version?: string; tags?: string[]; }; } ``` ``` -------------------------------- ### Chain Multiple Agents Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/06-agents-api.md Illustrates how to chain agents by using the output of one agent as the input for another. This example shows a documentation agent generating a note, which is then passed to a review agent for validation. ```typescript // 1. Documentation agent generates note const docAgent = await client.agents.get("agent_documentation"); const docResponse = await client.agents.sendMessage(docAgent.id, { messages: [ { role: "user", content: "Generate clinical note" } ], context: { items: [{ type: "transcript", id: "trx_abc123" }] } }); // 2. Review agent validates documentation const reviewAgent = await client.agents.get("agent_review"); const reviewResponse = await client.agents.sendMessage(reviewAgent.id, { messages: [ { role: "user", content: "Review the following documentation for completeness and accuracy", parts: [ { type: "text", text: docResponse.response.content } ] } ] }); console.log("Review feedback:", reviewResponse.response.content); ``` -------------------------------- ### Create and Use a Clinical Agent Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/06-agents-api.md Demonstrates the process of creating a new agent, retrieving relevant data like transcripts and facts, and sending a message to the agent with context. Ensure you have the necessary client setup and agent/transcript/fact IDs. ```typescript // 1. Create agent const agent = await client.agents.create({ name: "Cardiac Specialist Agent", description: "Expert in cardiac conditions", systemPrompt: "You are a cardiac specialist. Provide expert analysis on cardiac conditions.", experts: [ { id: "expert_cardiology", type: "expert" } ], capabilities: { canAccessTranscripts: true, canAccessDocuments: true, canAccessFacts: true } }); // 2. Get relevant transcript and facts const transcript = await client.transcripts.get("trx_abc123"); const facts = await client.facts.list({ interaction: "int_xyz789", group: "diagnosis" }); // 3. Send message with context const response = await client.agents.sendMessage(agent.id, { messages: [ { role: "user", content: "Please review this patient's cardiac assessment and provide recommendations" } ], context: { items: [ { type: "transcript", id: "trx_abc123" }, { type: "text", content: facts.items.map(f => `${f.group}: ${f.value}`).join("\n") } ] } }); console.log(response.response.content); ``` -------------------------------- ### Stream Audio from Microphone Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/08-streaming-api.md Example for browser environments to capture audio from the microphone and stream it to the Transcribe API. Requires AudioContext and MediaDevices API. ```typescript // Stream audio from microphone (browser example) const audioContext = new AudioContext(); const mediaStream = await navigator.mediaDevices.getUserMedia({ audio: true }); const mediaStreamAudioSource = audioContext.createMediaStreamSource(mediaStream); const processor = audioContext.createScriptProcessor(4096, 1, 1); mediaStreamAudioSource.connect(processor); processor.connect(audioContext.destination); processor.onaudioprocess = (event) => { const audioData = event.inputBuffer.getChannelData(0); const buffer = new Float32Array(audioData); ws.send(JSON.stringify({ type: "audio", data: Array.from(buffer), isFinal: false })); }; ``` -------------------------------- ### get() Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieves recording metadata and content stream. It allows consuming the recording content as a stream, ArrayBuffer, Blob, or typed array. ```APIDOC ## get() [Method] ### Description Retrieves recording metadata and content stream. It allows consuming the recording content as a stream, ArrayBuffer, Blob, or typed array. ### Method `get(id: string, requestOptions?: RecordingsClient.RequestOptions): core.HttpResponsePromise` ### Parameters #### Path Parameters - **id** (string) - Required - Recording ID - **requestOptions** (RecordingsClient.RequestOptions) - Optional - Request configuration ### Response #### Success Response - **BinaryResponse** - Object with multiple consumption methods (`stream()`, `arrayBuffer()`, `blob()`, `bytes()`). ### Response Example ```json { "bodyUsed": false, "stream": () => ReadableStream, "arrayBuffer": () => Promise, "blob": () => Blob, "bytes": () => Promise } ``` ### Example - Node.js Stream: ```typescript import { Readable } from "stream"; import { pipeline } from "stream/promises"; import { createWriteStream } from "fs"; const response = await client.recordings.get("rec_xyz789"); const stream = response.stream(); const nodeStream = Readable.fromWeb(stream); const writeStream = createWriteStream("output.mp3"); await pipeline(nodeStream, writeStream); ``` ### Example - Browser Download: ```typescript const response = await client.recordings.get("rec_xyz789"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "recording.mp3"; a.click(); URL.revokeObjectURL(url); ``` ### Example - Bun: ```typescript const response = await client.recordings.get("rec_xyz789"); const stream = response.stream(); await Bun.write("output.mp3", stream); ``` ``` -------------------------------- ### Get Recording as Browser Download Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieves a recording and prompts the user to download it as a file in a browser environment. Uses Blob and URL.createObjectURL for handling. ```typescript const response = await client.recordings.get("rec_xyz789"); const blob = await response.blob(); const url = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = url; a.download = "recording.mp3"; a.click(); URL.revokeObjectURL(url); ``` -------------------------------- ### Create Transcript from Recording Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Create a new transcript by providing a recording ID. This example demonstrates setting transcription options like language, model, speaker identification, and keyterms. ```typescript // From recording const transcript = await client.transcripts.create({ recording: "rec_abc123", interaction: "int_xyz789", language: "en", model: "medical", speakerIdentification: true, keyterms: { enabled: true, terms: [ { term: "hypertension", category: "condition" }, { term: "metformin", category: "medication" } ] } }); ``` -------------------------------- ### Hybrid Streaming + Batch Processing Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/11-advanced-patterns.md Use this pattern to get immediate live transcriptions while also performing a more thorough batch analysis. Ensure the CortiClient is initialized and the audio file and interaction ID are valid. ```typescript async function processWithLiveAndBatch( audioFile: string, interactionId: string ): Promise<{ liveTranscript: string; batchTranscript: string }> { const client = new CortiClient({ /* ... */ }); // Start live streaming for immediate feedback const ws = await client.transcribe.connect({ config: { language: "en", model: "medical" }, interaction: interactionId }); let liveTranscript = ""; ws.on("message", (message) => { const event = JSON.parse(message.toString()); if (event.segment?.isFinal) { liveTranscript += event.segment.text + " "; } }); // Concurrently upload for batch processing const recording = await client.recordings.upload(audioFile, { interaction: interactionId }); // Close stream after upload ws.close(); // Create batch transcript const batchTranscript = await client.transcripts.create({ recording: recording.id, language: "en", model: "medical" }); const completed = await waitForCompletion( () => client.transcripts.get(batchTranscript.id), (t) => t.status === "ready" ); return { liveTranscript: liveTranscript.trim(), batchTranscript: completed.content?.full || "" }; } ``` -------------------------------- ### Retrieve Environment URLs from CortiClient Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Call this method after initializing the client to get the specific URLs (base, wss, login, agents) it is configured to use. This is useful for debugging or understanding the client's network configuration. ```typescript const client = new CortiClient({ environment: "eu", ... }); const urls = await client.getEnvironmentUrls(); console.log(urls.base); // "https://api.eu.corti.app/v2" ``` -------------------------------- ### CortiClient Initialization with Environment Configuration Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Demonstrates initializing the CortiClient with environment configuration, supporting both string constants for predefined environments (US, EU) and a detailed `CortiEnvironmentUrls` object for custom configurations. ```APIDOC ## Client Initialization The `CortiClient` can be initialized with an `environment` configuration. This can be a string constant representing predefined environments or a `CortiEnvironmentUrls` object for custom configurations. ### Environment Configuration Options: **String Constants:** - `"us"`: Configures the client for the US environment. - `"eu"`: Configures the client for the EU environment. **`CortiEnvironmentUrls` Object:** This object allows for fine-grained control over the API endpoints: ```typescript { base: string; // Base API URL (e.g., https://api.corti.app/v2) wss: string; // WebSocket endpoint login: string; // OAuth token endpoint agents: string; // Agents API endpoint } ``` ### Example with Custom URLs: ```typescript const client = new CortiClient({ environment: { base: "https://custom.api.com/v2", wss: "wss://custom.api.com", login: "https://custom.auth.com", agents: "https://custom.agents.com" }, auth: { accessToken: "..." } }); ``` ### Example with String Constant: ```typescript const client = new CortiClient({ environment: "eu", auth: { accessToken: "..." } }); ``` ``` -------------------------------- ### Build the Project Source: https://github.com/corticph/corti-sdk-javascript/blob/master/CONTRIBUTING.md Execute this command to build the project. This is typically done after making code changes. ```bash pnpm build ``` -------------------------------- ### get() Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/06-agents-api.md Retrieves details of a specific agent by its ID. ```APIDOC ## get() ### Description Retrieves details of a specific agent. ### Method GET (assumed, based on SDK method name and common REST patterns) ### Endpoint `/agents/{id}` (inferred) ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the agent. #### Query Parameters None explicitly documented. #### Request Body None explicitly documented. ### Request Example ```typescript const agent = await client.agents.get("agent_abc123"); console.log(agent.name); console.log(agent.systemPrompt); ``` ### Response #### Success Response (200) - **Corti.AgentsAgent** - An object containing the agent's details. #### Response Example ```json { "name": "Example Agent", "systemPrompt": "You are a helpful assistant." } ``` ``` -------------------------------- ### Get Document Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/04-documents-templates-api.md Retrieves document details and content by its ID. ```APIDOC ## GET /documents/{id} ### Description Retrieves document details and content. ### Method GET ### Endpoint /documents/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the document. #### Request Example ```typescript const document = await client.documents.get("doc_abc123"); console.log(document.status); console.log(document.content.full); for (const section of document.content.sections) { console.log(`Section: ${section.key}`); console.log(`Confidence: ${section.confidence}`); } ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the document. - **interaction** (object) - Optional - Details about the interaction associated with the document. - **id** (string) - **template** (object) - Optional - Information about the template used for the document. - **id** (string) - **name** (string) - **status** (string) - The current status of the document generation ('draft', 'generating', 'ready', 'failed'). - **created** (string) - The creation timestamp of the document. - **modified** (string) - The last modification timestamp of the document. - **content** (object) - Optional - The content of the document. - **full** (string) - The complete document content. - **sections** (array) - An array of document sections. - **key** (string) - **title** (string) - Optional - **content** (string) - **confidence** (number) - Optional - Generation confidence score (0.0-1.0). - **references** (array) - Optional - References used for the section. - **source** (string) - Source of the reference ('transcript', 'facts', 'document'). - **id** (string) - **excerpt** (string) - Optional - **metadata** (object) - Optional - Metadata associated with the document. - **title** (string) - Optional - **author** (string) - Optional - **date** (string) - Optional - **wordCount** (number) - Optional - **characterCount** (number) - Optional - **error** (object) - Optional - Error details if document generation failed. - **code** (string) - **message** (string) #### Response Example ```json { "id": "doc_abc123", "status": "ready", "created": "2023-01-01T10:00:00Z", "modified": "2023-01-01T10:05:00Z", "content": { "full": "This is the full document content.", "sections": [ { "key": "introduction", "content": "Introduction section.", "confidence": 0.95, "references": [ { "source": "transcript", "id": "trx_xyz789" } ] } ] }, "metadata": { "title": "Sample Document" } } ``` ``` -------------------------------- ### get() Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/02-interactions-api.md Retrieves details of a specific interaction using its ID. ```APIDOC ## get() ### Description Retrieves details of a specific interaction. ### Method `get` ### Parameters #### Path Parameters - **id** (Uuid) - Required - Interaction ID - **requestOptions** (RequestOptions) - Optional - Request-specific configuration ### Returns `InteractionsGetResponse` with complete interaction details. ### Throws - `BadRequestError` (400) — Invalid ID format - `NotFoundError` (404) — Interaction does not exist - `ForbiddenError` (403) — Insufficient permissions ### Example ```typescript const interaction = await client.interactions.get("int_abc123"); console.log(interaction.id); console.log(interaction.encounter.status); console.log(interaction.created); console.log(interaction.modified); ``` ``` -------------------------------- ### Initialize Corti Client and Create Interaction Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/00-index.md Demonstrates how to initialize the CortiClient with authentication details and create a new interaction. Ensure you replace placeholder values with your actual tenant, environment, client ID, and client secret. ```typescript import { CortiClient } from "@corti/sdk"; const client = new CortiClient({ tenantName: "your-tenant", environment: "us", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" } }); // Create an interaction const interaction = await client.interactions.create({ encounter: { identifier: "encounter_001", status: "completed", type: "first_consultation" } }); console.log(interaction.id); ``` -------------------------------- ### Initialize CortiClient with PKCE Flow Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Initialize the CortiClient for the PKCE flow, including tenant name, environment ID, client ID, authorization code, redirect URI, and code verifier. ```typescript const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", code: "AUTH_CODE", redirectUri: "YOUR_REDIRECT_URI", codeVerifier: "YOUR_CODE_VERIFIER", }, }); ``` -------------------------------- ### Initialize CortiClient or CortiAuth Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/07-auth-api.md Instantiate the CortiClient to access authentication services or directly create a CortiAuth instance with environment and tenant details. ```typescript const client = new CortiClient({ ... }); const auth = client.auth; // Or directly const auth = new CortiAuth({ environment: "us", tenantName: "your-tenant" }); ``` -------------------------------- ### Initialize CortiClient with Client Credentials Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Instantiate the CortiClient using tenant name, environment ID, and client credentials for server-side applications. ```typescript import { CortiClient } from "@corti/sdk"; const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" }, }); await client.interactions.create({ encounter: { identifier: "identifier", status: "planned", type: "first_consultation" } }); ``` -------------------------------- ### get() Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieves transcript details and content, including full text, segmented content with speaker information, and metadata. ```APIDOC ## get() ### Description Retrieves transcript details and content, including full text, segmented content with speaker information, and metadata. ### Method GET ### Endpoint /v1/transcripts/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the transcript to retrieve. ### Response #### Success Response (200) - **transcript** (Corti.TranscriptsGetResponse) - Full transcript with segments and metadata. ### Response Example ```json { "id": "trx_abc123", "recording": { "id": "rec_abc123" }, "interaction": { "id": "int_xyz789" }, "language": "en", "model": "medical", "status": "ready", "created": "2023-01-01T10:00:00Z", "modified": "2023-01-01T10:05:00Z", "content": { "full": "This is the full transcript text.", "segments": [ { "id": "seg_1", "text": "Hello, how are you?", "speaker": "speaker_1", "startTime": 1000, "endTime": 3000, "confidence": 0.95 } ] }, "metadata": { "duration": 300, "speakers": 2, "language": "en", "words": 50 }, "keyterms": [ { "term": "hypertension", "category": "condition", "occurrences": 5, "confidence": 0.88 } ] } ``` ``` -------------------------------- ### Main SDK Export Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/00-index.md Import the main client and authentication classes from the SDK. ```typescript import { CortiClient, Corti, CortiAuth } from "@corti/sdk"; ``` -------------------------------- ### Access Transcripts API Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Get access to the Transcripts API client. This is typically the first step before calling any transcript-related methods. ```typescript const transcripts = client.transcripts; ``` -------------------------------- ### Bearer Token with Refresh Initialization Example Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Initialize the CortiClient with an access token and refresh token for automatic token refreshing. ```typescript const client = new CortiClient({ auth: { accessToken: "eyJ...", refreshToken: "refresh_token_value", clientId: "YOUR_CLIENT_ID", expiresIn: 300, refreshExpiresIn: 1800 } }); ``` -------------------------------- ### Upload Recording and Generate Transcript Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md This workflow demonstrates how to upload an audio recording, create a transcript for it, and then poll for the transcript's completion. It also shows how to configure language, model, speaker identification, and key terms for the transcription. ```APIDOC ## Upload Recording and Generate Transcript ### Description Uploads an audio recording and initiates a transcript generation process. The process includes options for language, model selection, speaker identification, and custom key term extraction. ### Methods - `client.recordings.upload(stream, options)`: Uploads an audio recording. - `client.transcripts.create(options)`: Creates a transcript for a given recording. - `client.transcripts.get(id)`: Retrieves the status and content of a transcript. ### Parameters #### `client.recordings.upload` - **stream** (ReadableStream) - Required - The audio recording stream to upload. - **options** (object) - Optional - Additional options, such as `interaction` ID. - **interaction** (string) - Optional - The ID of the interaction associated with the recording. #### `client.transcripts.create` - **options** (object) - Required - Configuration for the transcript. - **recording** (string) - Required - The ID of the recording to transcribe. - **language** (string) - Required - The language of the audio (e.g., "en"). - **model** (string) - Required - The transcription model to use (e.g., "medical"). - **speakerIdentification** (boolean) - Optional - Whether to enable speaker identification. - **keyterms** (object) - Optional - Configuration for key term extraction. - **enabled** (boolean) - Required - Whether to enable key term extraction. - **terms** (array) - Required - A list of key terms to extract. - **term** (string) - Required - The key term. - **category** (string) - Required - The category of the key term. #### `client.transcripts.get` - **id** (string) - Required - The ID of the transcript to retrieve. ### Response Example (Transcript Status) ```json { "id": "trx_abc123", "status": "ready", "content": { "full": "The full transcribed text...", "segments": [ { "speaker": "Doctor", "text": "Patient reports symptoms.", "confidence": 0.98 } ] } } ``` ``` -------------------------------- ### Full Environment URLs Options Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Configure the client using explicit Corti environment URLs. ```typescript { environment: CortiEnvironmentUrls; auth?: Auth; tenantName?: string; } ``` -------------------------------- ### Generate Document Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/04-documents-templates-api.md Generates a document using a guided schema and dynamic assembly. Supports template-based, assembly-based, and dynamic generation approaches. ```APIDOC ## POST /documents/generate ### Description Generates a document using guided schema and dynamic assembly. ### Method POST ### Endpoint /documents/generate ### Parameters #### Request Body - **approach** (string) - Required - The generation approach ('template_ref', 'assembly', 'dynamic'). - **templateRef** (object) - Required if approach is 'template_ref' - Configuration for template-based generation. - **templateId** (string) - Required - The ID of the template to use. - **interaction** (string) - Optional - The ID of the interaction to associate with the document. - **context** (object) - Optional - Contextual data for generation. - **transcript** (object) - Optional - Transcript context. - **id** (string) - Required - **startTime** (number) - Optional - **endTime** (number) - Optional - **facts** (object) - Optional - Facts context. - **id** (string) - Required - **groups** (array) - Optional - Specific groups of facts to include. - **documents** (array) - Optional - Document context. - **id** (string) - Required - **sections** (array) - Optional - Specific sections from the document. - **overrides** (object) - Optional - Overrides for guided sections. - **assembly** (object) - Required if approach is 'assembly' - Configuration for assembly-based generation. - **sections** (array) - Required - An array of sections to assemble. - **templateId** (string) - Required - The ID of the template for the section. - **sectionId** (string) - Required - The ID of the section within the template. - **context** (object) - Optional - Contextual data for the section. - **overrides** (object) - Optional - Overrides for the guided section. - **dynamic** (object) - Required if approach is 'dynamic' - Configuration for dynamic generation. - **schema** (object) - Required - The schema defining the dynamic output. - **context** (object) - Optional - Contextual data for generation. - **instructions** (string) - Optional - Instructions for dynamic generation. - **ephemeral** (boolean) - Optional - If true, the document is not persisted. - **streaming** (boolean) - Optional - If true, generation progress is streamed. ### Request Example - Template Ref ```typescript const generated = await client.documents.generate({ approach: "template_ref", ephemeral: false, templateRef: { templateId: "standard_clinical_note", interaction: "int_abc123", context: { transcript: { id: "trx_xyz789" } } } }); ``` ### Response #### Success Response (200) - **id** (string) - The unique identifier of the generated document. - **interaction** (object) - Optional - Details about the interaction associated with the document. - **id** (string) - **template** (object) - Optional - Information about the template used for the document. - **id** (string) - **name** (string) - **status** (string) - The current status of the document generation ('draft', 'generating', 'ready', 'failed'). - **created** (string) - The creation timestamp of the document. - **modified** (string) - The last modification timestamp of the document. - **content** (object) - Optional - The content of the document. - **full** (string) - The complete document content. - **sections** (array) - An array of document sections. - **key** (string) - **title** (string) - Optional - **content** (string) - **confidence** (number) - Optional - Generation confidence score (0.0-1.0). - **references** (array) - Optional - References used for the section. - **source** (string) - Source of the reference ('transcript', 'facts', 'document'). - **id** (string) - **excerpt** (string) - Optional - **metadata** (object) - Optional - Metadata associated with the document. - **title** (string) - Optional - **author** (string) - Optional - **date** (string) - Optional - **wordCount** (number) - Optional - **characterCount** (number) - Optional - **error** (object) - Optional - Error details if document generation failed. - **code** (string) - **message** (string) #### Response Example ```json { "id": "doc_generated_xyz", "status": "generating", "created": "2023-01-01T12:00:00Z", "modified": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### Check Code Style Source: https://github.com/corticph/corti-sdk-javascript/blob/master/CONTRIBUTING.md Run these commands to check the code style and formatting of the project. ```bash pnpm run lint ``` ```bash pnpm run format:check ``` -------------------------------- ### Initialize CortiClient with Authorization Code Flow Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Initialize the CortiClient for the Authorization Code flow, providing tenant name, environment ID, client ID, client secret, authorization code, and redirect URI. ```typescript const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET", code: "AUTH_CODE", redirectUri: "YOUR_REDIRECT_URI", }, }); ``` -------------------------------- ### Initialize CortiClient and Access Facts API Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/05-facts-codes-api.md Instantiate the CortiClient and obtain a reference to the facts API. ```typescript const client = new CortiClient({ ... }); const facts = client.facts; ``` -------------------------------- ### Initialize CortiClient with Resource Owner Password Credentials Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Initialize the CortiClient using the Resource Owner Password Credentials (ROPC) flow, requiring tenant name, environment ID, client ID, username, and password. ```typescript const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", username: "USERNAME", password: "PASSWORD" }, }); ``` -------------------------------- ### Get Recording as Bun Stream Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieves a recording and writes its stream content directly to a file using Bun.write. This is suitable for Bun runtime environments. ```typescript const response = await client.recordings.get("rec_xyz789"); const stream = response.stream(); await Bun.write("output.mp3", stream); ``` -------------------------------- ### Get Recording as Node.js Stream Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieves a recording and consumes its content as a Node.js stream, saving it to a file. Ensure 'stream' and 'fs' modules are imported. ```typescript import { Readable } from "stream"; import { pipeline } from "stream/promises"; import { createWriteStream } from "fs"; const response = await client.recordings.get("rec_xyz789"); const stream = response.stream(); const nodeStream = Readable.fromWeb(stream); const writeStream = createWriteStream("output.mp3"); await pipeline(nodeStream, writeStream); ``` -------------------------------- ### Agent Creation Parameters Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/10-types-enums.md Defines the structure for creating a new agent. Includes fields for name, description, type, system prompt, model configuration, expert definitions, MCP server configurations, capabilities, and metadata. ```typescript { name: string; description?: string; type?: "expert" | "tool" | "workflow" | "custom"; systemPrompt?: string; model?: string; temperature?: number; maxTokens?: number; experts?: Array<{ id: string; name?: string; description?: string; type: "expert" | "agent" | "tool"; }>; mcpServers?: Array<{ name: string; description?: string; transport: "stdio" | "sse"; authorization?: { type: "api_key" | "oauth" | "bearer"; credentials?: Record; }; command?: string; url?: string; }>; capabilities?: { canAccessDocuments?: boolean; canAccessFacts?: boolean; canAccessTranscripts?: boolean; canExecuteTools?: boolean; canAccessInteractions?: boolean; }; ephemeral?: boolean; tags?: string[]; metadata?: Record; } ``` -------------------------------- ### Utilities Module Import Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/00-index.md Import utility functions from the SDK. ```typescript import { /* utilities */ } from "@corti/sdk/utils"; ``` -------------------------------- ### Read Binary Response Stream (Browser) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Example for reading a binary response as a stream in the browser. This involves using a stream reader to process chunks of data. ```typescript const response = await client.recordings.get(...); const stream = response.stream(); const reader = stream.getReader(); const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) break; ``` -------------------------------- ### Get Transcript Details and Content Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/03-recordings-transcripts-api.md Retrieve a specific transcript by its ID. The response includes full text, segments with timestamps and speaker information, metadata, and extracted keyterms. ```typescript const transcript = await client.transcripts.get("trx_abc123"); console.log(transcript.content.full); // Full transcript console.log(transcript.metadata.duration); console.log(transcript.keyterms); // Process segments for (const segment of transcript.content.segments) { console.log(`[${segment.speaker}] ${segment.text}`); } ``` -------------------------------- ### Create and Process an Interaction Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/02-interactions-api.md This snippet demonstrates the common workflow for creating an interaction, uploading a recording, creating a transcript, extracting facts, generating a document, and updating the interaction status. ```typescript // 1. Create an interaction const interaction = await client.interactions.create({ encounter: { identifier: "encounter_001", status: "in-progress", type: "first_consultation" } }); // 2. Upload recording and transcript const recording = await client.recordings.upload(fileStream); const transcript = await client.transcripts.create({ recording: recording.id, language: "en" }); // 3. Extract facts and generate document const facts = await client.facts.extract({ transcript: transcript.id }); const document = await client.documents.create({ template: "standard", interaction: interaction.id }); // 4. Update interaction status await client.interactions.update(interaction.id, { encounter: { status: "completed" } }); // 5. Retrieve final state const final = await client.interactions.get(interaction.id); ``` -------------------------------- ### Initialize CortiClient with Client Credentials (Authentication) Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Initialize the CortiClient for server-side applications using client credentials. The SDK automatically handles token fetching and refreshing. ```typescript import { CortiClient } from "@corti/sdk"; const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" }, }); ``` -------------------------------- ### Retrieve Document Details and Content Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/04-documents-templates-api.md Use the `get` method to fetch a document's status, content, and metadata. Access the full content via `document.content.full` or iterate through sections. ```typescript const document = await client.documents.get("doc_abc123"); console.log(document.status); console.log(document.content.full); for (const section of document.content.sections) { console.log(`Section: ${section.key}`); console.log(`Confidence: ${section.confidence}`); } ``` -------------------------------- ### Pagination and Iteration Source: https://github.com/corticph/corti-sdk-javascript/blob/master/README.md Demonstrates how to iterate over paginated list endpoints using async iterators or manual page-by-page fetching. ```APIDOC ## Pagination List endpoints are paginated. The SDK provides an iterator so that you can simply loop over the items: ```typescript import { CortiClient } from "@corti/sdk"; const client = new CortiClient({ tenantName: "YOUR_TENANT_NAME", environment: "YOUR_ENVIRONMENT_ID", auth: { clientId: "YOUR_CLIENT_ID", clientSecret: "YOUR_CLIENT_SECRET" }, }); const pageableResponse = await client.interactions.list(); for await (const item of pageableResponse) { console.log(item); } // Or you can manually iterate page-by-page let page = await client.interactions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } // You can also access the underlying response const response = page.response; ``` ``` -------------------------------- ### Get Access Token using Resource Owner Password Credentials Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/07-auth-api.md Use `getRopcFlowToken` to obtain an access token by providing a username and password. This flow is less secure and should be used with caution. ```typescript const response = await auth.getRopcFlowToken({ clientId: "YOUR_CLIENT_ID", username: "user@example.com", password: "password123", scopes: ["profile"] }); console.log(response.accessToken); ``` -------------------------------- ### Logging Initialization Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/00-index.md Import and initialize the console logger for SDK events. ```typescript import { logging } from "@corti/sdk"; const logger = new logging.ConsoleLogger(); ``` -------------------------------- ### Initialize CortiClient with Custom Environment URLs Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Use this snippet to initialize the CortiClient when you need to connect to a custom API endpoint, WebSocket server, login service, and agents endpoint. Ensure you provide a valid access token for authentication. ```typescript const client = new CortiClient({ environment: { base: "https://custom.api.com/v2", wss: "wss://custom.api.com", login: "https://custom.auth.com", agents: "https://custom.agents.com" }, auth: { accessToken: "..." } }); ``` -------------------------------- ### Import CortiClient Source: https://github.com/corticph/corti-sdk-javascript/blob/master/_autodocs/01-client-initialization.md Import the CortiClient class from the SDK. ```typescript import { CortiClient } from "@corti/sdk"; ```