chat-agent-toolkit 1.2.49 → 1.2.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -18,6 +18,7 @@ export * from './memory';
18
18
  export * from './tools';
19
19
  export { AGENT_TOOLS } from './tools';
20
20
  export * from './utils';
21
+ export * from './mastra';
21
22
  export { configManager, ModelRegistry, getEnv, getModelProvidersUIConfigSection } from './config';
22
23
  export type { Config, ConfigModelProvider, MCPServerConfig, UIConfigSections, Model, ModelWithProvider } from './config';
23
24
  export { cropProvider, cropProviderAsBlob, cropProviderAsDataURL, getProviderImage, getProviderNames } from './utils/provider-image-cropper';
@@ -0,0 +1,72 @@
1
+ import { Agent } from '@mastra/core/agent';
2
+ import { z } from 'zod';
3
+ export interface MastraAgentConfig {
4
+ id: string;
5
+ name: string;
6
+ instructions: string;
7
+ model: any;
8
+ tools?: Record<string, any>;
9
+ maxSteps?: number;
10
+ memory?: {
11
+ enabled: boolean;
12
+ threadId?: string;
13
+ userId?: string;
14
+ };
15
+ }
16
+ /**
17
+ * Create a Mastra agent with full configuration.
18
+ * Supports tool-calling, multi-step reasoning, and memory.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import { createMastraAgent } from "chat-agent-toolkit/mastra";
23
+ * import { openai } from "@ai-sdk/openai";
24
+ *
25
+ * const agent = createMastraAgent({
26
+ * id: "research-assistant",
27
+ * name: "Research Assistant",
28
+ * instructions: "Help users research topics thoroughly.",
29
+ * model: openai("gpt-4o"),
30
+ * tools: { webSearch, extractPage },
31
+ * });
32
+ *
33
+ * const result = await agent.generate("What is RAG?");
34
+ * ```
35
+ */
36
+ export declare function createMastraAgent(config: MastraAgentConfig): Agent;
37
+ /**
38
+ * Create a Mastra agent with inline tool definitions using Zod schemas.
39
+ * Convenience wrapper for quick prototyping.
40
+ *
41
+ * @example
42
+ * ```ts
43
+ * const agent = createToolAgent({
44
+ * id: "calculator",
45
+ * name: "Calculator",
46
+ * instructions: "Perform math operations.",
47
+ * model: openai("gpt-4o"),
48
+ * toolDefs: [{
49
+ * id: "add",
50
+ * description: "Add two numbers",
51
+ * inputSchema: z.object({ a: z.number(), b: z.number() }),
52
+ * outputSchema: z.object({ result: z.number() }),
53
+ * execute: async ({ context }) => ({ result: context.a + context.b }),
54
+ * }],
55
+ * });
56
+ * ```
57
+ */
58
+ export declare function createToolAgent(config: {
59
+ id: string;
60
+ name: string;
61
+ instructions: string;
62
+ model: any;
63
+ toolDefs: Array<{
64
+ id: string;
65
+ description: string;
66
+ inputSchema: z.ZodType;
67
+ outputSchema: z.ZodType;
68
+ execute: (params: {
69
+ context: any;
70
+ }) => Promise<any>;
71
+ }>;
72
+ }): Agent;
@@ -0,0 +1,63 @@
1
+ /**
2
+ * @fileoverview Mastra Evals
3
+ *
4
+ * Scorer-based evaluation functions for LLM outputs.
5
+ * Assess factuality, relevance, coherence, and safety.
6
+ */
7
+ export interface EvalResult {
8
+ score: number;
9
+ reason: string;
10
+ }
11
+ export interface EvalSuiteResult {
12
+ overall: number;
13
+ results: Record<string, EvalResult>;
14
+ }
15
+ /**
16
+ * Evaluate factuality/groundedness of a response.
17
+ * Checks whether the output references sources or evidence.
18
+ *
19
+ * @example
20
+ * ```ts
21
+ * const result = await factualityEval(
22
+ * "The earth orbits the sun (source: NASA).",
23
+ * "What does the earth orbit?"
24
+ * );
25
+ * // { score: 0.9, reason: "Response includes source attribution." }
26
+ * ```
27
+ */
28
+ export declare function factualityEval(output: string, _query?: string, sources?: string[]): Promise<EvalResult>;
29
+ /**
30
+ * Evaluate relevance of a response to the query.
31
+ * Uses keyword overlap and length heuristics.
32
+ */
33
+ export declare function relevanceEval(output: string, query: string): Promise<EvalResult>;
34
+ /**
35
+ * Evaluate coherence and structure of a response.
36
+ * Checks sentence structure, paragraph flow, and logical markers.
37
+ */
38
+ export declare function coherenceEval(output: string): Promise<EvalResult>;
39
+ /**
40
+ * Evaluate output for toxic or harmful content.
41
+ * Basic keyword/pattern-based detection.
42
+ */
43
+ export declare function toxicityEval(output: string): Promise<EvalResult>;
44
+ /**
45
+ * Run a full evaluation suite against a response.
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const results = await runEvalSuite({
50
+ * output: agentResponse,
51
+ * query: "What is photosynthesis?",
52
+ * sources: ["Biology textbook chapter 3"],
53
+ * });
54
+ *
55
+ * console.log(results.overall); // 0.78
56
+ * console.log(results.results.factuality.score); // 0.85
57
+ * ```
58
+ */
59
+ export declare function runEvalSuite(params: {
60
+ output: string;
61
+ query?: string;
62
+ sources?: string[];
63
+ }): Promise<EvalSuiteResult>;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @fileoverview Mastra Integration Module
3
+ *
4
+ * Full-featured Mastra AI framework integration providing agents, workflows,
5
+ * RAG, evals, telemetry, and model routing. Built on @mastra/core with
6
+ * Vercel AI SDK compatibility.
7
+ *
8
+ * @module mastra
9
+ */
10
+ export { createMastraAgent, createToolAgent, type MastraAgentConfig } from './agents';
11
+ export { createWorkflowStep, createResearchWorkflow, createRAGWorkflow, type WorkflowStepConfig, } from './workflows';
12
+ export { MastraRAG, createRAGPipeline, type RAGConfig, type RAGDocument, type RAGChunk, type RAGRetrievalResult, } from './rag';
13
+ export { factualityEval, relevanceEval, coherenceEval, toxicityEval, runEvalSuite, type EvalResult, type EvalSuiteResult, } from './evals';
14
+ export { createMastraInstance, type MastraInstanceConfig, type TelemetryConfig, } from './telemetry';
15
+ export { createModelRouter, loadMastraModel, type ModelRouterConfig, type RoutingStrategy, } from './model-routing';
@@ -0,0 +1,65 @@
1
+ import { Agent } from '@mastra/core/agent';
2
+ export type RoutingStrategy = "cost" | "latency" | "capability" | "round-robin";
3
+ export interface ModelRouterConfig {
4
+ providers: Array<{
5
+ id: string;
6
+ model: any;
7
+ costPer1kTokens?: number;
8
+ avgLatencyMs?: number;
9
+ capabilities?: string[];
10
+ priority?: number;
11
+ }>;
12
+ strategy: RoutingStrategy;
13
+ fallbackProviderId?: string;
14
+ }
15
+ /**
16
+ * Model router that selects providers based on configurable strategies.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { createModelRouter } from "chat-agent-toolkit/mastra";
21
+ * import { openai } from "@ai-sdk/openai";
22
+ * import { anthropic } from "@ai-sdk/anthropic";
23
+ *
24
+ * const router = createModelRouter({
25
+ * providers: [
26
+ * { id: "openai", model: openai("gpt-4o"), costPer1kTokens: 0.005 },
27
+ * { id: "anthropic", model: anthropic("claude-sonnet-4-20250514"), costPer1kTokens: 0.003 },
28
+ * { id: "fast", model: openai("gpt-4o-mini"), costPer1kTokens: 0.0002, avgLatencyMs: 200 },
29
+ * ],
30
+ * strategy: "cost",
31
+ * });
32
+ *
33
+ * const model = router.select(); // cheapest provider
34
+ * const model2 = router.select({ capabilities: ["vision"] }); // capability match
35
+ * ```
36
+ */
37
+ export declare function createModelRouter(config: ModelRouterConfig): {
38
+ select(options?: {
39
+ capabilities?: string[];
40
+ maxCost?: number;
41
+ maxLatency?: number;
42
+ }): any;
43
+ createAgent(agentConfig: {
44
+ id: string;
45
+ name: string;
46
+ instructions: string;
47
+ tools?: Record<string, any>;
48
+ }, routingOptions?: {
49
+ capabilities?: string[];
50
+ maxCost?: number;
51
+ maxLatency?: number;
52
+ }): Agent;
53
+ };
54
+ /**
55
+ * Load a Mastra-compatible model from a provider string.
56
+ * Convenience wrapper around Vercel AI SDK provider imports.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const model = await loadMastraModel("openai", "gpt-4o");
61
+ * const model2 = await loadMastraModel("anthropic", "claude-sonnet-4-20250514");
62
+ * const model3 = await loadMastraModel("groq", "llama-3.3-70b-versatile");
63
+ * ```
64
+ */
65
+ export declare function loadMastraModel(provider: "openai" | "anthropic" | "groq" | "google", modelId: string): Promise<any>;
@@ -0,0 +1,83 @@
1
+ /**
2
+ * @fileoverview Mastra RAG (Retrieval-Augmented Generation)
3
+ *
4
+ * Document processing, chunking, embedding, and vector-store retrieval.
5
+ * Uses Vercel AI SDK embeddings with pluggable vector backends.
6
+ */
7
+ export interface RAGConfig {
8
+ embeddingModel: any;
9
+ chunkSize?: number;
10
+ chunkOverlap?: number;
11
+ topK?: number;
12
+ }
13
+ export interface RAGDocument {
14
+ id: string;
15
+ content: string;
16
+ metadata?: Record<string, any>;
17
+ }
18
+ export interface RAGChunk {
19
+ id: string;
20
+ documentId: string;
21
+ text: string;
22
+ embedding: number[];
23
+ metadata?: Record<string, any>;
24
+ }
25
+ export interface RAGRetrievalResult {
26
+ chunk: RAGChunk;
27
+ score: number;
28
+ }
29
+ /**
30
+ * In-memory RAG pipeline with document chunking, embedding, and retrieval.
31
+ * For production, swap the vector store with Pinecone, Qdrant, or pgvector.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * import { MastraRAG } from "chat-agent-toolkit/mastra";
36
+ * import { openai } from "@ai-sdk/openai";
37
+ *
38
+ * const rag = new MastraRAG({
39
+ * embeddingModel: openai.embedding("text-embedding-3-small"),
40
+ * chunkSize: 512,
41
+ * topK: 5,
42
+ * });
43
+ *
44
+ * await rag.ingest([
45
+ * { id: "doc1", content: "Long document text..." },
46
+ * ]);
47
+ *
48
+ * const results = await rag.retrieve("What is the main topic?");
49
+ * ```
50
+ */
51
+ export declare class MastraRAG {
52
+ private config;
53
+ private chunks;
54
+ constructor(config: RAGConfig);
55
+ /**
56
+ * Split text into overlapping chunks of configured size.
57
+ */
58
+ private splitIntoChunks;
59
+ /**
60
+ * Ingest documents: chunk, embed, and store.
61
+ */
62
+ ingest(documents: RAGDocument[]): Promise<number>;
63
+ /**
64
+ * Retrieve relevant chunks for a query using cosine similarity.
65
+ */
66
+ retrieve(query: string): Promise<RAGRetrievalResult[]>;
67
+ /**
68
+ * Retrieve and format context string for LLM consumption.
69
+ */
70
+ getContext(query: string): Promise<string>;
71
+ /**
72
+ * Get total chunk count in the store.
73
+ */
74
+ get size(): number;
75
+ /**
76
+ * Clear all stored chunks.
77
+ */
78
+ clear(): void;
79
+ }
80
+ /**
81
+ * Factory for creating a configured RAG pipeline.
82
+ */
83
+ export declare function createRAGPipeline(config: RAGConfig): MastraRAG;
@@ -0,0 +1,35 @@
1
+ import { Mastra } from '@mastra/core';
2
+ export interface TelemetryConfig {
3
+ serviceName: string;
4
+ enabled?: boolean;
5
+ sampling?: number;
6
+ exporterUrl?: string;
7
+ }
8
+ export interface MastraInstanceConfig {
9
+ agents?: Record<string, any>;
10
+ workflows?: Record<string, any>;
11
+ telemetry?: TelemetryConfig;
12
+ storage?: any;
13
+ }
14
+ /**
15
+ * Create a fully configured Mastra instance with agents, workflows,
16
+ * and telemetry. Central entry point for Mastra framework setup.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * import { createMastraInstance } from "chat-agent-toolkit/mastra";
21
+ *
22
+ * const mastra = createMastraInstance({
23
+ * agents: { assistant, researcher },
24
+ * workflows: { researchWorkflow },
25
+ * telemetry: {
26
+ * serviceName: "my-app",
27
+ * enabled: true,
28
+ * },
29
+ * });
30
+ *
31
+ * const agent = mastra.getAgent("assistant");
32
+ * const result = await agent.generate("Hello");
33
+ * ```
34
+ */
35
+ export declare function createMastraInstance(config: MastraInstanceConfig): Mastra;
@@ -0,0 +1,79 @@
1
+ import { z } from 'zod';
2
+ export interface WorkflowStepConfig<TInput = any, TOutput = any> {
3
+ id: string;
4
+ inputSchema: z.ZodType<TInput>;
5
+ outputSchema: z.ZodType<TOutput>;
6
+ execute: (params: {
7
+ inputData: TInput;
8
+ }) => Promise<TOutput>;
9
+ }
10
+ /**
11
+ * Create a typed workflow step.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const fetchStep = createWorkflowStep({
16
+ * id: "fetch-sources",
17
+ * inputSchema: z.object({ query: z.string() }),
18
+ * outputSchema: z.object({ sources: z.array(z.string()) }),
19
+ * execute: async ({ inputData }) => {
20
+ * const sources = await searchWeb(inputData.query);
21
+ * return { sources };
22
+ * },
23
+ * });
24
+ * ```
25
+ */
26
+ export declare function createWorkflowStep<TInput, TOutput>(config: WorkflowStepConfig<TInput, TOutput>): import('@mastra/core/workflows').Step<string, unknown, TInput, TOutput, unknown, unknown, import('@mastra/core/workflows').DefaultEngineType, unknown>;
27
+ /**
28
+ * Create a research workflow: fetch → analyze → summarize.
29
+ * Pre-built pipeline for common research tasks.
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * const workflow = createResearchWorkflow({
34
+ * fetchFn: async (topic) => fetchSources(topic),
35
+ * analyzeFn: async (sources) => analyzeContent(sources),
36
+ * summarizeFn: async (analysis) => generateSummary(analysis),
37
+ * });
38
+ *
39
+ * const run = await workflow.createRunAsync();
40
+ * const result = await run.start({ inputData: { topic: "quantum computing" } });
41
+ * ```
42
+ */
43
+ export declare function createResearchWorkflow(handlers: {
44
+ fetchFn: (topic: string) => Promise<string[]>;
45
+ analyzeFn: (sources: string[]) => Promise<string>;
46
+ summarizeFn: (analysis: string) => Promise<string>;
47
+ }): import('@mastra/core/workflows').Workflow<import('@mastra/core/workflows').DefaultEngineType, import('@mastra/core/workflows').Step<string, unknown, unknown, unknown, unknown, unknown, any, unknown>[], "research-workflow", unknown, {
48
+ topic: string;
49
+ }, {
50
+ summary: string;
51
+ }, {
52
+ summary: string;
53
+ }, unknown>;
54
+ /**
55
+ * Create a RAG workflow: chunk → embed → retrieve → generate.
56
+ * End-to-end retrieval-augmented generation pipeline.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * const workflow = createRAGWorkflow({
61
+ * chunkFn: async (doc) => splitIntoChunks(doc),
62
+ * embedFn: async (chunks) => embedChunks(chunks),
63
+ * retrieveFn: async (query) => findRelevant(query),
64
+ * generateFn: async (context, query) => llmGenerate(context, query),
65
+ * });
66
+ * ```
67
+ */
68
+ export declare function createRAGWorkflow(handlers: {
69
+ chunkFn: (document: string) => Promise<string[]>;
70
+ embedFn: (chunks: string[]) => Promise<number[][]>;
71
+ retrieveFn: (query: string) => Promise<string[]>;
72
+ generateFn: (context: string[], query: string) => Promise<string>;
73
+ }): import('@mastra/core/workflows').Workflow<import('@mastra/core/workflows').DefaultEngineType, import('@mastra/core/workflows').Step<string, unknown, unknown, unknown, unknown, unknown, any, unknown>[], "rag-workflow", unknown, {
74
+ query: string;
75
+ }, {
76
+ answer: string;
77
+ }, {
78
+ answer: string;
79
+ }, unknown>;