### Run Supabase Bootstrap Command Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Initiates the Supabase project setup process using the 'supabase bootstrap' command. This command guides the user through setting up a project with starter templates. It can be run directly or via npx. ```bash supabase bootstrap ``` ```bash npx supabase bootstrap ``` -------------------------------- ### Install fetch-blob Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/fetch-blob/README.md Installs the fetch-blob package using npm. This is the primary method for adding the library to your project. ```sh npm install fetch-blob ``` -------------------------------- ### Install Supabase CLI via Scoop (Windows) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI on Windows using Scoop, a command-line installer. It includes adding the Supabase bucket and upgrading the CLI. ```powershell scoop bucket add supabase https://github.com/supabase/scoop-bucket.git scoop install supabase ``` ```powershell scoop update supabase ``` -------------------------------- ### Install Supabase CLI via Homebrew (macOS/Linux) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI using Homebrew, a popular package manager for macOS and Linux. It also shows how to install and switch to the beta release channel and how to upgrade. ```bash brew install supabase/tap/supabase ``` ```bash brew install supabase/tap/supabase-beta brew link --overwrite supabase-beta ``` ```bash brew upgrade supabase ``` -------------------------------- ### Install bin-links Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/bin-links/README.md Installs the bin-links package using npm. This is the primary method for adding the library to your project dependencies. ```bash $ npm install bin-links ``` -------------------------------- ### JavaScript: Setup Supabase Tables for Lana AI Source: https://github.com/muktargoni1/lana-ai/blob/Dev/frontend/scripts/README.md Provides instructions and SQL commands for creating the 'user_events' table and adding the 'learning_profile' column to the 'users' table in Supabase. This script is intended to guide manual SQL execution. ```javascript console.log("--- Supabase Table Setup Instructions ---"); console.log("1. Create 'user_events' table:"); console.log(" Refer to backend/migrations/versions/001_create_user_events_table.sql"); console.log("2. Add 'learning_profile' column to 'users' table:"); console.log(" Refer to backend/migrations/versions/002_add_learning_profile_to_users.sql"); console.log("Ensure you have set NEXT_PUBLIC_SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY in your .env.local file."); ``` -------------------------------- ### Bash: Run Supabase Setup and Verification Scripts Source: https://github.com/muktargoni1/lana-ai/blob/Dev/frontend/scripts/README.md Commands to execute the Supabase table setup and verification scripts via npm. These commands trigger the respective JavaScript files to provide instructions or perform checks. ```bash npm run supabase:setup ``` ```bash npm run supabase:verify ``` -------------------------------- ### Install node-fetch with npm Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/node-fetch/README.md Installs the latest stable release (v3.x) of node-fetch, which requires Node.js 12.20.0 or later. ```sh npm install node-fetch ``` -------------------------------- ### Install Supabase CLI via Pkgx Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI using Pkgx, a package manager that simplifies software installation. The package script is available in the Pkgx pantry. ```bash pkgx install supabase ``` -------------------------------- ### Install Supabase CLI via Go Modules Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI directly using Go modules, suitable for platforms without standard package managers. It also includes instructions for creating a symlink for easier access. ```bash go install github.com/supabase/cli@latest ``` ```bash ln -s "$(go env GOPATH)/bin/cli" /usr/bin/supabase ``` -------------------------------- ### Handle Bin Linking Success with binLinks Promise Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/bin-links/README.md An example demonstrating how to use the Promise returned by the binLinks function to log a success message once the binaries have been linked. ```javascript binLinks({path, pkg, force, global, top}).then(() => console.log('bins linked!')) ``` -------------------------------- ### Install Supabase CLI with Yarn and Node Options Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI using Yarn, specifically disabling experimental fetch for older Node.js versions. This is a workaround for compatibility issues. ```bash NODE_OPTIONS=--no-experimental-fetch yarn add supabase ``` -------------------------------- ### Install node-fetch v2 for CommonJS Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/node-fetch/README.md Installs version 2 of node-fetch, which is compatible with CommonJS modules. Critical bug fixes will continue for v2. ```sh npm install node-fetch@2 ``` -------------------------------- ### Minipass Stream Usage Example (JavaScript) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/minipass/README.md Provides a fundamental example of how to use a Minipass stream. It shows instantiation, writing data, piping to another stream, and ending the stream. ```javascript import { Minipass } from 'minipass' const mp = new Minipass(options) // options is optional mp.write('foo') mp.pipe(someOtherStream) mp.end('bar') ``` -------------------------------- ### Install Supabase CLI via Linux Packages Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI on Linux using native package managers by downloading and running the appropriate package file (.apk, .deb, .rpm, .pkg.tar.zst). ```bash sudo apk add --allow-untrusted <...>.apk ``` ```bash sudo dpkg -i <...>.deb ``` ```bash sudo rpm -i <...>.rpm ``` ```bash sudo pacman -U <...>.pkg.tar.zst ``` -------------------------------- ### Synchronous Minipass Stream Example (JavaScript) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/minipass/README.md Demonstrates the default synchronous behavior of a Minipass stream. Data is emitted immediately upon writing. This example shows the output order when 'write' is called. ```javascript import { Minipass } from 'minipass' // or: // const { Minipass } = require('minipass') const stream = new Minipass() stream.on('data', () => console.log('data event')) console.log('before write') stream.write('hello') console.log('after write') // output: // before write // data event // after write ``` -------------------------------- ### Install cmd-shim using npm Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/cmd-shim/README.md This snippet shows the command to install the cmd-shim package using npm. It is a prerequisite for using the cmd-shim API. ```bash npm install cmd-shim ``` -------------------------------- ### Install Supabase CLI via NPM Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/supabase/README.md Installs the Supabase CLI as a development dependency using NPM. This is a common method for Node.js projects. ```bash npm i supabase --save-dev ``` -------------------------------- ### Fetch plain text or HTML Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/node-fetch/README.md Example of fetching content from a URL and retrieving the response body as plain text. This is useful for HTML pages or simple text files. ```js import fetch from 'node-fetch'; const response = await fetch('https://github.com/'); const body = await response.text(); console.log(body); ``` -------------------------------- ### WebSocket Connection Example with HttpsProxyAgent (TypeScript) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/https-proxy-agent/README.md Shows how to use HttpsProxyAgent to establish a proxied WebSocket connection. This example requires the 'ws' library and 'https-proxy-agent'. The HttpsProxyAgent is configured with the proxy URL and then passed to the WebSocket constructor. ```typescript import WebSocket from 'ws'; import { HttpsProxyAgent } from 'https-proxy-agent'; const agent = new HttpsProxyAgent('http://168.63.76.32:3128'); const socket = new WebSocket('ws://echo.websocket.org', { agent }); socket.on('open', function () { console.log('"open" event!'); socket.send('hello world'); }); socket.on('message', function (data, flags) { console.log('"message" event! %j %j', data, flags); socket.close(); }); ``` -------------------------------- ### Minipass Stream Immediate Data Flow Example Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/minipass/README.md Illustrates the efficient data flow in Minipass streams, where data is written immediately through the pipeline without significant buffering. This example shows that writes return true, indicating no pausing or event deferrals, highlighting Minipass's speed advantage. ```javascript const Minipass = require('minipass') const m1 = new Minipass() const m2 = new Minipass() const m3 = new Minipass() const m4 = new Minipass() m1.pipe(m2).pipe(m3).pipe(m4) m4.on('data', () => console.log('made it through')) m1.write(Buffer.alloc(2048)) // returns true ``` -------------------------------- ### Get Guardian Reports Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Retrieves guardian reports with optional filtering capabilities. ```APIDOC ## GET /guardian-reports ### Description Retrieves guardian reports with optional filtering capabilities. ### Method GET ### Endpoint /guardian-reports ### Parameters #### Query Parameters - **child_uid** (uuid) - Optional - Filter reports by child unique identifier. - **report_type** (string) - Optional - Filter reports by type (e.g., 'weekly', 'monthly'). - **sent** (boolean) - Optional - Filter reports by sent status (true/false). ### Request Example ```bash curl -X GET "http://localhost:8000/guardian-reports?child_uid=YOUR_CHILD_UID&report_type=monthly" ``` ### Response #### Success Response (200) - **reports** (array) - An array of guardian report objects. - **id** (uuid) - The unique identifier of the report. - **child_uid** (uuid) - The unique identifier of the child. - **guardian_email** (text) - The email address of the guardian. - **report_type** (text) - The type of the report. - **period_start** (date) - The start date of the report period. - **period_end** (date) - The end date of the report period. - **sent** (boolean) - Indicates if the report has been sent. - **created_at** (timestamp) - The timestamp when the report was created. #### Response Example ```json { "reports": [ { "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef", "child_uid": "f0e9d8c7-b6a5-4321-0987-fedcba098765", "guardian_email": "guardian@example.com", "report_type": "weekly", "period_start": "2023-10-16", "period_end": "2023-10-22", "sent": true, "created_at": "2023-10-23T10:00:00Z" } ] } ``` ``` -------------------------------- ### Manual Guardian Report Generation with cURL Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Examples of using cURL to manually trigger guardian report generation. Demonstrates generating a weekly report for a specific child and batch generating reports for all eligible guardians. ```bash # Generate a weekly report for a child curl -X POST "http://localhost:8000/guardian-reports/generate?child_uid=YOUR_CHILD_UID&report_type=weekly" # Generate reports for all eligible guardians curl -X POST "http://localhost:8000/guardian-reports/batch-generate?report_type=weekly" ``` -------------------------------- ### Get Tarball Filenames Asynchronously in JavaScript Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/tar/README.md An example of how to get a list of filenames from a tarball. It uses the 'tar.t' function with an 'onReadEntry' callback to push each entry's path into an array. The function is asynchronous and returns a promise. ```javascript const getEntryFilenames = async tarballFilename => { const filenames = [] await tar.t({ file: tarballFilename, onReadEntry: entry => filenames.push(entry.path), }) return filenames } ``` -------------------------------- ### POST FormData using node-fetch Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/node-fetch/README.md Illustrates how to construct and send a `FormData` payload with `node-fetch`. This includes setting text fields and uploading a file. The example demonstrates creating a `FormData` object, adding a file created from binary data, and sending it via a POST request to `https://httpbin.org/post`. ```javascript import fetch, { FormData, File, fileFrom } from 'node-fetch' const httpbin = 'https://httpbin.org/post' const formData = new FormData() const binary = new Uint8Array([ 97, 98, 99 ]) const abc = new File([binary], 'abc.txt', { type: 'text/plain' }) formData.set('greeting', 'Hello, world!') formData.set('file-upload', abc, 'new name.txt') const response = await fetch(httpbin, { method: 'POST', body: formData }) const data = await response.json() console.log(data) ``` -------------------------------- ### Generate Guardian Report Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Generates a guardian report for a specific child and report type. ```APIDOC ## POST /guardian-reports/generate ### Description Generates a guardian report for a specific child and report type. ### Method POST ### Endpoint /guardian-reports/generate ### Parameters #### Query Parameters - **child_uid** (uuid) - Required - The unique identifier of the child. - **report_type** (string) - Required - The type of report to generate (e.g., 'weekly', 'monthly'). ### Request Example ```bash curl -X POST "http://localhost:8000/guardian-reports/generate?child_uid=YOUR_CHILD_UID&report_type=weekly" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the report generation. #### Response Example ```json { "message": "Guardian report generated successfully." } ``` ``` -------------------------------- ### tar.WriteEntry Constructor Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/tar/README.md Initializes a new WriteEntry instance with a specified path and options. ```APIDOC ## POST /muktargoni1/lana-ai/tar/WriteEntry ### Description Initializes a new `WriteEntry` instance with a specified path and options. ### Method POST ### Endpoint /muktargoni1/lana-ai/tar/WriteEntry ### Parameters #### Path Parameters - **path** (string) - Required - The path of the entry as it is written in the archive. #### Query Parameters - **options** (object) - Optional - Configuration options for the entry. - **portable** (boolean) - Omit system-specific metadata (`ctime`, `atime`, `uid`, `gid`, `uname`, `gname`, `dev`, `ino`, `nlink`). `mtime` is still included. `mode` defaults to a reasonable value based on `umask`. - **maxReadSize** (number) - The maximum buffer size for `fs.read()` operations. Defaults to 1 MB. - **linkCache** (Map) - A Map object to identify hard links using device and inode values for entries with `nlink > 1`. - **statCache** (Map) - A Map object that caches `lstat` calls. - **preservePaths** (boolean) - Allow absolute paths. By default, `/` is stripped from absolute paths. - **cwd** (string) - The current working directory for creating the archive. Defaults to `process.cwd()`. - **absolute** (string) - The absolute path to the entry on the filesystem. Defaults to `path.resolve(this.cwd, this.path)`. - **strict** (boolean) - Treat warnings as crash-worthy errors. Defaults to `false`. - **win32** (boolean) - If true, replaces `\` with `/` in paths for Windows compatibility. - **onwarn** (function) - A function called with `(code, message, data)` for any warnings encountered. - **noMtime** (boolean) - Set to true to omit writing `mtime` values for entries. This prevents mtime-based features like `tar.update` or `keepNewer`. - **umask** (number) - Restricts entry modes, similar to file creation `umask`. Defaults to `process.umask()` on Unix or `0o22` on Windows. ### Request Example ```json { "path": "/path/to/entry", "options": { "portable": true, "maxReadSize": 1048576, "preservePaths": false, "strict": false, "noMtime": false } } ``` ### Response #### Success Response (200) - **WriteEntry** (object) - An instance of the WriteEntry class. #### Response Example ```json { "writeEntryInstance": "" } ``` ``` -------------------------------- ### Batch Generate Guardian Reports Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Batch generates reports for all eligible guardians based on the specified report type. ```APIDOC ## POST /guardian-reports/batch-generate ### Description Batch generates reports for all eligible guardians based on the specified report type. ### Method POST ### Endpoint /guardian-reports/batch-generate ### Parameters #### Query Parameters - **report_type** (string) - Required - The type of reports to generate (e.g., 'weekly', 'monthly'). ### Request Example ```bash curl -X POST "http://localhost:8000/guardian-reports/batch-generate?report_type=weekly" ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating the batch report generation process has started. #### Response Example ```json { "message": "Batch report generation initiated for weekly reports." } ``` ``` -------------------------------- ### View Supabase Edge Function Logs Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Commands to view logs for the 'generate-guardian-reports' and 'send-guardian-reports' Supabase Edge Functions. Useful for debugging issues with report generation or sending. ```bash supabase functions logs generate-guardian-reports supabase functions logs send-guardian-reports ``` -------------------------------- ### Python Backend Testing for Guardian Reports Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Command to run the backend validation script for the guardian reports system. This script ensures all components are correctly set up and functioning. ```bash cd backend python test_guardian_reports.py ``` -------------------------------- ### Deploy Supabase Edge Functions for Guardian Reports Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Commands to deploy the 'generate-guardian-reports' and 'send-guardian-reports' Supabase Edge Functions. These functions automate the generation and sending of guardian reports. ```bash supabase functions deploy generate-guardian-reports supabase functions deploy send-guardian-reports ``` -------------------------------- ### Load Environment Variables and Initialize Clients Source: https://github.com/muktargoni1/lana-ai/blob/Dev/backend/sample.md Loads environment variables from a .env file using `dotenv` and initializes clients for Groq, Google GenAI, and Supabase. It also includes a check to ensure all required environment variables are set, raising a RuntimeError if any are missing. ```python load_dotenv() GROQ_API_KEY = os.getenv("GROQ_API_KEY") GOOGLE_API_KEY = os.getenv("GOOGLE_API_KEY") SUPABASE_URL = os.getenv("SUPABASE_URL") SUPABASE_KEY = os.getenv("SUPABASE_ANON_KEY") SUPABASE_SERVICE_KEY = os.getenv("SUPABASE_SERVICE_ROLE_KEY") if not (GROQ_API_KEY and GOOGLE_API_KEY and SUPABASE_URL and SUPABASE_KEY): raise RuntimeError("Missing required env vars") groq_client = AsyncGroq( api_key=GROQ_API_KEY, http_client=httpx.AsyncClient( limits=httpx.Limits(max_keepalive_connections=10, max_connections=20), timeout=30.0 ) ) gemini_client = genai.Client(api_key=GOOGLE_API_KEY) supabase = create_client(SUPABASE_URL, SUPABASE_KEY) ``` -------------------------------- ### SQL Database Schema for Guardian Reports Source: https://github.com/muktargoni1/lana-ai/blob/Dev/GUARDIAN_REPORTS_SETUP.md Defines the 'guardians' and 'guardian_reports' tables in Supabase SQL. The 'guardians' table stores guardian contact information and report preferences, while 'guardian_reports' stores generated report details, including type, payload, and sent status. ```sql -- Guardians table CREATE TABLE public.guardians ( id uuid NOT NULL DEFAULT gen_random_uuid(), email text NOT NULL, child_uid uuid, weekly_report boolean DEFAULT true, monthly_report boolean DEFAULT true, created_at timestamp with time zone DEFAULT now(), CONSTRAINT guardians_pkey PRIMARY KEY (id), CONSTRAINT guardians_child_uid_fkey FOREIGN KEY (child_uid) REFERENCES auth.users(id) ); -- Guardian reports table CREATE TABLE public.guardian_reports ( id uuid NOT NULL DEFAULT gen_random_uuid(), child_uid uuid NOT NULL, guardian_email text NOT NULL, report_type text CHECK (report_type = ANY (ARRAY['weekly'::text, 'monthly'::text])), report_payload jsonb NOT NULL, period_start date NOT NULL, period_end date NOT NULL, created_at timestamp with time zone DEFAULT now(), sent boolean DEFAULT false, CONSTRAINT guardian_reports_pkey PRIMARY KEY (id), CONSTRAINT guardian_reports_child_uid_fkey FOREIGN KEY (child_uid) REFERENCES auth.users(id) ); ``` -------------------------------- ### Perform a simple POST request Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/node-fetch/README.md Shows how to make a basic POST request to a specified URL with a simple string body. The response is then parsed as JSON. ```js import fetch from 'node-fetch'; const response = await fetch('https://httpbin.org/post', {method: 'POST', body: 'a=1'}); const data = await response.json(); console.log(data); ``` -------------------------------- ### Link Binaries and Man Pages with bin-links Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/bin-links/README.md Demonstrates how to use the binLinks function to link binaries and man pages for a JavaScript package. It requires the package path and package.json content, with options for global installation, top-level package, and forcing overwrites. ```javascript const binLinks = require('bin-links') const readPackageJson = require('read-package-json-fast') binLinks({ path: '/path/to/node_modules/some-package', pkg: readPackageJson('/path/to/node_modules/some-package/package.json'), // true if it's a global install, false for local. default: false global: true, // true if it's the top level package being installed, false otherwise top: true, // true if you'd like to recklessly overwrite files. force: true, }) ``` -------------------------------- ### Generate Structured Lesson with Caching and Groq API (Python) Source: https://github.com/muktargoni1/lana-ai/blob/Dev/backend/sample.md This Python function generates a structured lesson plan. It first checks a cache for existing content. If not found, it handles social greetings or calls the Groq API with an age-aware system prompt. The response is parsed, processed, and cached for future requests. Includes error handling for JSON parsing and parallel processing of sections and quizzes. ```python async def structured_lesson(body: StructuredLessonRequest): """Generate structured lesson with enhanced caching""" topic = body.topic.strip() age = body.age # Check cache first cache_key = get_cache_key(topic) cached_result = await get_cache(cache_key, namespace="lessons") if cached_result: logging.info(f"📦 Cache hit for: {topic}") return cached_result # Handle social greetings if is_social_greeting(topic): response = StructuredLessonResponse( introduction=SOCIAL_REPLY, classifications=[], sections=[ SectionItem(title="Friendly Note", content=SOCIAL_REPLY) ], diagram="No diagram needed for a friendly chat.", quiz=[ { "q": "What would you like to learn next?", "options": ["A) Science", "B) History", "C) Anything"], "answer": "C) Anything" } ]) await set_cache(cache_key, response, ttl=7200, namespace="lessons") return response try: # Create age-aware system prompt system_prompt = SYSTEM_PROMPT.replace("@age", str(age) if age else "general audience") # Optimized Groq call with better parameters res = await groq_client.chat.completions.create( model="llama-3.1-8b-instant", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Topic: {topic}"} ], temperature=0.3, max_tokens=1200, top_p=0.9, stream=False, ) content = res.choices[0].message.content or "" content = content.strip() if '```json' in content: start = content.find('```json') + 7 end = content.find('```', start) if end != -1: content = content[start:end].strip() elif '```' in content: start = content.find('```') + 3 end = content.find('```', start) if end != -1: content = content[start:end].strip() if not (content.startswith('{') and content.endswith('}')): start_idx = content.find('{') end_idx = content.rfind('}') if start_idx != -1 and end_idx != -1 and end_idx > start_idx: content = content[start_idx:end_idx + 1] try: data = orjson.loads(content) except orjson.JSONDecodeError: import re content = re.sub(r'[\x00-\x1f\x7f-\x9f]', '', content) content = content.replace('\n', '\\n').replace('\r', '\\r').replace('\t', '\\t') content = re.sub(r',(\s*[}\]])', r'\1', content) try: data = orjson.loads(content) except orjson.JSONDecodeError: t = body.topic data = { "introduction": {"definition": f"Learn about {t}", "relevance": ""}, "sections": [{"title": f"Introduction to {t}", "content": f"Overview of {t}."}], "classifications": [], "quiz": [] } # Parallel processing of data with better error handling async def safe_process_sections(): try: return await process_sections(data) except Exception as e: logging.warning(f"Section processing error: {e}") return [] async def safe_process_quiz(): try: return await process_quiz(data) except Exception as e: logging.warning(f"Quiz processing error: {e}") return [] sections_task = asyncio.create_task(safe_process_sections()) quiz_task = asyncio.create_task(safe_process_quiz()) sections = await sections_task quiz = await quiz_task intro_str = None if "introduction" in data and isinstance(data["introduction"], dict): intro = data["introduction"] intro_str = f"{intro.get('definition', '')}\n{intro.get('relevance', '')}".strip() response = StructuredLessonResponse( introduction=intro_str, classifications=[ ClassificationItem(type=c["type"], description=c["description"]) for c in data.get("classifications", []) if isinstance(c, dict) and "type" in c and "description" in c ], sections=sections, diagram=data.get("diagram_description", ""), quiz=quiz ) # Cache the response await set_cache(cache_key, response, ttl=7200, namespace="lessons") ``` -------------------------------- ### Initialize Supabase Client Source: https://github.com/muktargoni1/lana-ai/blob/Dev/backend/sample.md Creates a Supabase client instance using the provided URL and API key. This client is used to interact with the Supabase backend for data storage and retrieval. ```python supabase = create_client(SUPABASE_URL, SUPABASE_KEY) ``` -------------------------------- ### Install FormData Polyfill Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/formdata-polyfill/README.md Installs the formdata-polyfill package using npm. This package provides a FormData polyfill for browsers and a module for NodeJS. ```bash npm install formdata-polyfill ``` -------------------------------- ### Create Gzipped Tarball in JavaScript Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/tar/README.md Replicates the 'tar czf my-tarball.tgz files and folders' command. This example uses the 'create' function from the 'tar' library to generate a gzipped tarball. It takes an options object for gzip and file naming, and an array of files/folders to include. The operation returns a promise that resolves upon completion. ```javascript import { create } from 'tar' create( { gzip: , file: 'my-tarball.tgz' }, ['some', 'files', 'and', 'folders'] ).then(_ => { .. tarball has been created .. }) ``` -------------------------------- ### Install debug utility using npm Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/debug/README.md This command installs the 'debug' package, a JavaScript debugging utility, using npm. It is a prerequisite for using the library in Node.js projects. ```bash npm install debug ``` -------------------------------- ### Initialize Async Groq Client with Connection Pooling Source: https://github.com/muktargoni1/lana-ai/blob/Dev/backend/sample.md Initializes the asynchronous Groq client with optimized HTTP connection pooling for improved performance and resource management. It sets limits for keep-alive and total connections, along with a request timeout. ```python groq_client = AsyncGroq( api_key=GROQ_API_KEY, http_client=httpx.AsyncClient( limits=httpx.Limits(max_keepalive_connections=10, max_connections=20), timeout=30.0 ) ) ``` -------------------------------- ### Node.js Installation and Usage of iMurmurHash Source: https://github.com/muktargoni1/lana-ai/blob/Dev/node_modules/imurmurhash/README.md For Node.js environments, install the 'imurmurhash' module using NPM. Subsequently, require the module to make the MurmurHash3 object available in your scripts. ```bash npm install imurmurhash ``` ```javascript MurmurHash3 = require('imurmurhash'); ``` -------------------------------- ### Manual Testing of Supabase Functions Source: https://github.com/muktargoni1/lana-ai/blob/Dev/SETUP_SCHEDULED_FUNCTIONS.md Command-line examples for manually testing the deployed Supabase Edge Functions. These cURL commands demonstrate how to invoke the report generation and sending functions. ```bash curl -X GET "https://.supabase.co/functions/v1/generate-guardian-reports?type=weekly" curl -X GET "https://.supabase.co/functions/v1/send-guardian-reports" ``` -------------------------------- ### Configure and Run Uvicorn Server Source: https://github.com/muktargoni1/lana-ai/blob/Dev/backend/sample.md This Python snippet shows how to configure and run a uvicorn server for a web application. It specifies host, port, reload settings, logging level, and various performance-related parameters like workers, limit_concurrency, backlog, and timeout_keep_alive. It's intended for development environments. ```python # ---------- Server startup ---------- if __name__ == "__main__": import uvicorn # Run with single worker for development to avoid worker process issues uvicorn.run( "main:app", host="0.0.0.0", port=8000, reload=False, log_level="info", access_log=False, server_header=False, date_header=False, workers=1, # Single worker to avoid process issues limit_concurrency=100, backlog=2048, timeout_keep_alive=5 ) ```