Skip to content
Adel-dev-2001Public

About

A personal assistant chatbot that integrates the Gemini API for code generation.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

Syntax Logo

Syntax

Conversational AI & Developer Workspace

Built and maintained by Adel Mohamed

React TypeScript Vite Tailwind CSS Google Gemini API License: MIT

Live Application | Source Repository


Overview

Syntax is an applied AI workstation designed for software development, algorithmic problem-solving, and technical research. While underlying language inference runs live against Google's Gemini REST and streaming APIs, Syntax is engineered as a complete orchestration and workspace layer on top of those models, combining domain-specific personas, cross-session memory, live Server-Sent Events (SSE) token streaming, automatic model routing, isolated execution sandboxes, and structured vector PDF export.

Rather than exposing a raw request wrapper, this architecture lets users work inside a cohesive, specialized AI environment tailored to engineering workflows while keeping full transparency over live upstream model execution. The application runs entirely client-side without an intermediate backend server: settings, conversation histories, custom instructions, and API keys stay locally in localStorage and communicate directly with Google's official endpoints over HTTPS.


Academic & Learning Context Note

Note for Academic Reviewers and Evaluation Committees:

This project was developed by Adel Mohamed as part of a self-directed learning journey in software engineering, modern frontend development, and practical AI integration. The primary educational goals of building Syntax were to gain hands-on experience in:

  • Designing modular single-page applications with React and TypeScript.
  • Authenticating and communicating with external REST APIs (Google Gemini API), handling asynchronous data streams, and managing rate limits and error states gracefully.
  • Implementing client-side state persistence, browser security practices (such as opaque-origin iframe sandboxes and HTML escaping), and technical documentation.

Because this application was built as an educational project while actively learning and experimenting with these technologies, certain architectural patterns or edge cases may still have room for further refinement and optimization. Constructive feedback and academic review are always welcome as part of this ongoing learning process.


Key Features

1. Live Google Gemini API Connection & Dynamic Model Discovery

  • Direct API & Live SSE Streaming: Communicates directly over HTTPS with https://generativelanguage.googleapis.com/v1beta/models using Google's :streamGenerateContent?alt=sse endpoint for real-time token streaming (filtering internal model thought scratchpads and guarding stalls with idle abort timeouts).
  • Forward-Compatible Model Discovery: Queries the live models catalog, parses semantic versions dynamically (supporting current 2.x and 3.x series as well as future releases), ranks strictly by version priority (major -> minor -> patch, preferring stable canonical aliases and full Flash models before Lite or preview variants), and filters out non-conversational endpoints (such as image-only, audio, or embedding models).
  • Live HTTP Verification & Privacy-Safe Caching: When validating an API key or refreshing the catalog, sends lightweight live probes (maxOutputTokens: 1) across up to 8 top candidate models in staggered pairs and keeps up to 6 verified working endpoints (200 OK), storing catalog signatures under a non-reversible key hash in localStorage.
  • Automatic Latest-Model Routing & Failover: Syntax automatically locks onto the newest verified free-tier model without manual switching. If an endpoint hits a rate limit (HTTP 429) or becomes unavailable (HTTP 404) before response tokens arrive, Syntax immediately routes to the next verified backup with a toast notification, automatically restores the newest flagship model after cooldown recovery, and notifies you when Google's daily quota resets at Midnight Pacific Time.

2. Interactive Code Block & Sandboxed Execution

  • Code Formatting & Actions: Renders fenced code blocks with language labels, line numbering support, one-click clipboard copy, and direct source snippet download (Save).
  • In-Browser Live Runner: Detects runnable web code (HTML5, CSS, SVG, Canvas applications, and standalone browser JavaScript) and provides an in-place toggle between the Code view and the Live App / Run output view.
  • Isolated Iframe Sandboxes: Interactive web previews run inside a restricted iframe (sandbox="allow-scripts allow-forms allow-modals"), standalone JavaScript snippets run inside a hidden sandbox="allow-scripts" iframe with a 5-second timeout, and external tab previews load inside a sandboxed host wrapper. None of these execution environments are granted allow-same-origin, preventing untrusted code from accessing parent localStorage, cookies, or API keys.
  • Execution Controls: Includes pause/resume overlays for Canvas animations, a restart button, execution timing metrics for JavaScript console outputs, an option to open the preview in a sandboxed new tab, and a fullscreen view with Esc key support.

