Skip to content
reaatechREAATECH

Files · xAI Grok Knowledge Agent for SMB HR Policy Q&A

69 (1 binary, 528.5 kB total)attempt 1

README.md·6101 B·markdown
markdown
# xAI Grok Knowledge Agent for SMB HR Policy Q&A
 
> Empower employees to self‑serve PTO, benefits, and handbook questions with a Grok‑backed agent that remembers policy contexts across sessions.
 
A tutorialized reference solution from [reaatech.com](https://reaatech.com), demonstrating how to build production-grade AI systems with the `@reaatech/*` package family.
 
## Architecture
 
```
┌──────────────┐     ┌─────────────────────┐     ┌──────────────────┐
│  Next.js App  │────▶│  ChatService        │────▶│  GrokClient      │
│  (API Route)  │     │  (orchestrator)     │     │  (xAI API)       │
└──────────────┘     └───────┬─────────────┘     └──────────────────┘

                    ┌────────┴────────┐
                    │                 │
             ┌──────▼──────┐  ┌──────▼──────┐
             │MemoryService │  │PoliciesService│
             │(REAA memory) │  │(Qdrant vec DB)│
             └──────┬──────┘  └──────┬──────┘
                    │                 │
             ┌──────▼──────┐  ┌──────▼──────┐
             │Postgres/    │  │  Qdrant     │
             │InMemory     │  │ Vector Store│
             └─────────────┘  └─────────────┘
```
 
The agent uses `@reaatech/agent-memory-core` to persist employee-specific policy context, `@reaatech/agent-memory-storage` for memory persistence (InMemory or Postgres), `@reaatech/agent-memory-retrieval` to fetch relevant policy paragraphs from a Qdrant vector store, and `@reaatech/agent-memory-embedding` (backed by fastembed/BGE) to encode both user questions and stored policies. Grok reasoning is accessed via the OpenAI-compatible xAI API through the `openai` SDK. All structured outputs are validated with `zod`.
 
## Project layout
 
```
app/                  Next.js App Router pages + API routes
src/
  services/           Business logic: ChatService, MemoryService, PoliciesService, EmbeddingService
  lib/                Infrastructure: GrokClient, auth (JWT), observability (logging)
  types.ts            Domain types and Zod schemas
tests/
  lib/                Unit tests for lib modules
  services/           Unit tests for services
  integration/        Integration tests (full flow)
packages/             API references for every dependency (read these first)
```
 
## Prerequisites
 
- Node.js >= 22
- pnpm 10
- An xAI API key (for Grok access) — set `XAI_API_KEY`
- A Qdrant instance (or use `http://localhost:6333`)
- Docker (for Qdrant)
- PostgreSQL 15+ with `pgvector` extension for persistent memory storage
 
## Setup
 
```bash
pnpm install
```
 
Copy `.env.example` to `.env` and fill in:
 
| Variable | Description | Default |
|---|---|---|
| `XAI_API_KEY` | xAI API key for Grok access | — |
| `QDRANT_URL` | Qdrant vector store URL | `http://localhost:6333` |
| `JWT_SECRET` | Secret for JWT token verification | — |
| `DB_HOST` | PostgreSQL host (if using Postgres) | `localhost` |
| `DB_PORT` | PostgreSQL port | `5432` |
| `DB_NAME` | PostgreSQL database name | `postgres` |
| `DB_USER` | PostgreSQL user | `postgres` |
| `DB_PASSWORD` | PostgreSQL password | — |
| `LOG_LEVEL` | Logging level | `info` |
| `OPENAI_API_KEY` | OpenAI API key (for embeddings) | — |
 
## Running
 
```bash
pnpm dev              # next dev
pnpm build            # next build
pnpm start            # next start
pnpm test             # vitest run with coverage
pnpm lint             # eslint check
pnpm typecheck        # tsc --noEmit
```
 
## API
 
### POST /api/hr/chat
 
Ask an HR policy question.
 
**Request:**
```json
{
  "employeeId": "emp-001",
  "message": "How much PTO do I have?",
  "sessionId": "session-123"
}
```
 
**Response:**
```json
{
  "answer": "You have 15 days of PTO per year.",
  "sources": [
    {
      "chunkId": "chunk-001",
      "text": "PTO policy...",
      "score": 0.95,
      "policyName": "PTO Policy"
    }
  ],
  "sessionId": "session-123"
}
```
 
**Authentication:** Requires a Bearer JWT in the `Authorization` header. The JWT must contain `employeeId`, `tenantId`, `role`, `tenure`, and `name` claims.
 
### POST /api/hr/policies
 
Ingest a handbook PDF into the policy vector store.
 
### GET /api/hr/policies
 
List indexed policy collections.
 
### DELETE /api/hr/policies
 
Remove an indexed policy collection.
 
### GET /api/hr/memories
 
Get stored memories for an employee.
 
### POST /api/hr/memories
 
Create a new memory entry for an employee.
 
## Testing
 
Tests use `vitest` with `msw` for HTTP-level mocking. All external network calls (xAI, OpenAI, Qdrant) are intercepted by MSW handlers defined in `tests/setup.ts`.
 
```bash
pnpm test    # runs vitest with coverage
```
 
Coverage thresholds: 90% lines, branches, functions, statements on `src/**/*.ts` and `app/**/route.ts`.
 
## Key packages
 
- `@reaatech/agent-memory-core@0.1.0` — Memory types, importance levels, lifecycle management
- `@reaatech/agent-memory-storage@0.1.0` — InMemoryMemoryStorage, PostgresMemoryStorage, MemoryQuery
- `@reaatech/agent-memory-retrieval@0.1.0` — MemoryRetriever, ContextInjector, RetrievalStrategy
- `@reaatech/agent-memory-embedding@0.1.0` — EmbeddingProvider interface, OpenAI/InMemory adapters
- `@qdrant/js-client-rest@1.18.0` — Qdrant vector store client
- `fastembed@2.1.0` — Local embedding (BGE-small-en-v1.5)
- `openai@4.100.0` — OpenAI-compatible SDK for xAI Grok API
- `jose@6.0.10` — JWT verification
- `zod@4.4.3` — Schema validation
- `pdf-parse@2.4.5` — PDF text extraction
 
## License
 
MIT — see [LICENSE](./LICENSE).