Skip to content
/ codeai Public

LLM focused language that is converted into golang

License

Notifications You must be signed in to change notification settings

bargom/codeai

Repository files navigation

CodeAI

Go Version License Build Status Coverage

A Go-based runtime for defining and executing AI agent specifications using a declarative domain-specific language (DSL). CodeAI provides a structured approach to building backend services with built-in support for databases, authentication, workflows, jobs, events, and integrations.


Table of Contents


Overview

CodeAI is a declarative backend framework that allows developers and LLMs to define entire backend services using a simple, readable DSL. Instead of writing boilerplate code for APIs, database schemas, authentication, and background jobs, you describe what you want and CodeAI generates the runtime.

Key Benefits

  • Declarative DSL: Define entities, endpoints, workflows, and jobs in a human-readable format
  • LLM-Friendly: Designed to be easily understood and generated by AI assistants
  • Production-Ready Infrastructure: Built-in auth, caching, circuit breakers, retry logic, and observability
  • Type-Safe: Full validation at parse time with detailed error messages
  • Extensible: Modular architecture with pluggable integrations

Target Audience

  • LLM Agents: Generate complete backend specifications programmatically
  • Backend Developers: Rapidly prototype and build production services
  • DevOps Engineers: Deploy standardized, observable microservices
  • Startups: Accelerate time-to-market with minimal boilerplate

Project Status

Version: 1.0 | Status: 90% Complete

Component Status
Go Runtime Infrastructure Production-Ready
CLI Tool Complete
Database Module (PostgreSQL) Complete
Database Module (MongoDB) Complete
HTTP/API Module (Chi Router) Complete
Authentication (JWT/JWKS/RBAC) Complete
Caching (Redis/Memory) Complete
Workflow Engine (Temporal) Complete
Job Scheduler (Asynq) Complete
Event System Complete
Integration Layer Complete
Observability Stack Complete
DSL Parser Complete (Core language)

Quick Start

One-Line Installation

go install github.com/bargom/codeai/cmd/codeai@latest

Or Build from Source

git clone https://github.com/bargom/codeai.git
cd codeai
make build
./bin/codeai version

Basic Usage

# Parse a DSL file
./bin/codeai parse myapp.cai

# Validate syntax
./bin/codeai validate myapp.cai

# Start the API server
./bin/codeai server start --db-name codeai

# Generate shell completions
./bin/codeai completion bash > /etc/bash_completion.d/codeai

Full Quick Start Guide


Features

DSL Language

Define your backend with a clean, declarative syntax:

Feature Description
Variables var name = "value"
Control Flow if, else, for-in loops
Functions User-defined with parameters
Shell Execution exec { kubectl get pods }
Comments Single-line // and multi-line /* */

Backend Modules

Module Description Technology
Database (PostgreSQL) Relational database with migrations, repositories lib/pq
Database (MongoDB) Document database with collections, embedded docs mongo-driver
HTTP/API RESTful endpoints with Chi router go-chi/chi
Authentication JWT validation, JWKS support, RBAC golang-jwt
Caching Redis and in-memory caching go-redis
Workflows Long-running processes with compensation Temporal
Job Scheduler Cron and interval-based jobs Asynq
Events Pub/sub event system with persistence Custom
Integrations REST/GraphQL clients with resilience Custom

Built-In Patterns

Pattern Description
Circuit Breaker Prevent cascade failures with configurable thresholds
Retry with Backoff Exponential and linear retry strategies
Saga Pattern Distributed transaction compensation
Rate Limiting Request throttling per client
Request Validation Automatic input validation
Pagination Cursor and offset-based pagination

Observability

Feature Technology
Structured Logging Go slog with JSON output
Metrics Prometheus with /metrics endpoint
Health Checks /health, /ready, /live endpoints
Tracing OpenTelemetry integration
Graceful Shutdown Clean connection draining

OpenAPI Generation

Automatic OpenAPI 3.0 specification generation from your DSL definitions.