3. Conversation Management & Workflow Tools

  • Multi-Session Architecture: Create chat sessions, rename titles, pin important conversations to the top of the sidebar, or delete sessions via a confirmation dialog.
  • Instant Search (Ctrl + K): Filter saved conversations in real time by matching against both chat titles and message bodies.
  • Concurrent Background Generation: Start a new conversation or switch between existing chats while another session is waiting for or streaming a response in the background.
  • Inline Prompt Editing: Edit any previously sent user message in place to update the prompt and regenerate the response from that point in the conversation.
  • Multimodal Image Attachments: Attach PNG, JPEG, WebP, or GIF images (up to 10MB per file) to analyze screenshots, diagrams, or code snippets alongside text prompts.

4. Custom Instructions, Memory & Domain Personas

  • Built-In Selectable Personas: Switch between 4 domain personas in Settings -> Instructions:
    • Syntax Algorithms & ICPC (data structures, graph theory, and complexity analysis)
    • CS Academic Researcher (research structuring, formal computer science theory, and academic writing)
    • Low-Level & Cloud Architect (systems programming, concurrency, and backend architecture)
    • Russian-English CS Bridge (bilingual technical terminology and academic translation)
  • Custom System Instructions: Configure persistent system-level behavior rules and user background profile notes in the Settings modal.
  • Memory Bank: Add, edit, enable/disable, or delete specific personal notes and preferences appended to the model context across sessions.

5. Vector PDF Export

  • Selectable PDF Reports: Exports any conversation via a native HTML/Vector print engine (pdfExportService.ts), with Markdown file fallback if print initialization fails.
  • Multilingual Typography: Supports both Left-to-Right (English, Russian) and Right-to-Left (Arabic) text layout, preserving code blocks, timestamps, and conversation metadata.

6. Real-Time Notifications, Official Google Links & Theme Support

  • Google AI Studio Shortcuts (Settings -> General & API): Provides quick access links to obtain a free API key and view official account quotas (aistudio.google.com/usage) directly in Google AI Studio.
  • Real-Time Status Notifications: Displays toast alerts for automatic quota failovers, newest-model restoration after cooldown recovery, daily quota resets at Midnight PT, new Google catalog updates, network disconnection/reconnection, API exhaustion (HTTP 429), and safety filter blocks.
  • Light & Dark Themes: Initializes in light mode by default with an instant toggle to dark mode, backed by an inline script in index.html to prevent theme flickering on page load.

Security & SEO Implementation

Security Measures

  • Local-Only Credential Storage: API keys are stored strictly in the user's browser localStorage (syntax_ai_settings_v1) and sent directly to generativelanguage.googleapis.com over HTTPS without passing through any intermediary server.
  • Opaque-Origin Sandbox Isolation: Interactive HTML previews, standalone JavaScript snippets, and new-tab previews all execute inside sandboxed iframes without allow-same-origin, isolating them from parent DOM and localStorage.
  • Safe Markdown & Export Sanitization: Inline markdown links ([label](url)) allow only http:// and https:// protocols with target="_blank" rel="noopener noreferrer"; markdown and PDF images validate explicit raster image protocols/MIME types; PDF export metadata, titles, and bodies are HTML-escaped prior to rendering.

SEO & Structured Data

  • Metadata & Social Cards: Configured in index.html with canonical URLs pointing to https://adel-dev-2001.github.io/syntax/, meta descriptions, keywords, Open Graph (og:*) tags, and Twitter Card metadata.
  • Schema.org JSON-LD: Includes structured data graphs for WebApplication and Person (creator attribution).
  • Indexing Assets: Includes public/robots.txt, public/sitemap.xml, and a Web App Manifest (public/manifest.json) configured with relative asset paths for GitHub Pages subpath deployment.

