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

# Examples

> Complete code examples for the Nia AI SDKs

All examples assume you have initialized the SDK:

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    import os
    from nia_py.sdk import NiaSDK

    sdk = NiaSDK(api_key=os.environ["NIA_API_KEY"])
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { NiaSDK } from "nia-ai-ts";

    const sdk = new NiaSDK({ apiKey: process.env.NIA_API_KEY! });
    ```
  </Tab>
</Tabs>

***

## Repository Operations

### Index a Repository

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py import AuthenticatedClient
    from nia_py.api.v2_api import index_repository_v2_v2_repositories_post
    from nia_py.models import RepositoryRequest

    client = AuthenticatedClient(
        base_url="https://apigcp.trynia.ai/v2",
        token=os.environ["NIA_API_KEY"],
    )

    result = index_repository_v2_v2_repositories_post.sync(
        client=client,
        body=RepositoryRequest(repository="vercel/ai", branch="main"),
    )
    print(f"Indexing started: {result}")
    ```

    Or with the high-level SDK:

    ```python theme={null}
    sdk.sources.create({"url": "https://github.com/vercel/ai", "branch": "main"})
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiRepositoriesService } from "nia-ai-ts";

    const result = await V2ApiRepositoriesService.indexRepositoryV2V2RepositoriesPost({
      repository: "vercel/ai",
      branch: "main",
    });
    console.log("Indexing started:", result);
    ```

    Or with the high-level SDK:

    ```typescript theme={null}
    await sdk.sources.create({ url: "https://github.com/vercel/ai", branch: "main" });
    ```
  </Tab>
</Tabs>

### Check Repository Status

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import get_repository_status_v2_v2_repositories_repository_id_get

    status = get_repository_status_v2_v2_repositories_repository_id_get.sync(
        client=client,
        repository_id="vercel/ai",
    )
    print(f"Status: {status}")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const status = await V2ApiRepositoriesService.getRepositoryStatusV2V2RepositoriesRepositoryIdGet(
      "vercel/ai"
    );
    console.log("Status:", status);
    ```
  </Tab>
</Tabs>

### Browse Repository Tree

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import get_repository_tree_v2_v2_repositories_repository_id_tree_get

    tree = get_repository_tree_v2_v2_repositories_repository_id_tree_get.sync(
        client=client,
        repository_id="vercel/ai",
    )
    print(tree)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const tree = await V2ApiRepositoriesService.getRepositoryTreeV2V2RepositoriesRepositoryIdTreeGet(
      "vercel/ai"
    );
    console.log(tree);
    ```
  </Tab>
</Tabs>

### Read File Content

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import get_repository_content_v2_v2_repositories_repository_id_content_get

    content = get_repository_content_v2_v2_repositories_repository_id_content_get.sync(
        client=client,
        repository_id="vercel/ai",
        path="packages/ai/src/index.ts",
    )
    print(content)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const content = await V2ApiRepositoriesService.getRepositoryContentV2V2RepositoriesRepositoryIdContentGet(
      "vercel/ai",
      "packages/ai/src/index.ts"
    );
    console.log(content);
    ```
  </Tab>
</Tabs>

### Grep Search in Repository

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import grep_repository_v2_v2_repositories_repository_id_grep_post
    from nia_py.models import CodeGrepRequest

    results = grep_repository_v2_v2_repositories_repository_id_grep_post.sync(
        client=client,
        repository_id="vercel/ai",
        body=CodeGrepRequest(
            pattern="async function",
            path="src/",
            context_lines=2,
            case_sensitive=False,
        ),
    )
    print(results)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiRepositoriesService } from "nia-ai-ts";

    const results = await V2ApiRepositoriesService.grepRepositoryV2V2RepositoriesRepositoryIdGrepPost(
      "vercel/ai",
      {
        pattern: "async function",
        path: "src/",
        context_lines: 2,
        case_sensitive: false,
      }
    );
    console.log(results);
    ```
  </Tab>
</Tabs>

***

## AI Search

