Skip to content
reaatech

Files · OpenAI Code Sandbox for Veterinary Practice Performance Analytics

74 (1 binary, 643.4 kB total)attempt 1

README.md·4091 B·markdown
markdown
# OpenAI Code Sandbox for Veterinary Practice Performance Analytics
 
> Secure, cost-capped AI data sandbox that lets veterinary practice managers run ad‑hoc analysis on clinic data without exposing sensitive information to external services.
 
A tutorialized reference solution from [reaatech.com](https://reaatech.com), demonstrating how to build production-grade AI systems with the `@reaatech/*` package family.
 
## Architecture
 
The system follows this flow:
 
1. **Client** sends a natural-language analytics question to `POST /api/analytics`
2. **Route handler** validates the request with Zod and delegates to the orchestration service
3. **Session continuity** (`@reaatech/session-continuity`) preserves multi-turn conversation context
4. **Budget guard** (`@reaatech/agent-budget-engine`) checks per-practice spend caps before processing
5. **Code generation** uses the OpenAI Chat Completions API to translate the question into Python/Pandas code
6. **Sandbox execution** runs the generated code in an E2B secure sandbox pre-loaded with sanitized practice data
7. **Observability** (`@reaatech/otel-genai-semconv-openai` + `@traceloop/node-server-sdk`) emits OpenTelemetry spans for every LLM call
8. **Response** is returned with execution results, token usage, and cost tracking
 
## API
 
### POST /api/analytics
 
Accepts a natural-language analytics question and returns executed Python/Pandas results.
 
**Request body:**
 
```json
{
  "question": "Show me monthly revenue for 2024",
  "practiceId": "p001",
  "sessionId": "optional-session-id-for-multi-turn"
}
```
 
**Response (200):**
 
```json
{
  "sessionId": "uuid",
  "answer": "Revenue by month:\n2024-01: $12,500\n2024-02: $14,200\n2024-03: $13,800",
  "executionLog": "",
  "usage": { "inputTokens": 50, "outputTokens": 30, "cost": 0.002, "model": "gpt-5.2-mini" }
}
```
 
**Response (429 — budget exceeded):**
 
```json
{
  "sessionId": "uuid",
  "answer": "Budget exceeded for this practice. Please try again later.",
  "executionLog": "",
  "usage": { "inputTokens": 0, "outputTokens": 0, "cost": 0, "model": "gpt-5.2-mini" }
}
```
 
**Example curl:**
 
```bash
curl -X POST http://localhost:3000/api/analytics \
  -H "Content-Type: application/json" \
  -d '{"question": "Show revenue by month", "practiceId": "p001"}'
```
 
### GET /api/analytics
 
Health check endpoint.
 
**Response (200):** `{ "status": "ok", "endpoint": "analytics" }`
 
## Environment variables
 
| Variable | Description |
|---|---|
| `OPENAI_API_KEY` | OpenAI API key |
| `E2B_API_KEY` | E2B code interpreter API key |
| `TRACELOOP_API_KEY` | Traceloop observability API key |
| `BUDGET_LIMIT` | Per-practice daily budget in USD |
| `BUDGET_SOFT_CAP` | Fraction of budget that triggers downgrade (0.0-1.0) |
| `BUDGET_HARD_CAP` | Fraction of budget that stops execution (0.0-1.0) |
| `OPENAI_MODEL` | OpenAI model ID (default: gpt-5.2-mini) |
 
## Packages
 
### REAA packages
- `@reaatech/agent-budget-engine` — Budget enforcement engine with pre-flight cost checks and per-scope state machine
- `@reaatech/session-continuity` — Typed session lifecycle manager for multi-turn conversations
- `@reaatech/otel-genai-semconv-openai` — OpenAI SDK instrumentation emitting GenAI semantic convention spans
 
### Third-party packages
- `@e2b/code-interpreter` — Secure cloud sandbox for executing AI-generated code
- `openai` — Official OpenAI TypeScript SDK
- `zod` — TypeScript-first schema validation
- `p-limit` — Promise concurrency limiter
- `dotenv` — Environment variable loader
- `@traceloop/node-server-sdk` — OpenLLMetry SDK for LLM observability
 
## Running locally
 
```bash
pnpm install
pnpm test            # vitest run with coverage
pnpm dev             # next dev
```
 
## Project layout
 
```
app/                  Next.js App Router pages + API routes
src/                  services, lib, adapters
tests/                vitest suite (mirrors src/)
packages/             API references for every dependency (read these first)
DEV_PLAN.md           build plan for this recipe
```
 
## License
 
MIT — see [LICENSE](./LICENSE).