Technology Stack

Layer Technology
UI Framework React 18.3 (Functional Components & Hooks)
Language TypeScript 5.7 (Strict Mode)
Build Tool Vite 6.0
Styling Tailwind CSS 3.4 & PostCSS
Icons Lucide React
PDF Generation Native Browser Vector Print Engine (HTML/CSS)
API Provider Google Gemini REST API (v1beta)

Project Structure

syntax/
├── .github/
│   └── workflows/
│       └── deploy.yml                  # GitHub Actions workflow for GitHub Pages deployment
├── public/
│   ├── favicon.svg                     # Application vector icon
│   ├── logo.svg                        # Brand vector logo
│   ├── manifest.json                   # Web App Manifest
│   ├── robots.txt                      # Search crawler rules
│   └── sitemap.xml                     # XML sitemap
├── src/
│   ├── components/
│   │   ├── ChatHeader.tsx              # Top bar, active auto-model status indicator, and theme toggle
│   │   ├── ChatInput.tsx               # Auto-resizing prompt input and image attachment bar
│   │   ├── ChatMessage.tsx             # Message renderer, markdown parser, and inline editor
│   │   ├── CodeBlock.tsx               # Code viewer, snippet downloader, and sandboxed runner
│   │   ├── ConversationOptionsMenu.tsx # Pin, rename, PDF export, and delete dropdown
│   │   ├── ErrorBoundary.tsx           # React error boundary for graceful recovery
│   │   ├── RenameModal.tsx             # Modal dialog for renaming chat sessions
│   │   ├── SettingsModal.tsx           # API keys, auto-routing status, personas, memory, data reset
│   │   ├── Sidebar.tsx                 # Collapsible session list, search bar, and delete modal
│   │   └── ToastContainer.tsx          # Notification toasts for network and API events
│   ├── data/
│   │   └── personas.ts                 # Pre-defined system personas and sample prompts
│   ├── services/
│   │   ├── geminiApi.ts                # Google Gemini SSE streaming client, model ranker, and live verifier
│   │   ├── pdfExportService.ts         # Multi-language vector PDF print exporter
│   │   └── storageService.ts           # localStorage wrapper, sessions, settings, and sanitization
│   ├── types/
│   │   └── chat.ts                     # TypeScript interfaces for messages, sessions, and settings
│   ├── App.tsx                         # Main application state and session controller
│   ├── index.css                       # Global styles and Tailwind imports
│   └── main.tsx                        # React application entry point
├── index.html                          # HTML shell, SEO meta tags, and JSON-LD schema
├── LICENSE                             # MIT License
├── package.json                        # Scripts and dependencies
├── postcss.config.js                   # PostCSS configuration
├── tailwind.config.js                  # Tailwind CSS configuration
├── tsconfig.json                       # TypeScript compiler configuration
└── vite.config.ts                      # Vite build configuration (relative base path)

Getting Started Locally

Prerequisites

  • Node.js (v18.0.0 or newer)
  • npm (v9.0.0 or newer)

1. Clone the Repository

git clone https://github.com/Adel-dev-2001/syntax.git
cd syntax

2. Install Dependencies

npm install

3. Start the Development Server

npm run dev

Open http://localhost:5173 in your browser.

4. Build for Production

npm run build

The production-ready static files will be generated in the dist/ directory.


Configuring a Google Gemini API Key

  1. Visit Google AI Studio and create a free API key.
  2. Open Syntax and click Settings in the bottom-left corner of the sidebar.
  3. Paste your key into the Google Gemini API Key field and click Test Key.
  4. Syntax will verify the key against Google's servers, discover the active free-tier models available for your account, and save your configuration locally.

Author


License

This project is licensed under the MIT License.

About

A personal assistant chatbot that integrates the Gemini API for code generation.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages