);
};
```
--------------------------------
### Integrate CopilotKit with Mastra
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
Configures the CopilotKit React components to communicate with a Mastra agent. Requires the runtime URL of the Mastra server and the specific agent identifier.
```typescript
import { CopilotChat } from "@copilotkit/react-ui";
import { CopilotKit } from "@copilotkit/react-core";
import "@copilotkit/react-ui/styles.css";
const MASTRA_BASE_URL = "http://localhost:4750";
function CopilotKitDemo() {
return (
);
}
```
--------------------------------
### Create Weather Agent with Memory and Tools (TypeScript)
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
Defines a 'Weather Agent' using Mastra's Agent class, including its ID, name, description, instructions, model, tools, and memory. This agent is designed to provide weather information using a predefined 'weatherTool'.
```typescript
// src/mastra/agents/weather-agent.ts
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { weatherTool } from "../tools/weather-tool";
export const weatherAgent = new Agent({
id: "weather-agent",
name: "Weather Agent",
description: "This agent provides weather information for a given location",
instructions: `
You are a helpful weather assistant that provides accurate weather information.
Your primary function is to help users get weather details for specific locations.
- Always ask for a location if none is provided
- If the location name isn't in English, please translate it
- Include relevant details like humidity, wind conditions, and precipitation
- Keep responses concise but informative
Use the weatherTool to fetch current weather data.
`,
model: "openai/gpt-4o-mini",
tools: { weatherTool },
memory: new Memory(),
});
```
--------------------------------
### Configure Multi-Agent Networks
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
Defines a routing agent that coordinates specialized agents and workflows, enabling complex task delegation based on user intent.
```typescript
import { Agent } from "@mastra/core/agent";
import { weatherAgent } from "./weather-agent";
import { ghibliAgent } from "./ghibli-agent";
import { Memory } from "@mastra/memory";
import { activitiesWorkflow } from "../workflows/activities-workflow";
export const routingAgent = new Agent({
id: "routing-agent",
name: "Routing Agent",
instructions: `You are a routing agent that directs user queries to the appropriate specialized agent.\n\n Available agents:\n - weatherAgent: Provides weather information for specific locations.\n - ghibliAgent: Answers questions about Studio Ghibli films and characters.\n\n Available workflows:\n - activitiesWorkflow: Helps plan activities in various cities.\n\n Route queries based on topic: weather queries to Weather Agent, Ghibli queries to Ghibli Agent, activity planning to the workflow.`,
model: "openai/gpt-4o-mini",
agents: {
weatherAgent,
ghibliAgent,
},
workflows: {
activitiesWorkflow,
},
memory: new Memory(),
});
```
--------------------------------
### Fetch Agent Details with useAgent Hook (TypeScript)
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
The `useAgent` hook fetches details for a specific agent using the Mastra client. It utilizes `react-query` for data fetching and caching. It requires an `agentId` and returns query state including data, loading, and error information. The query is enabled only when an `agentId` is provided.
```typescript
import { useMastraClient } from "@mastra/react";
import { useQuery } from "@tanstack/react-query";
export const useAgent = (agentId?: string) => {
const client = useMastraClient();
return useQuery({
queryKey: ["agent", agentId],
queryFn: () => (agentId ? client.getAgent(agentId).details() : null),
retry: false,
enabled: Boolean(agentId),
});
};
```
--------------------------------
### Create Custom Tools with Zod Schemas in Mastra
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
Defines an executable tool using Mastra's createTool function. It utilizes Zod to enforce strict input and output schemas, ensuring data integrity during agent execution.
```typescript
import { createTool } from "@mastra/core/tools";
import { z } from "zod";
export const forecastSchema = z.object({
date: z.string(),
maxTemp: z.number(),
minTemp: z.number(),
precipitationChance: z.number(),
temperature: z.number(),
feelsLike: z.number(),
humidity: z.number(),
windSpeed: z.number(),
windGust: z.number(),
conditions: z.string(),
location: z.string(),
icon: z.string(),
});
export const weatherTool = createTool({
id: "get-weather",
description: "Get current weather for a location",
inputSchema: z.object({
location: z.string().describe("The location to get the weather for"),
}),
outputSchema: forecastSchema,
execute: async (inputData) => {
const geocodingUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(inputData.location)}&count=1`;
const geocodingResponse = await fetch(geocodingUrl);
const geocodingData = await geocodingResponse.json();
if (!geocodingData.results?.[0]) {
throw new Error(`Location '${inputData.location}' not found`);
}
const { latitude, longitude, name } = geocodingData.results[0];
const weatherUrl = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_gusts_10m,weather_code&hourly=precipitation_probability,temperature_2m`;
const response = await fetch(weatherUrl);
const data = await response.json();
return {
date: new Date().toISOString(),
maxTemp: Math.max(...data.hourly.temperature_2m),
minTemp: Math.min(...data.hourly.temperature_2m),
temperature: data.current.temperature_2m,
feelsLike: data.current.apparent_temperature,
humidity: data.current.relative_humidity_2m,
windSpeed: data.current.wind_speed_10m,
windGust: data.current.wind_gusts_10m,
conditions: "Clear sky",
location: name,
precipitationChance: Math.max(...data.hourly.precipitation_probability),
icon: "sun",
};
},
});
```
--------------------------------
### List Memory Threads with useThreads Hook (TypeScript)
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
The `useThreads` hook lists memory threads associated with a resource and agent. It depends on `react-query` and the Mastra client. The hook requires `resourceId`, `agentId`, and `isMemoryEnabled` as parameters. The query is only executed if `isMemoryEnabled` is true.
```typescript
export const useThreads = ({ resourceId, agentId, isMemoryEnabled }) => {
const client = useMastraClient();
return useQuery({
queryKey: ["memory", "threads", resourceId, agentId],
queryFn: async () => {
if (!isMemoryEnabled) return null;
const result = await client.listMemoryThreads({ resourceId, agentId });
return result.threads;
},
enabled: Boolean(isMemoryEnabled),
});
};
```
--------------------------------
### Fetch Agent Messages with useAgentMessages Hook (TypeScript)
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
The `useAgentMessages` hook fetches messages for a specific thread belonging to an agent. It uses `react-query` for data management. This hook requires `threadId`, `agentId`, and `memory` object. The query is enabled only if `memory` is truthy and `threadId` is provided.
```typescript
export const useAgentMessages = ({ threadId, agentId, memory }) => {
const client = useMastraClient();
return useQuery({
queryKey: ["memory", "messages", threadId, agentId],
queryFn: () => threadId ? client.listThreadMessages(threadId, { agentId }) : null,
enabled: memory && Boolean(threadId),
});
};
```
--------------------------------
### Delete Thread with useDeleteThread Hook (TypeScript)
Source: https://context7.com/mastra-ai/ui-dojo/llms.txt
The `useDeleteThread` hook provides functionality to delete a memory thread. It utilizes `react-query`'s `useMutation` hook for handling mutations and `useQueryClient` for cache invalidation. The mutation function takes `threadId` and `agentId` to identify and delete the thread. On successful deletion, it invalidates the 'memory threads' query to refresh the list.
```typescript
import { useMutation, useQueryClient } from "@tanstack/react-query";
export const useDeleteThread = () => {
const client = useMastraClient();
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ threadId, agentId }) => {
const thread = client.getMemoryThread({ threadId, agentId });
return thread.delete();
},
onSuccess: (_, { agentId }) => {
queryClient.invalidateQueries({ queryKey: ["memory", "threads", agentId, agentId] });
},
});
};
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.