---
title: "Code recipes — Context Infrastructure"
canonical: "https://press.getalchemystai.com/books/context-infrastructure-build-ai-that-understands-your-business/appendix-d-code-recipes"
last_updated: "2018-10-20"
book: "Context Infrastructure"
label: "Appendix D"
---

# Code recipes

All recipes use `@alchemystai/sdk` 0.11.1 with `const client = new AlchemystAI()`.

## Ingest many files with bounded concurrency

One `add()` per file keeps `fileName` deduplication meaningful; three requests in flight respects rate limits, and the SDK retries transient failures.

```ts
import AlchemystAI from '@alchemystai/sdk';

const client = new AlchemystAI({ maxRetries: 5 });

type SourceFile = { name: string; type: string; text: string };

export async function ingestFiles(files: SourceFile[], groupName: string[]) {
  for (let i = 0; i < files.length; i += 3) {
    await Promise.all(
      files.slice(i, i + 3).map((f) =>
        client.v1.context.add({
          context_type: 'resource',
          scope: 'internal',
          source: 'bulk-import',
          documents: [{ content: f.text }],
          metadata: { fileName: f.name, fileType: f.type, groupName },
        }),
      ),
    );
  }
}
```

## Keep history with versioned file names (Strategy B)

The typed SDK metadata accepts `fileName`, `fileType`, `fileSize`, `groupName` and `lastModified`, so carry version details in the name and a short header in the content.

```ts
await client.v1.context.add({
  context_type: 'resource',
  scope: 'internal',
  source: 'legal',
  documents: [{ content: `Version 2.0 (final). Supersedes msa-acme-v1.pdf.\n\n${contractText}` }],
  metadata: {
    fileName: 'msa-acme-v2.pdf',
    fileType: 'application/pdf',
    groupName: ['legal', 'contracts', 'acme'],
    lastModified: new Date().toISOString(),
  },
});
```

## Expose search to your agent as a tool

Letting the model write the query keeps it short and specific, and an explicit "no evidence" result stops it from guessing.

```ts
export const searchCompanyContext = {
  name: 'search_company_context',
  description: 'Look up company policies, product facts and customer history. Use a short, specific query.',
  parameters: {
    type: 'object',
    properties: {
      query: { type: 'string' },
      area: { type: 'string', enum: ['support', 'billing', 'product'] },
    },
    required: ['query'],
  },
};

export async function runSearchCompanyContext(args: { query: string; area?: string }) {
  const { contexts } = await client.v1.context.search({
    query: args.query,
    minimum_similarity_threshold: 0.5,
    similarity_threshold: 0.9,
    scope: 'internal',
    body_metadata: args.area ? { groupName: [args.area] } : undefined,
  });
  if (!contexts?.length) return 'NO_EVIDENCE: say you could not find this in company sources.';
  return contexts.map((c, i) => `[${i + 1}] ${c.content}`).join('\n\n');
}
```

## Remember the outcome of every call

Keyed on the customer, so the next attempt starts from this one.

```ts
await client.v1.context.memory.add({
  sessionId: `customer-${customerId}`,
  contents: [
    {
      role: 'assistant',
      content: `Call ${callId}: customer promised payment by ${promiseDate}; stated reason for delay: ${objection}.`,
    },
  ],
  metadata: { groupName: ['collections', campaignId] },
});
```

---

- Previous: [Appendix C: Benchmark data](https://press.getalchemystai.com/books/context-infrastructure-build-ai-that-understands-your-business/appendix-c-benchmark-data.md)
- Contents: [Context Infrastructure](https://press.getalchemystai.com/books/context-infrastructure-build-ai-that-understands-your-business.md)
- Next: [Appendix E: groupName taxonomy templates](https://press.getalchemystai.com/books/context-infrastructure-build-ai-that-understands-your-business/appendix-e-groupname-taxonomy-templates.md)