DSL Example

Blog API with REST Endpoints

CodeAI allows you to define complete backend services with database schemas, REST endpoints, middleware, and business logic:

// blog-api.cai - Complete Blog API Example

// =============================================================================
// Configuration
// =============================================================================
config {
    name: "blog-api"
    version: "1.0.0"
    database_type: "postgres"
    api_prefix: "/api/v1"
}

// =============================================================================
// Database Schema
// =============================================================================
database postgres {
    // Users table
    users {
        id         uuid primary_key default "gen_random_uuid()"
        email      varchar(255) unique not_null
        username   varchar(100) unique not_null
        name       varchar(255) not_null
        role       varchar(50) default "'user'"
        created_at timestamp default "now()"
        updated_at timestamp default "now()"
    }

    // Posts table
    posts {
        id         uuid primary_key default "gen_random_uuid()"
        user_id    uuid references "users(id)"
        title      varchar(255) not_null
        slug       varchar(255) unique not_null
        content    text not_null
        status     varchar(50) default "'draft'"
        created_at timestamp default "now()"
        updated_at timestamp default "now()"
    }
}

// =============================================================================
// REST API Endpoints
// =============================================================================

// Create a new user
endpoint POST "/users" {
    middleware rate_limit
    request CreateUser from body
    response User status 201
    do {
        validate(request)
        user = create(User, request)
        emit(user_created, user)
    }
}

// Get user by ID
endpoint GET "/users/:id" {
    request UserID from path
    response User status 200
    do {
        validate(request)
        user = find(User, id)
    }
}

// Update user (admin only)
endpoint PUT "/users/:id" {
    middleware auth
    request UpdateUser from body
    response User status 200
    do {
        validate(request)
        authorize(request, "admin")
        user = find(User, id)
        updated = update(user, request)
    }
}

// Create a blog post
endpoint POST "/posts" {
    middleware auth
    request CreatePost from body
    response Post status 201
    do {
        validate(request)
        post = create(Post, request)
        emit(post_created, post)
    }
}

// Get posts for a user (nested resource)
endpoint GET "/users/:userId/posts" {
    request UserPostsParams from query
    response PostList status 200
    do {
        validate(request)
        posts = find(Post) where "user_id = :userId"
    }
}

Parse and Run

# Parse and validate the DSL
./bin/codeai parse blog-api.cai
./bin/codeai validate blog-api.cai

# Start the API server
./bin/codeai server start --file blog-api.cai --port 8080

API Interaction

# Health check
curl http://localhost:8080/health

# Create a user
curl -X POST http://localhost:8080/api/v1/users \
  -H "Content-Type: application/json" \
  -d '{
    "email": "alice@example.com",
    "username": "alice",
    "name": "Alice Johnson",
    "role": "author"
  }'

# Get user by ID
curl http://localhost:8080/api/v1/users/550e8400-e29b-41d4-a716-446655440000

# Create a blog post (requires auth)
curl -X POST http://localhost:8080/api/v1/posts \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{
    "title": "Getting Started with CodeAI",
    "slug": "getting-started",
    "content": "CodeAI is a declarative backend framework...",
    "status": "published"
  }'

# Get user's posts
curl http://localhost:8080/api/v1/users/550e8400-e29b-41d4-a716-446655440000/posts

Architecture

┌─────────────────────────────────────────────────────────────────────────┐
│                              HTTP Layer                                  │
│  ┌───────────────────────────────────────────────────────────────────┐  │
│  │              Chi Router + Middleware Stack                         │  │
│  │  (RequestID, RealIP, Logger, Recoverer, Timeout, JSON)            │  │
│  └───────────────────────────────────────────────────────────────────┘  │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
                    ┌───────────────┼───────────────┐
                    ▼               ▼               ▼
            ┌───────────┐   ┌───────────┐   ┌───────────┐
            │   Auth    │   │  Handlers │   │  OpenAPI  │
            │Middleware │   │  (CRUD)   │   │   Docs    │
            └───────────┘   └───────────┘   └───────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                        Business Logic Layer                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │  Parser  │  │ Workflow │  │Scheduler │  │ Validator│               │
