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

# Mastra

> Integrate Gentrace with Mastra's agent framework for AI applications

<Info>
  For a complete example, check out our [Mastra integration example on
  GitHub](https://github.com/gentrace/gentrace-node/blob/main/examples/mastra-ai-sdk.ts).
</Info>

Mastra is a framework for building AI agents with built-in support for multiple LLM providers. This guide shows you how to integrate Gentrace with Mastra to trace and monitor your AI agents.

## Prerequisites

* Node.js 20+
* A [Gentrace account and API key](https://gentrace.ai/s/api-keys)
* A Mastra project

## Installation

<CodeGroup>
  ```bash npm theme={null}
  npm install @mastra/core gentrace @ai-sdk/openai
  ```

  ```bash yarn theme={null}
  yarn add @mastra/core gentrace @ai-sdk/openai
  ```

  ```bash pnpm theme={null}
  pnpm add @mastra/core gentrace @ai-sdk/openai
  ```
</CodeGroup>

## Configuration

Initialize both Gentrace and Mastra in your application:

```typescript theme={null}
import { init, interaction } from 'gentrace';
import { Mastra } from '@mastra/core';
import { createOpenAI } from '@ai-sdk/openai';

async function main() {
  // Initialize Gentrace
  init({
    apiKey: process.env.GENTRACE_API_KEY,
  });

  // Create OpenAI provider
  const openai = createOpenAI({
    apiKey: process.env.OPENAI_API_KEY,
  });

  // Initialize Mastra with Gentrace telemetry
  const mastra = new Mastra({
    openai,
    telemetry: {
      gentrace: {
        apiKey: process.env.GENTRACE_API_KEY,
      },
    },
  });
}

// Run the main function
main().catch(console.error);
```

## Usage

Here's a complete example showing how to create and use a Mastra agent with Gentrace tracing:

```typescript agents/email-assistant.ts theme={null}
import { Agent } from '@mastra/core';

// Create an agent
const emailAssistant = new Agent({
  name: 'EmailAssistant',
  model: 'gpt-4o-mini',
  instructions:
    'You are a helpful email assistant. Help users write professional emails.',
  provider: 'OPENAI',
});

// Use the agent within a Gentrace interaction
async function generateEmail(subject: string, context: string) {
  return await interaction(
    'generate-email',
    async () => {
      const response = await emailAssistant.text({
        messages: [
          {
            role: 'user',
            content: `Write a professional email about: ${subject}\nContext: ${context}`,
          },
        ],
      });

      return response.text;
    },
    {
      pipelineId: process.env.GENTRACE_PIPELINE_ID!,
      metadata: {
        subject,
        agentName: 'EmailAssistant',
      },
    },
  );
}
```

## Environment Variables

Create a `.env` file with your API keys:

```bash .env theme={null}
GENTRACE_API_KEY=your-gentrace-api-key
GENTRACE_PIPELINE_ID=your-pipeline-id
OPENAI_API_KEY=your-openai-api-key
```

## Advanced Features

### Using Multiple Agents

Mastra supports creating multiple agents with different configurations:

```typescript theme={null}
const technicalAgent = new Agent({
  name: 'TechnicalWriter',
  model: 'gpt-4o',
  instructions: 'You are a technical documentation expert.',
  provider: 'OPENAI',
});

const creativeAgent = new Agent({
  name: 'CreativeWriter',
  model: 'gpt-4o-mini',
  instructions: 'You are a creative content writer.',
  provider: 'OPENAI',
});
```

### Agent Tools and Functions

Mastra agents can use tools and functions, which are automatically traced by Gentrace:

```typescript theme={null}
const researchAgent = new Agent({
  name: 'ResearchAssistant',
  model: 'gpt-4o',
  instructions: 'You help with research tasks.',
  provider: 'OPENAI',
  tools: {
    searchWeb: {
      description: 'Search the web for information',
      input: z.object({
        query: z.string(),
      }),
      execute: async ({ query }) => {
        // Your search implementation
        return `Search results for: ${query}`;
      },
    },
  },
});
```

## Related Resources

* [Vercel AI SDK Integration](/integrations/ai-sdk)
* [Tracing Guide](/tracing/overview)
