A production-ready AI agent that safely answers data questions by querying a Postgres database, returning structured results, and rendering them in an interactive web UI. Built with Mastra framework and TypeScript, following Better Agents best practices.
- Natural Language Querying: Ask questions in plain English about your data
- Safe SQL Generation: Automatically generates and executes secure SQL queries
- Structured Results: Returns data in JSON, tables, and charts
- Interactive UI: Web-based interface for exploring results
- Multi-turn Conversations: Supports follow-up questions and query refinements
- Error Handling: Graceful handling of invalid queries and database errors
- Comprehensive Testing: End-to-end scenario tests and evaluations
- Instrumentation: Full LangWatch integration for monitoring and analytics
- Node.js 18+
- pnpm package manager
- PostgreSQL database
- API keys for:
- OpenAI (or other LLM provider)
- LangWatch
- Clone the repository:
git clone <repository-url>
cd data-analytics-agent- Install dependencies:
pnpm install- Copy environment variables:
cp .env.example .env- Fill in your API keys and database connection details in
.env:
OPENAI_API_KEY=your_openai_api_key
LANGWATCH_API_KEY=your_langwatch_api_key
DATABASE_URL=postgresql://user:password@localhost:5432/database-
Ensure your PostgreSQL database is running and accessible.
-
Install LangWatch CLI globally:
pnpm add -g @langwatch/cli- Sync prompts:
langwatch prompt syncStart the development server:
pnpm devThe agent will be available at http://localhost:3000 (or the configured port).
-
Open your browser and navigate to the agent URL
-
Ask questions in natural language, such as:
- "What are the total sales by month?"
- "Show me customers with orders over $1000"
- "What's the average order value by product category?"
-
The agent will:
- Generate a safe SQL query
- Execute it against your database
- Return structured results
- Display them in an interactive UI
The agent exposes REST endpoints for programmatic access:
// Example API call
const response = await fetch('/api/query', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
question: "What are the top 10 products by sales?"
})
});
const result = await response.json();Run end-to-end scenario tests:
pnpm test:scenariosRun unit tests with vitest:
pnpm testRun evaluation notebooks:
# Requires Jupyter
jupyter notebook tests/evaluations/├── app/ # Main application code
│ └── index.ts # Agent entry point
├── prompts/ # Versioned prompt files (YAML)
├── tests/
│ ├── evaluations/ # Jupyter notebooks for evaluations
│ └── scenarios/ # End-to-end scenario tests
├── prompts.json # Prompt registry
├── .env # Environment variables
└── AGENTS.md # Development guidelines
- Understand Requirements: Clarify what the agent should do
- Design the Approach: Plan components needed
- Implement with Prompts: Use LangWatch Prompt CLI for prompts
- Write Tests: Create scenario tests for validation
- Run Tests: Verify everything works
All prompts are managed via LangWatch Prompt CLI:
# Create a new prompt
langwatch prompt create my_new_prompt
# Edit the YAML file in prompts/
# Then sync
langwatch prompt syncThe agent expects a standard e-commerce schema. Update the prompts and agent logic if your schema differs.
Example schema:
customerstableorderstableorder_itemstableproductstable
OPENAI_API_KEY: Your OpenAI API keyLANGWATCH_API_KEY: LangWatch API key for instrumentationDATABASE_URL: PostgreSQL connection stringPORT: Server port (default: 3000)
Configure your Postgres connection in .env. The agent uses connection pooling for performance.
The agent is fully instrumented with LangWatch for:
- Query performance monitoring
- Error tracking
- Usage analytics
- Prompt optimization
Access the LangWatch dashboard at https://app.langwatch.ai/
- Follow the guidelines in
AGENTS.md - Use LangWatch Prompt CLI for prompt management
- Write scenario tests for new features
- Run all tests before submitting PRs
This project is licensed under the MIT License - see the LICENSE file for details.
- AGENTS.md - Development guidelines
- LangWatch Documentation
- Mastra Framework
- Vercel AI SDK
- Scenario Testing