│  │  (DSL)   │  │(Temporal)│  │ (Asynq)  │  │          │               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                       Infrastructure Layer                               │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Database │  │  Event   │  │  Cache   │  │Integration│               │
│  │(Postgres)│  │   Bus    │  │ (Redis)  │  │(REST/GQL)│               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘
                                    │
┌─────────────────────────────────────────────────────────────────────────┐
│                      Cross-Cutting Concerns                              │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────┐               │
│  │ Logging  │  │ Metrics  │  │  Health  │  │ Shutdown │               │
│  │ (slog)   │  │(Promethe)│  │  Checks  │  │ Graceful │               │
│  └──────────┘  └──────────┘  └──────────┘  └──────────┘               │
└─────────────────────────────────────────────────────────────────────────┘

Directory Structure

codeai/
├── cmd/codeai/           # CLI entry point (Cobra commands)
│   └── cmd/              # parse, validate, server, deploy, config
├── internal/             # Private application code
│   ├── api/              # HTTP handlers, router, server
│   ├── ast/              # Abstract Syntax Tree definitions
│   ├── auth/             # JWT validation, JWKS, middleware
│   ├── cache/            # Redis and memory caching
│   ├── database/         # PostgreSQL, migrations, repositories
│   ├── event/            # Event bus and dispatching
│   ├── health/           # Health check endpoints
│   ├── openapi/          # OpenAPI specification generation
│   ├── pagination/       # Pagination utilities
│   ├── parser/           # DSL lexer and parser (Participle)
│   ├── query/            # Query builder and executor
│   ├── rbac/             # Role-based access control
│   ├── scheduler/        # Asynq job scheduler
│   ├── shutdown/         # Graceful shutdown handling
│   ├── validation/       # Input validation middleware
│   ├── validator/        # AST validation
│   ├── webhook/          # Webhook delivery system
│   └── workflow/         # Temporal workflow orchestration
├── pkg/                  # Public libraries
│   ├── integration/      # REST, GraphQL clients, circuit breaker
│   ├── logging/          # Structured logging utilities
│   ├── metrics/          # Prometheus metrics
│   └── types/            # Shared type definitions
├── config/               # Configuration files (YAML)
├── docs/                 # Documentation
└── test/                 # Integration and performance tests

Requirements

Required

Dependency Version Purpose
Go 1.24+ Runtime and build
PostgreSQL 14+ Primary database
Make Any Build automation

Optional

Dependency Version Purpose
MongoDB 4.4+ Document database (alternative/complement to PostgreSQL)
Redis 6+ Caching layer
Docker 20+ Containerization, integration tests
Temporal 1.20+ Workflow orchestration

Verify Installation

go version          # go1.24.0 or higher
psql --version      # PostgreSQL 14.x or higher
make --version      # GNU Make 3.81 or higher

Installation

From Source

# Clone repository
git clone https://github.com/bargom/codeai.git
cd codeai

# Install dependencies
go mod download

# Build binary
make build

# Verify installation
./bin/codeai version
./bin/codeai --help

Database Setup

# Create database
createdb codeai

# Run migrations
./bin/codeai server migrate --db-name codeai --db-user postgres

# Or with custom settings
./bin/codeai server migrate \
  --db-host localhost \
  --db-port 5432 \
  --db-name codeai \
  --db-user codeai_user \
  --db-password secret

Development

Running Tests

# All tests with race detector
make test

# Unit tests only
make test-unit

# Integration tests (requires PostgreSQL)
make test-integration

# CLI integration tests
make test-cli

# Coverage report
make test-coverage
# Open coverage.html in browser

Running Benchmarks

# All benchmarks
make bench

# Parser benchmarks
make bench-parse