### Semantic Code Search

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.query(
        messages=[{"role": "user", "content": "How does streaming work in the AI SDK?"}],
        repositories=["vercel/ai"],
        include_sources=True,
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.query({
      messages: [{ role: "user", content: "How does streaming work in the AI SDK?" }],
      repositories: ["vercel/ai"],
      include_sources: true,
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

### Universal Search

Searches across all your indexed repositories and documentation automatically.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.universal(
        query="How to implement tool calling?",
        top_k=10,
        include_repos=True,
        include_docs=True,
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.universal({
      query: "How to implement tool calling?",
      top_k: 10,
      include_repos: true,
      include_docs: true,
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

### Web Search

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.web(query="latest LLM developments 2025")
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.web({ query: "latest LLM developments 2025" });
    console.log(result);
    ```
  </Tab>
</Tabs>

### Deep Research

Multi-step research with AI analysis and citations.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.deep(
        query="Compare React Server Components vs traditional SSR approaches",
        output_format="comparison table",
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.deep({
      query: "Compare React Server Components vs traditional SSR approaches",
      output_format: "comparison table",
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

***

## Documentation Sources

### Index Documentation

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import create_data_source_v2_v2_data_sources_post
    from nia_py.models import DataSourceRequest

    result = create_data_source_v2_v2_data_sources_post.sync(
        client=client,
        body=DataSourceRequest(
            url="https://docs.anthropic.com",
            display_name="Anthropic Docs",
            crawl_entire_domain=True,
        ),
    )
    print(f"Indexing started: {result}")
    ```

    Or with the high-level SDK:

    ```python theme={null}
    sdk.sources.create({
        "url": "https://docs.anthropic.com",
        "display_name": "Anthropic Docs",
    })
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiDataSourcesService } from "nia-ai-ts";

    const result = await V2ApiDataSourcesService.createDataSourceV2V2DataSourcesPost({
      url: "https://docs.anthropic.com",
      display_name: "Anthropic Docs",
      crawl_entire_domain: true,
    });
    console.log("Indexing started:", result);
    ```

    Or with the high-level SDK:

    ```typescript theme={null}
    await sdk.sources.create({
      url: "https://docs.anthropic.com",
      display_name: "Anthropic Docs",
    });
    ```
  </Tab>
</Tabs>

### List Sources

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    # List all sources
    all_sources = sdk.sources.list()

    # Filter by type
    repos = sdk.sources.list(type="repository")
    docs = sdk.sources.list(type="documentation")

    # Search by name
    results = sdk.sources.list(query="anthropic")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    // List all sources
    const allSources = await sdk.sources.list({});

    // Filter by type
    const repos = await sdk.sources.list({ type: "repository" });
    const docs = await sdk.sources.list({ type: "documentation" });

    // Search by name
    const results = await sdk.sources.list({ query: "anthropic" });
    ```
  </Tab>
</Tabs>

### Search Documentation

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.query(
        messages=[{"role": "user", "content": "How to use Claude's tool use feature?"}],
        data_sources=["Anthropic Docs"],
        search_mode="sources",
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.query({
      messages: [{ role: "user", content: "How to use Claude's tool use feature?" }],
      data_sources: ["Anthropic Docs"],
      search_mode: "sources",
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

***

## Research Papers

### Index an arXiv Paper

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import index_research_paper_v2_v2_research_papers_post
    from nia_py.models import ResearchPaperRequest

    result = index_research_paper_v2_v2_research_papers_post.sync(
        client=client,
        body=ResearchPaperRequest(url="https://arxiv.org/abs/2303.08774"),
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiDataSourcesService } from "nia-ai-ts";

    const result = await V2ApiDataSourcesService.indexResearchPaperV2V2ResearchPapersPost({
      url: "https://arxiv.org/abs/2303.08774",
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

***

## Package Search

Search source code of public packages on npm and PyPI without indexing.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import package_search_hybrid_v2_v2_package_search_hybrid_post
    from nia_py.models import PackageSearchHybridRequest

    result = package_search_hybrid_v2_v2_package_search_hybrid_post.sync(
        client=client,
        body=PackageSearchHybridRequest(
            registry="py_pi",
            package_name="openai",
            semantic_queries=["How does streaming work?"],
        ),
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiPackageSearchService } from "nia-ai-ts";

    const result = await V2ApiPackageSearchService.packageSearchHybridV2V2PackageSearchHybridPost({
      registry: "py_pi",
      package_name: "openai",
      semantic_queries: ["How does streaming work?"],
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

***

## Oracle Research

### Create and Poll a Research Job

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    # Start a research job
    job = sdk.oracle.create_job(
        query="Compare React Server Components vs traditional SSR",
        repositories=["vercel/next.js"],
        output_format="comparison table",
        model="claude-sonnet-4-5-20250929",
    )
    print(f"Job ID: {job['id']}, Status: {job['status']}")

    # Poll until complete (default 10min timeout)
    result = sdk.oracle.wait_for_job(
        job_id=job["id"],
        timeout_seconds=300.0,
        poll_interval_seconds=3.0,
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    // Start a research job
    const job = await sdk.oracle.createJob({
      query: "Compare React Server Components vs traditional SSR",
      repositories: ["vercel/next.js"],
      output_format: "comparison table",
      model: "claude-sonnet-4-5-20250929",
    });
    console.log(`Job ID: ${job.id}, Status: ${job.status}`);

    // Poll until complete (default 10min timeout)
    const result = await sdk.oracle.waitForJob(job.id, 300_000, 3_000);
    console.log(result);
    ```
  </Tab>
</Tabs>

### Stream Research Events

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    job = sdk.oracle.create_job(query="Analyze the caching strategy in Next.js App Router")

    for event in sdk.oracle.stream_job_events(job_id=job["id"]):
        # Each event is a parsed JSON dict from the SSE stream
        event_type = event.get("type", "unknown")
        print(f"[{event_type}] {event}")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const job = await sdk.oracle.createJob({
      query: "Analyze the caching strategy in Next.js App Router",
    });

    for await (const event of sdk.oracle.streamJob(job.id)) {
      // Each event is a parsed JSON object from the SSE stream
      console.log(`[${event.type}]`, event);
    }
    ```
  </Tab>
</Tabs>

### List and Manage Jobs

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    # List recent jobs
    jobs = sdk.oracle.list_jobs(limit=10)

    # Filter by status
    completed = sdk.oracle.list_jobs(status="completed")

    # Get a specific job
    job = sdk.oracle.get_job(job_id="job-uuid")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { DefaultService } from "nia-ai-ts";

    // List recent jobs
    const jobs = await DefaultService.listOracleJobsV2OracleJobsGet(undefined, 10);

    // Get a specific job
    const job = await DefaultService.getOracleJobV2OracleJobsJobIdGet("job-uuid");
    ```
  </Tab>
</Tabs>

***

## Context Sharing

Save and retrieve context across sessions.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import (
        save_context_v2_v2_contexts_post,
        semantic_search_contexts_v2_v2_contexts_semantic_search_get,
    )
    from nia_py.models import ContextSaveRequest

    # Save context
    save_context_v2_v2_contexts_post.sync(
        client=client,
        body=ContextSaveRequest(
            title="Auth implementation notes",
            summary="Implemented OAuth2 flow with refresh tokens",
            content="Detailed implementation notes...",
            tags=["auth", "oauth"],
        ),
    )

    # Search contexts by semantic similarity
    results = semantic_search_contexts_v2_v2_contexts_semantic_search_get.sync(
        client=client,
        query="authentication",
    )
    print(results)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { V2ApiContextsService } from "nia-ai-ts";

    // Save context
    await V2ApiContextsService.saveContextV2V2ContextsPost({
      title: "Auth implementation notes",
      summary: "Implemented OAuth2 flow with refresh tokens",
      content: "Detailed implementation notes...",
      tags: ["auth", "oauth"],
    });

    // Search contexts by semantic similarity
    const results = await V2ApiContextsService.semanticSearchContextsV2V2ContextsSemanticSearchGet(
      "authentication"
    );
    console.log(results);
    ```
  </Tab>
</Tabs>

***

## GitHub Tracer

Live code search across GitHub repositories without indexing.

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    from nia_py.api.v2_api import create_tracer_job_v2_github_tracer_post
    from nia_py.models import TracerRequest

    job = create_tracer_job_v2_github_tracer_post.sync(
        client=client,
        body=TracerRequest(
            query="How does the streaming API work?",
            repositories=["vercel/ai"],
        ),
    )
    print(f"Tracer job: {job}")
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    import { GithubSearchService } from "nia-ai-ts";

    const job = await GithubSearchService.createTracerJobV2GithubTracerPost({
      query: "How does the streaming API work?",
      repositories: ["vercel/ai"],
    });
    console.log("Tracer job:", job);
    ```
  </Tab>
</Tabs>

***

## Local Sync with E2E Encryption

Sync personal data sources (iMessage, WhatsApp, Apple Notes, etc.) with zero-knowledge encryption. Plaintext never leaves your device.

<Card title="iMessage Demo App" icon="github" href="https://github.com/nozomio-labs/nia-imessage-app-demo">
  Full working example: E2E encrypted iMessage sync, indexing, and conversational search. Clone and run.
</Card>

### Sync iMessage

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    import { NiaSDK } from "nia-ai-ts";
    import { deriveE2EKeys, buildE2ESyncBatch } from "nia-ai-ts/local-first";
    import { iMessageAdapter } from "nia-ai-ts/local-first/imessage";

    const sdk = new NiaSDK({ apiKey: process.env.NIA_API_KEY! });

    // 1. Derive encryption keys from passphrase (stored in OS keychain)
    const { encryptionKey, blindIndexKey } = await deriveE2EKeys(passphrase);

    // 2. Extract messages from local chat.db
    const batch = await iMessageAdapter.buildSyncBatch({
      dbPath: "~/Library/Messages/chat.db",
      cursor: null,  // null = full sync, or pass last cursor for incremental
    });

    // 3. Encrypt and upload
    const encrypted = await buildE2ESyncBatch({
      chunks: batch.files,
      encryptionKey,
      blindIndexKey,
      embedder: "zembed-1-2560",
    });

    await sdk.daemon.pushE2ESync({
      localFolderId: "your-imessage-folder-id",
      chunks: encrypted.syncChunks,
    });

    console.log(`Synced ${batch.stats.total} messages`);
    ```
  </Tab>
</Tabs>

### Create a Decrypt Session

Decrypt sessions grant temporary, scoped access to encrypted data for agents.

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    // Desktop creates a session for the remote agent
    const session = await sdk.daemon.createE2ESession({
      localFolderId: "your-imessage-folder-id",
      ttlSeconds: 300,         // 5-minute window
      maxChunks: 50,           // max chunks decryptable
      allowedOperations: ["search", "read"],
    });

    console.log(`Session: ${session.id}, expires: ${session.expiresAt}`);
    ```
  </Tab>
</Tabs>

### Query E2E Sources

<Tabs>
  <Tab title="Python">
    ```python theme={null}
    result = sdk.search.query(
        messages=[{"role": "user", "content": "What did Alice say about the deadline?"}],
        local_folders=["your-imessage-folder-id"],
        e2e_session_id="session-id-from-desktop",
    )
    print(result)
    ```
  </Tab>

  <Tab title="TypeScript">
    ```typescript theme={null}
    const result = await sdk.search.query({
      messages: [{ role: "user", content: "What did Alice say about the deadline?" }],
      local_folders: ["your-imessage-folder-id"],
      e2e_session_id: "session-id-from-desktop",
    });
    console.log(result);
    ```
  </Tab>
</Tabs>

### Purge Encrypted Data

<Tabs>
  <Tab title="TypeScript">
    ```typescript theme={null}
    // Remove all encrypted data for a source
    await sdk.daemon.purgeE2EData({
      localFolderId: "your-imessage-folder-id",
    });
    ```
  </Tab>
</Tabs>

***

## Async Support (Python)

Every low-level API function has four variants:

```python theme={null}
from nia_py.api.v2_api import search_universal_v2_v2_search_universal_post
from nia_py.models import UniversalSearchRequest
from nia_py.types import Response

body = UniversalSearchRequest(query="test")

# Sync — returns parsed data or None
result = search_universal_v2_v2_search_universal_post.sync(client=client, body=body)

# Sync detailed — returns Response with status_code, headers, parsed
response: Response = search_universal_v2_v2_search_universal_post.sync_detailed(client=client, body=body)

# Async — returns parsed data or None
result = await search_universal_v2_v2_search_universal_post.asyncio(client=client, body=body)

# Async detailed — returns Response
response = await search_universal_v2_v2_search_universal_post.asyncio_detailed(client=client, body=body)
```
