> ## Documentation Index
> Fetch the complete documentation index at: https://getalchemystai.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Typescript SDK

> Get started with the Alchemyst Typescript SDK

### Installation

<CodeGroup>
  ```bash Npm theme={null}
    npm install @alchemystai/sdk
  ```

  ```bash Yarn theme={null}
    yarn add @alchemystai/sdk
  ```

  ```bash Pnpm theme={null}
    pnpm add @alchemystai/sdk
  ```

  ```bash Bun theme={null}
    bun add @alchemystai/sdk
  ```
</CodeGroup>

### Authentication

Set your API key via environment variable or pass it directly when initializing the client.

* Recommended env var: `ALCHEMYST_AI_API_KEY`

```bash theme={null}
export ALCHEMYST_AI_API_KEY="your_api_key_here"
```

### Quickstart

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
    apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

async function main() {
  const res = await client.v1.context.view.retrieve();
  console.log(res);
}

main().catch(console.error);
```

### Usage by Endpoint

All methods return a promise you can `await`. Types are available out-of-the-box in TypeScript.

#### Context: Add

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
    apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
    await client.v1.context.add({
       // [REQUIRED] The actual data to embed
      documents: [
                {
                  content: 'The content of the document',
                },
              ],
              // [REQUIRED] System classifications
              context_type: 'resource',
              source: 'web-upload',
              scope: 'internal',

              // [OPTIONAL] Can be null. Use for filtering later.
              metadata: {
                fileName: 'notes.txt',
                fileType: 'text/plain',
                lastModified: new Date().toISOString(),
                fileSize: 1024,
                groupName: ['group1', 'group2'],
            },
    });
    console.log("Context successfully added.")
    
} catch (error) {
    //Handles validation error (eg. missing required fields like 'documents')
    console.error("Error adding context:", error)    
}
```

<Warning>
  **Version Requirements**: The `groupName` field is introduced in TypeScript SDK version 0.6.0. If you use `groupName` in previous versions, you will encounter an error. If `groupName` is not provided, it will be set to a default value automatically.
</Warning>

<Note>
  **groupName**: The group name acts like a namespace which creates a scope for context. Documents with the same group name will be grouped together for better organization and retrieval.

  **Example Use Cases**:

  * `['project-alpha']` - Group all documents related to a specific project
  * `['customer-support', 'tier-1']` - Organize support documentation by department and priority
  * `['legal', 'contracts']` - Categorize legal documents by type and category
  * `['training', 'onboarding']` - Group training materials for new employee onboarding
</Note>

#### Context: Search

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
  apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
  const { contexts } = await client.v1.context.search({

    // [REQUIRED] Core search parameters
    query: 'Your search query here',
    similarity_threshold: 0.8,
    minimum_similarity_threshold: 0.5,
    scope: 'internal',

    // Optional - can be null
    body_metadata: {
       groupName: ['project-alpha'],
       fileType: 'ai/conversation',
    },
  });

  console.log(contexts);

} 
catch (error) {
  console.error("Search failed:", error);
}
```

#### Context: Delete

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
  apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
  await client.v1.context.delete({
    // [REQUIRED] Must specify the source to delete from
    source: 'web-upload',
    
    // [OPTIONAL] Target specific users or organizations
    user_id: 'your_user_id', 
    organization_id: 'your_organization_id',
    
    // [REQUIRED] Flags to specify deletion scope (must set one)
    by_doc: true,
    by_id: false,
  });

  console.log("Context deleted successfully.");

} catch (error) {
  console.error("Failed to delete context:", error);
}
```

#### Context: View (per-user)

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
    apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
    // Retrieves context specific to the authenticated user
    const docs = await client.v1.context.view.docs();
    console.log("User docs retrieved:", docs)
} catch (error) {
    console.error("Could not retrieve user docs:", error)
}
```

<Note>
  **Per-user View**: This endpoint gives the authenticated user their own context from the organization.
</Note>

#### Context: Traces

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
  apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
  // List all traces
  const { traces } = await client.v1.context.traces.list();
  console.log("Traces found:", traces);

  // Example: Delete a specific trace
  if (traces.length > 0) {
     const traceId = traces[0].id;
     await client.v1.context.traces.delete(traceId);
     console.log(`Trace ${traceId} deleted.`);
  }

} catch (error) {
  console.error("Error managing traces:", error.message);
}
```

#### Organization: View Context

```ts theme={null}
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({
  apiKey: process.env.ALCHEMYST_AI_API_KEY,
});

try {
  // Retrieves context for specific users within the organization
  const res = await client.v1.org.context.view({
    userIds: ['user_123', 'user_456'],
  });
  
  console.log("Organization context retrieved:", res);

} catch (error) {
  console.error("Organization view failed:", error);
}
```

<Note>
  **Organization View**: This endpoint allows you to fetch context based on specific user IDs within your organization.
</Note>

## Troubleshooting and Errors

If you encounter unexpected behavior or specific API errors, please refer to our [Troubleshooting Guide](/advanced/troubleshooting) for detailed solutions and error code definitions.