# Validator benchmarks
make bench-validate

Code Quality

# Run linter
make lint

# Tidy dependencies
make tidy

# Clean build artifacts
make clean

Available Make Targets

Target Description
make build Build the application binary
make test Run all tests with race detector
make test-unit Run unit tests only
make test-integration Run integration tests
make test-coverage Generate coverage report
make bench Run benchmarks
make lint Run linters (go vet)
make clean Clean build artifacts
make tidy Tidy go modules

Contributing

See CONTRIBUTING.md for guidelines on:

  • Code style and conventions
  • Pull request process
  • Testing requirements
  • Documentation standards

Deployment

Docker

# Dockerfile
FROM golang:1.24-alpine AS builder
WORKDIR /app
COPY . .
RUN go build -ldflags "-s -w" -o codeai ./cmd/codeai

FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /app
COPY --from=builder /app/codeai .
EXPOSE 8080
CMD ["./codeai", "server", "start"]
# Build and run
docker build -t codeai:latest .
docker run -p 8080:8080 \
  -e CODEAI_DB_HOST=host.docker.internal \
  -e CODEAI_DB_NAME=codeai \
  codeai:latest

Kubernetes

# deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: codeai
spec:
  replicas: 3
  selector:
    matchLabels:
      app: codeai
  template:
    metadata:
      labels:
        app: codeai
    spec:
      containers:
      - name: codeai
        image: codeai:latest
        ports:
        - containerPort: 8080
        env:
        - name: CODEAI_DB_HOST
          valueFrom:
            secretKeyRef:
              name: codeai-secrets
              key: db-host
        - name: CODEAI_DB_PASSWORD
          valueFrom:
            secretKeyRef:
              name: codeai-secrets
              key: db-password
        livenessProbe:
          httpGet:
            path: /health
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 10
        readinessProbe:
          httpGet:
            path: /ready
            port: 8080
          initialDelaySeconds: 5
          periodSeconds: 5
---
apiVersion: v1
kind: Service
metadata:
  name: codeai
spec:
  selector:
    app: codeai
  ports:
  - port: 80
    targetPort: 8080
  type: ClusterIP

Full Deployment Guide


Documentation

Document Description
Quick Start Get up and running in minutes
DSL Language Spec Complete language reference
DSL Cheatsheet Quick syntax reference
Database Guide PostgreSQL and MongoDB configuration
Architecture System design and module details
API Reference HTTP API documentation
Workflows & Jobs Background processing guide
Integration Patterns External service integration
Observability Logging, metrics, and tracing
Testing Testing strategies and examples
Deployment Production deployment guide
Troubleshooting Common issues and solutions
Migration Guide Version upgrade instructions
Contributing Contribution guidelines
Implementation Status Current feature status

Environment Variables

Variable Default Description
CODEAI_DB_HOST localhost PostgreSQL host
CODEAI_DB_PORT 5432 PostgreSQL port
CODEAI_DB_NAME codeai Database name
CODEAI_DB_USER postgres Database user
CODEAI_DB_PASSWORD (empty) Database password
CODEAI_DB_SSLMODE disable SSL mode
CODEAI_MONGODB_URI (empty) MongoDB connection URI
CODEAI_MONGODB_DATABASE (empty) MongoDB database name
CODEAI_SERVER_HOST localhost Server bind host
CODEAI_SERVER_PORT 8080 Server bind port
CODEAI_REDIS_URL (empty) Redis connection URL
CODEAI_JWT_SECRET (empty) JWT signing secret
CODEAI_JWKS_URL (empty) JWKS endpoint URL

License

This project is licensed under the MIT License - see the LICENSE file for details.

MIT License

Copyright (c) 2026 bargom

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

Acknowledgments

Built with excellent open-source projects:


CodeAI - Declarative Backend Development
GitHub | Quick Start | API Docs

About

LLM focused language that is converted into golang

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors 2

  •  
  •  

Languages