Skip to content

Latest commit

 

History

History
273 lines (205 loc) · 7.78 KB

File metadata and controls

273 lines (205 loc) · 7.78 KB
title SDK Quickstart
description Get up and running with Metorial in under 5 minutes
**What you'll learn:**
  • How to install the Metorial SDK
  • Available AI providers and integrations
  • How to create sessions and use tools
  • OAuth flow for authenticated services

Before you begin:

References:

Prerequisites

  1. Metorial API key: Get one from app.metorial.com
  2. Provider deployment ID: Deploy a provider (e.g., Exa for search) from the dashboard
  3. AI provider API key: OpenAI, Anthropic, Google, etc.

Installation

The Metorial SDK consists of two parts: the core SDK (which handles sessions and tool management) and a provider package (which integrates with your chosen AI model). Install both to get started.

# Install the core SDK
npm install metorial

# Install a provider package (choose one or more)
npm install @metorial/ai-sdk      # Vercel AI SDK (recommended)
npm install @metorial/anthropic   # Anthropic Claude
npm install @metorial/openai      # OpenAI
npm install @metorial/google      # Google Gemini
npm install @metorial/mistral     # Mistral
npm install @metorial/deepseek    # DeepSeek
# Install the SDK
pip install metorial

# Install your AI provider
pip install anthropic   # For Claude
pip install openai      # For OpenAI/DeepSeek

We support OpenAI, Anthropic, Google, Mistral, DeepSeek, and any OpenAI-compatible API. See the TypeScript SDK and Python SDK repos for all available providers.

Your First AI Agent

This example shows how to create an AI agent that can use tools from your deployed providers. The agent will have access to any tools provided by your provider deployment (like search, file operations, or API calls).

What this code does:

  1. Initializes the Metorial SDK with your API key
  2. Creates a session connected to your provider deployment
  3. Passes the available tools to your AI model
  4. Handles tool calls in an agentic loop
import { Metorial } from 'metorial';
import { metorialAiSdk } from '@metorial/ai-sdk';
import { anthropic } from '@ai-sdk/anthropic';
import { streamText } from 'ai';

let metorial = new Metorial({
    apiKey: process.env.METORIAL_API_KEY
});

let session = await metorial.connect({
  adapter: metorialAnthropic(),
  providers: [
    { providerDeploymentId: 'your-provider-deployment-id' }
  ]
});

let tools = session.tools()


let result = streamText({
	model: anthropic('claude-sonnet-4-5'),
	prompt: 'Search for the latest AI research',
	tools
});

for await (let textPart of result.textStream) {
	process.stdout.write(textPart);
}
from metorial import Metorial
from anthropic import AsyncAnthropic
import asyncio
import os

metorial = Metorial(api_key=os.getenv("METORIAL_API_KEY"))
anthropic = AsyncAnthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))

async def main():
    async with metorial.provider_session(
        provider="anthropic",
        providers=[{"provider_deployment_id": "your-provider-deployment-id"}],
    ) as session:
        response = await anthropic.messages.create(
            model="claude-sonnet-4-5",
            max_tokens=1024,
            tools=session.tools,
            messages=[{"role": "user", "content": "What's trending on Hacker News?"}],
        )

        if response.stop_reason == "tool_use":
            tool_calls = [b for b in response.content if b.type == "tool_use"]
            results = await session.call_tools(tool_calls)
            # Add results to messages and continue conversation...

asyncio.run(main())

OAuth Flow

For services requiring user authentication (like Slack, GitHub, or Google Calendar), use a Provider Setup Session to authorize your users. The resulting Provider Auth Config stores their credentials for reuse.

The flow:

  1. Create a Provider Setup Session for each service that needs authentication
  2. Redirect your user to the session URL to complete OAuth
  3. Wait for the setup session to complete — you get back an auth config
  4. Pass the auth config ID when creating sessions for that user
import { Metorial } from 'metorial';
import { metorialAnthropic } from '@metorial/anthropic';

let metorial = new Metorial({
    apiKey: process.env.METORIAL_API_KEY
});

// 1. Create a setup session for the provider
let setupSession = await metorial.providers.setupSessions.create({
    providerId: 'your-slack-provider-id',
    providerAuthMethodId: 'oauth'
    // redirectUrl: 'https://yourapp.com/oauth/callback'
});

// 2. Send the URL to your user
console.log('Authorize Slack:', setupSession.url);

// 3. (For development) wait for completion — returns the completed setup session
let completedSetup = await metorial.waitForSetupSession([setupSession]);

// Store completedSetup.authConfig.id for this user in your database

// 4. Use the auth config in a session
let session = await metorial.connect({
  adapter: metorialAnthropic(),
  providers: [
    {
		providerDeploymentId: 'your-provider-deployment-id',
		providerAuthConfigId: completedSetup.authConfig.id
	}
  ]
});

let tools = session.tools();
import asyncio
from metorial import Metorial

async def main():
    metorial = Metorial(api_key="your-metorial-api-key")

    # 1. Create a setup session for the provider
    setup_session = await metorial.providers.setup_sessions.create(
        provider_id="your-slack-provider-id",
        provider_auth_method_id="oauth"
        # redirect_url="https://yourapp.com/oauth/callback"
    )

    # 2. Send the URL to your user
    print(f"Authorize Slack: {setup_session.url}")

    # 3. Wait for completion — returns the completed setup session
    completed = await metorial.wait_for_setup_session(setup_session)

    # Store completed.auth_config.id for this user in your database

    # 4. Use the auth config in a session
    async with metorial.provider_session(
        provider="anthropic",
        providers=[
            {
                "provider_deployment_id": "your-slack-provider-deployment-id",
                "provider_auth_config_id": completed.auth_config.id
            },
            {
                "provider_deployment_id": "your-exa-deployment-id"  # No OAuth needed
            }
        ],
    ) as session:
        pass  # Use session.tools

asyncio.run(main())

Error Handling

The Metorial SDK provides specific error types to help you handle different failure scenarios. Catch MetorialAPIError for API-related issues like authentication failures, rate limits, or invalid deployment IDs.

import { MetorialAPIError } from 'metorial';

try {
    /* ... */
} catch (error) {
    if (error instanceof MetorialAPIError) {
        console.error(`API Error: ${error.message} (Status: ${error.status})`);
    } else {
        console.error('Unexpected error:', error);
    }
}
from metorial import MetorialAPIError

try:
    async with metorial.provider_session(...) as session:
        pass
except MetorialAPIError as e:
    print(f"API Error: {e.message} (Status: {e.status})")
except Exception as e:
    print(f"Unexpected error: {e}")

What's Next?

Handle user authorization for services like Slack and GitHub. Use with OpenAI, Anthropic, Google, and more.