Giới Thiệu AI Research Agent
Nghiên cứu học thuật di chuyển nhanh — bài báo mới xuất hiện mỗi ngày trên arXiv và pre-print server khác. Theo dõi thủ công có thể overwhelming. Trong hướng dẫn này, chúng ta sẽ xây dựng một AI research assistant mà:
- Hiểu câu hỏi ngôn ngữ tự nhiên của researcher
- Tìm bài báo relevant nhất trong vector database của arXiv abstracts
- Tóm tắt key insight và giải thích cách chúng trả lời câu hỏi
- Cung cấp link PDF trực tiếp để đọc sâu hơn
Chúng ta sẽ hoàn thành điều này với Mastra, framework TypeScript open-source để xây dựng AI agent, và Upstash cho Redis serverless và Vector storage. Đây là demo trực tiếp của article agent tập trung vào AI research. Nó được deploy trên Vercel để bạn thử.

Mastra Là Gì?
Mastra là framework batteries-included làm cho việc tạo production-grade AI agent trở nên đơn giản.
- Agents & Workflows — Compose agent, tool, và multi-step workflow
- Retrieval-Augmented Generation (RAG) - Built-in memory và vector stores
- Multi-LLM - Hoạt động với OpenAI, Claude và hơn nữa.
Chúng ta sẽ tạo agent dùng Upstash Redis cho memory. Nó cũng sẽ có tool tìm bài báo research relevant, mà chúng ta sẽ đã embedded trước đó vào Upstash Vector database.
Để deep dive, xem tài liệu Mastra.
Tech Stack Cho Dự Án
- Mastra Framework để tạo AI agent và tool
- Upstash Redis để cho conversation memory cho agent
- Upstash Vector để lưu embedding của research article abstracts
- Next.js & Vercel để build và deploy web application
Chúng ta cũng sẽ dùng Upstash Ratelimit để limit request cho demo app.
Implementation Walkthrough
Xây dựng ứng dụng này liên quan đến tạo hai component chính: Mastra server và web application. Mặc dù chúng có thể ở cùng project, nhưng clean hơn để tách riêng. Hãy bắt đầu với Mastra server.
Tạo Mastra Project
Để tạo Mastra project mới, chạy lệnh sau trong terminal.
npm create mastra@latest
Nó sẽ hỏi vài câu hỏi; cho project này, default settings ổn.
Tạo Agent Và Tool
Bước đầu cấu hình agent là định nghĩa name, purpose, và tool. Cũng quan trọng là chọn language model perform tốt cho task. Trong project này, chúng ta sẽ có một agent và một tool.
export const articleAgent = new Agent({ name: "articleAgent", instructions: instruction, model: openai('gpt-4o'), tools: { articleQueryTool }, memory: memory });
Cấu hình agent đơn giản như trên. Chúng ta định nghĩa articleAgent với instruction (làm system prompt), tools dedicated, model, và component quan trọng khác: memory.
Memory Của Agent
Mastra cung cấp agent cả chat history và semantic recall capability. Bằng cách maintain memory trong storage, agent có thể cung cấp câu trả lời personalized và accurate hơn. Hãy xem cấu hình memory của agent.
export const memory = new Memory({ storage: myUpstashStore, options: { lastMessages: 10, semanticRecall: false, threads: { generateTitle: true } } });
Để enable chat history, chúng ta dùng Upstash Redis làm storage option. Chúng ta khởi tạo nó như object UpstashStore, extend MastraStorage, đảm bảo nó work seamlessly với Mastra agent.
export const myUpstashStore = new UpstashStore({ url: process.env.UPSTASH_REDIS_REST_URL!, token: process.env.UPSTASH_REDIS_REST_TOKEN!, });
Chúng ta đã nhắc thêm semantic recall feature cho agent, cho phép nó xem xét message trước liên quan đến context hiện tại. Cho đó, agent cần vector database và embedder để process message. Vì demo public không dùng cho personal use và không cần nhớ message cross thread, chúng ta không dùng feature này, nhưng có thể implement như sau.
export const myUpstashVector = new UpstashVector({ url: process.env.UPSTASH_VECTOR_REST_URL!, token: process.env.UPSTASH_VECTOR_REST_TOKEN!, }); export const memory = new Memory({ storage: myUpstashStore, vector: myUpstashVector, embedder: openai.embedding("text-embedding-3-small"), options: { lastMessages: 10, semanticRecall: { topK: 3, messageRange: 2, scope: 'resource' }, threads: { generateTitle: true } } });
Trong cấu hình semantic recall, topK chỉ định số message similar để retrieve, messageRange định nghĩa bao nhiêu surrounding context để include với mỗi match, và set scope thành 'resource' làm cho agent search qua tất cả thread associated với user tên 'resource'. Cross-thread memory này là powerful available với Upstash.
Tools
Tạo tool gần như đơn giản như tạo agent. Chúng ta cung cấp name, description, input/output schema, và function execute khi agent cần capability của tool.
export const articleQueryTool = createTool({ id: 'get-relevant-article', description: 'Get relevant article information', inputSchema: z.object({ question: z.string().describe('the question about the field'), }), outputSchema: z.object({ bestOption: z.object({ abstract: z.string().describe('the abstract of the article'), title: z.string().describe('the title of the article'), pdfUrl: z.string().describe('the PDF URL of the article') }) }), execute: async ({ context }) => { return await querySimilar(context.question); }, });
Chúng ta dùng Zod để validate input/output schema. Điều này giúp maintain consistent response và minimize potential error từ LLM. Chúng ta cũng define function cho tool dùng. Tool sẽ query collection lớn research article, cập nhật định kỳ qua arXiv API và embedded trong Upstash Vector database.
const querySimilar = async (query: string) => { const { embedding } = await embed({ value: query, model: openai.embedding("text-embedding-3-small"), }); const results = await myMastraUpstashVector.query({ indexName: "arxiv", queryVector: embedding, topK: 3, }); if (results && results.length > 0) { const bestMatch = results[0]; const metadata = bestMatch.metadata as ArxivPaper; return { bestOption: { abstract: metadata.abstract, title: metadata.title, pdfUrl: metadata.pdfUrl } }; } throw new Error("No relevant information found"); }
Chúng ta có thể perform simple operation trên vector database qua instance UpstashVector, extend MastraVector. Trên, chúng ta query cho article abstract similar đã embedded trước và return best result cho tool. Lưu ý chúng ta dùng cùng embedding model cho query như cho article. Chúng ta sẽ giải thích article embedding chi tiết hơn sau.
Mastra Instance
export const mastra = new Mastra({ storage: myMastraUpstashStore, agents: { articleAgent }, deployer: new VercelDeployer() });
Chỉ cần chỉ định agent nào dùng, và object Mastra sẵn sàng. Chúng ta cũng cung cấp storage để persist data beyond in-memory. Bạn cũng có thể chọn từ deployment config available; chúng ta sẽ deploy dùng Vercel.
Với default options từ create-mastra-app, chúng ta đã có file structure cần thiết:
. └── mastra ├── agents │ └── index.ts ├── tools │ └── index.ts └── index.ts
Chỉ còn một bước trước khi deploy: environment variables.
OPENAI_API_KEY= UPSTASH_VECTOR_REST_URL= UPSTASH_VECTOR_REST_TOKEN= UPSTASH_REDIS_REST_URL= UPSTASH_REDIS_REST_TOKEN=
Đặt đây trong file .env.local cho local development và thêm vào deployment environment.
Bây giờ sẵn sàng build và deploy Mastra server.
npm run build && vercel --prod
Bạn có thể check Vercel documentation để xem cách deploy.
Khi developing, chúng ta có thể dùng Mastra Playground xem output của server. Chạy lệnh sau:
npm run dev
Điều này cung cấp link đến web interface nơi bạn chat với agent, chạy tool explicitly, và explore capability của server.
Bây giờ đến phần còn lại của ứng dụng.
Next.js Server
Một khi Mastra server setup xong, chúng ta cần handle ba thứ: UI, communication với Mastra server, và article service nói chuyện với arXiv API và embed abstract vào Upstash Vector. Mastra có client SDK để expose server functionality. Qua nó, bạn có thể access agent, tool, memory, và hơn. Usage đơn giản, nhưng chúng ta sẽ share vài ví dụ. Cho detail, check documentation here. Trong project Next.js, bạn đơn giản install và dùng client SDK.
npm install @mastra/client-js@latest
Trong code, tạo instance MastraClient để dùng trong project.
import { MastraClient } from "@mastra/client-js"; export const mastra_sdk = new MastraClient({ baseUrl: process.env.NEXT_PUBLIC_MASTRA_API!, retries: 3, });
Bạn cần set NEXT_PUBLIC_MASTRA_API thành address của Mastra server. Nếu develop locally, đây sẽ là address localhost. Vì có thể port conflict trên 3000, bạn có thể thay đổi config Mastra server khi chạy locally, như sau:
export const mastra = new Mastra({ storage: myMastraUpstashStore, agents: { articleAgent }, server: { port: 4111, timeout: 10000, } });
Bây giờ, khi chạy Mastra server locally với npm run dev, nó served tại port 4111. Chúng ta có thể set NEXT_PUBLIC_MASTRA_API thành https://localhost:4111 khi chạy Next.js project locally.
Hãy xem cách dùng Mastra client SDK.
export const MASTRA_CONFIG = { resourceId: process.env.NEXT_PUBLIC_RESOURCE_ID || "articleAgent", agentId: "articleAgent", baseUrl: process.env.NEXT_PUBLIC_MASTRA_API || "https://localhost:4111", retries: 3, }; // this is exported in another file so that we can use it anywhere in the codebase. // Get your agent and simply stream your response through your agent object. const agent = mastra_sdk.getAgent(MASTRA_CONFIG.agentId); const response = await agent.stream({ messages: [message], resourceId: MASTRA_CONFIG.resourceId, threadId: threadId });
Bạn có thể get tool và agent, và khi có chúng, bạn có thể làm gần như mọi thứ bạn làm với object thực qua client SDK.
Vì chúng ta sẽ publish demo project công khai, quan trọng là tránh heavy load trên agent. Đây là nơi Upstash Ratelimit xuất hiện. Trước mọi stream request, chúng ta sẽ check nếu user bị rate-limited. Để config rate limiter, chúng ta cần Upstash Redis. Chúng ta có thể dùng cùng Redis database cho Mastra agent.
import { Ratelimit } from '@upstash/ratelimit'; import { Redis } from '@upstash/redis'; // Using the same Redis DB across the project export const rateLimit = new Ratelimit({ redis: new Redis({ url: process.env.UPSTASH_REDIS_MEMORY_URL!, token: process.env.UPSTASH_REDIS_MEMORY_TOKEN! }), limiter: Ratelimit.slidingWindow(10, '10s'), prefix: 'upstash-ratelimit', }); // Fetch the below function before every stream. export async function isRateLimited(id: string): Promise<boolean> { const { success } = await rateLimit.limit(id); return !success; }
Cách này, chúng ta đảm bảo endpoint không bị heavy load.
Khi tạo chat agent với Mastra, biết một số feature của thread generation Mastra có thể helpful. Nhớ khi cấu hình memory cho agent, chúng ta set generateTitle thành true trong object threads. Điều này làm Mastra tự động generate title cho thread mới tạo. Nhưng có cái catch: có thể tạo thread explicitly, nhưng automatic title generation không triggered cách đó. Thông thường, cách tạo thread mới là:
const thread = await mastraClient.createMemoryThread({ title: "New Conversation", metadata: { category: "support" }, resourceId: "resource-1", agentId: "agent-1", });
Tuy nhiên, điều này cướp đi khả năng generate title tự động của agent, vì bạn set nó manually. Để trống field title cũng không work. Trong trường hợp này, xem Playground làm gì. Nhớ Playground, do Mastra cung cấp để experience capability của server khi developing? Nếu inspect network tab trong devtools, chúng ta thấy khi thread mới tạo, nó không send API request tạo nó. Thay vào đó, nó chờ bạn submit first message. Sau đó, nó send stream request với thread ID mới generate. Điều này báo cho Mastra rằng không thread nào tồn tại với ID này, nên nó nên tạo một và, nếu generateTitle true, generate title dựa trên first message.
Tiếp tục với component cuối của project: arXiv articles.
arXiv Articles
arXiv là open-access archive gần 2.4 triệu research article ở nhiều lĩnh vực. articleQueryTool query Upstash Vector database, được feed bởi article fetched qua arXiv API. API đơn giản để dùng; tìm detail hơn ở đây.
Trong project, chúng ta fetch và store article hàng ngày. Lần đầu server chạy, nó fetch khoảng 30,000 article từ category chỉ định. Sau đó, nó fetch article mới publish ngày trước. Để chỉ định category article và có fetch initial large batch không, set environment variable tương ứng. Chúng ta nên provide category mong muốn dùng taxonomy arXiv, cách nhau bởi dấu phẩy. Bạn có thể lookup category ở đây.
CATEGORIES=cs.AI RUN_BEGINNING_STACK=false
Nếu bạn muốn database comprehensive hơn, dùng bulk data access của arXiv. Không có nó, chúng ta limited 30,000 article per API query, đủ cho mục đích.
Simple query đến arXiv trông như này:
const categories = process.env.CATEGORIES?.split(',') || []; // Get the desired categories and split them for the query. const searchQuery = categories.length === 1 ? `cat:${categories[0]}` : `(${categories.map(c => `cat:${c}`).join(" OR ")})`; const query = `search_query=${searchQuery}&sortBy=submittedDate&sortOrder=descending`; const url = `https://export.arxiv.org/api/query?${query}`; const response = await axios.get(url); // Make the API call with the constructed URL.
Chúng ta làm similar call để get latest article mỗi ngày và fetch initial stack.
Sau khi fetch article, chúng ta normalize và embed để lưu trong Upstash Vector. Phải là cùng vector database mà Mastra tool dùng. "Normalize" nghĩa là parse fetched article thành standard type ArxivPaper, dùng xuyên suốt codebase.
export interface ArxivPaper { id: string; title: string; abstract: string; authors: string[]; published: string; pdfUrl: string; category: string; }// The type for our articles, across our codebase. async function storeAbstracts(papers: ArxivPaper[]) { const embeddingModel = openai.embedding("text-embedding-3-small"); // The same model used to query on the Mastra side. const embeddings = await embedArticles(papers, embeddingModel) // Put the embeddings into the required form with their metadata. const vectorsToUpsert = getVectorsToUpsert(embeddings, papers) for (let j = 0; j < vectorsToUpsert.length; j++) { await vectorStore.upsert(vectorsToUpsert[j], { namespace: "arxiv" }); // Upsert the embeddings with their metadata to Upstash Vector. } }
Để đảm bảo database cập nhật với research mới, chúng ta implement Upstash QStash cho scheduled task execution. Với deployment trên Vercel, cần prevent function timeout có thể xảy ra với extended processing interval. Chúng ta address bằng cách expose public API endpoint trên server, cho QStash instance trigger daily database update function reliably.
// src/app/api/arxiv_reneval/route.ts import { verifySignatureAppRouter } from "@upstash/qstash/nextjs" import { fetchAndUpsertYesterday} from "@/services/arxiv" async function handler(request: Request) { console.log("Fetching and upserting yesterday's papers...") await fetchAndUpsertYesterday() console.log("Fetching and upserting yesterday's papers completed") return Response.json({ success: true }) } export const POST = verifySignatureAppRouter(handler)
Scheduler có thể cấu hình qua Upstash Console để tự động trigger request đến endpoint này hàng ngày 6:00 AM UTC.

Với scheduler config này, server sẽ perform automated database update mỗi sáng, đảm bảo data freshness liên tục.
Chúng ta cũng nên cung cấp credential cho QStash instance, all required env variables cho trong example env file.
Đó là hầu như xong. Nếu bạn muốn, thử chơi với code. Chỉ fork repositories và bắt đầu develop. Bạn vào Mastra part repo ở đây và repo kia ở đây. Sau khi fork:
- Clone về local machine.
- Điền environment variables (example
.envfile provided). - Đi đến root directory cho cả hai project trong terminal riêng.
- Chạy lệnh:
npm install npm run dev
Bây giờ bạn thấy ứng dụng tại https://localhost:3000.
Với Mastra, bạn có thể xây dựng thứ phức tạp hơn bằng cách dùng template khác như RAG, workflows, và networks. Có vẻ memory và storage đóng vai trò quan trọng trong tất cả mục đích này. Đây là nơi Upstash tỏa sáng.