{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "7cf31ec4",
   "metadata": {},
   "source": [
    "# Libraries"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 47,
   "id": "5fe736bf",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "from pathlib import Path\n",
    "from typing import TypedDict, List, Optional, Annotated, Literal\n",
    "from IPython.display import Image, display\n",
    "from pydantic import BaseModel, Field\n",
    "\n",
    "# Ensure the project root is on the path so `src` is importable\n",
    "_project_root = str(Path(__file__).resolve().parents[2]) if \"__file__\" in dir() else str(Path.cwd().parents[1])\n",
    "if _project_root not in sys.path:\n",
    "    sys.path.insert(0, _project_root)\n",
    "\n",
    "from langchain_core.documents import Document\n",
    "from langchain_core.messages import BaseMessage, SystemMessage, AIMessage\n",
    "from langchain_core.tools import tool\n",
    "from langgraph.checkpoint.memory import InMemorySaver\n",
    "from langgraph.graph.message import add_messages\n",
    "from langchain_ollama import ChatOllama, OllamaEmbeddings\n",
    "from langchain_elasticsearch import ElasticsearchStore\n",
    "from langgraph.graph import StateGraph, END\n",
    "from langgraph.prebuilt import ToolNode, tools_condition\n",
    "from langfuse import Langfuse\n",
    "\n",
    "from src.utils.llm_factory import create_chat_model\n",
    "from src.utils.emb_factory import create_embedding_model\n",
    "from src.config import (\n",
    "    ELASTICSEARCH_LOCAL_URL,\n",
    "    ELASTICSEARCH_INDEX,\n",
    "    OLLAMA_MODEL_NAME,\n",
    "    OLLAMA_EMB_MODEL_NAME\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a73629e1",
   "metadata": {},
   "source": [
    "# State"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 48,
   "id": "5097b8a5",
   "metadata": {},
   "outputs": [],
   "source": [
    "class AgentState(TypedDict):\n",
    "    messages: Annotated[list, add_messages]\n",
    "    reformulated_query: str\n",
    "    context: str"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "id": "c5328a0d",
   "metadata": {},
   "outputs": [],
   "source": [
    "class AgenticAgentState(TypedDict):\n",
    "    messages: Annotated[list, add_messages]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 50,
   "id": "e8f0a0bc",
   "metadata": {},
   "outputs": [],
   "source": [
    "REFORMULATE_PROMPT = SystemMessage(\n",
    "    content=(\n",
    "        \"You are a deterministic query rewriting function.\\n\"\n",
    "        \"You convert natural language questions into keyword search queries.\\n\\n\"\n",
    "        \"Strict constraints:\\n\"\n",
    "        \"1. Keep function names and technical tokens unchanged.\\n\"\n",
    "        \"2. Remove filler phrases.\\n\"\n",
    "        \"3. Do not answer.\\n\"\n",
    "        \"4. Do not explain.\\n\"\n",
    "        \"5. Do not generate code.\\n\"\n",
    "        \"6. Return a single-line query only.\\n\"\n",
    "        \"7. If already optimal, return unchanged.\\n\"\n",
    "    )\n",
    ")\n",
    "\n",
    "GENERATE_PROMPT = SystemMessage(\n",
    "    content=\"\"\"You are an agent designed to assist users with AVAP (Advanced Virtual API Programming) language.\n",
    "    It's a new language, so you should know nothing about it.\n",
    "    Use ONLY the provided context to answer AVAP-related questions.\n",
    "    If the context does not contain enough information, say so honestly.\n",
    "    If the question is not related to AVAP, answer based on your general knowledge.\n",
    "\n",
    "    Context:\n",
    "    {context}\"\"\"\n",
    ")\n",
    "\n",
    "AGENTIC_PROMPT = SystemMessage(\n",
    "    content=\"\"\"You are an agent designed to assist users with AVAP (Advanced Virtual API Programming) language.\n",
    "    It's a new language, so you should know nothing about it.\n",
    "    Use ONLY the provided 'context_retrieve' tool to answer AVAP-related questions.\n",
    "    The 'context_retrieve' tool receives a user query (as a string) and returns relevant context from a vector store.\n",
    "    If the context does not contain enough information, say so honestly.\n",
    "    If the question is not related to AVAP, answer based on your general knowledge.\n",
    "    \"\"\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebd003d9",
   "metadata": {},
   "source": [
    "# Function"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 51,
   "id": "b4e5d981",
   "metadata": {},
   "outputs": [],
   "source": [
    "def format_context(docs: List[Document]) -> str:\n",
    "    chunks: List[str] = []\n",
    "    for i, doc in enumerate(docs, 1):\n",
    "        source = (doc.metadata or {}).get(\"source\", \"Untitled\")\n",
    "        source_id = (doc.metadata or {}).get(\"id\", f\"chunk-{i}\")\n",
    "        text = doc.page_content or \"\"\n",
    "        chunks.append(f\"[{i}] id={source_id} source={source}\\n{text}\")\n",
    "    return \"\\n\\n\".join(chunks)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 52,
   "id": "8a38359a",
   "metadata": {},
   "outputs": [],
   "source": [
    "def reformulate(state: AgentState, llm=None) -> AgentState:\n",
    "    \"\"\"Use the LLM to rewrite the user query for better retrieval.\"\"\"\n",
    "    # The graph runner passes the state only. Accept an optional `llm` so\n",
    "    # this function can also be called directly with an explicit model.\n",
    "    user_msg = state[\"messages\"][-1]\n",
    "    if llm is None:\n",
    "        llm = globals().get('llm')\n",
    "        if llm is None:\n",
    "            raise RuntimeError('No LLM available for reformulate')\n",
    "    resp = llm.invoke([REFORMULATE_PROMPT, user_msg])\n",
    "    reformulated = resp.content.strip()\n",
    "    print(f\"[reformulate] '{user_msg.content}' → '{reformulated}'\")\n",
    "    return {\"reformulated_query\": reformulated}\n",
    "\n",
    "\n",
    "def retrieve(state: AgentState, vector_store=None, retrieve_kwargs=None) -> AgentState:\n",
    "    \"\"\"Retrieve context using the reformulated query.\"\"\"\n",
    "    # Graph runner passes state first. Accept optional `vector_store` and\n",
    "    # `retrieve_kwargs` for direct calls; otherwise fall back to globals.\n",
    "    if vector_store is None:\n",
    "        vector_store = globals().get('vector_store')\n",
    "        if vector_store is None:\n",
    "            raise RuntimeError('No vector_store available for retrieve')\n",
    "    if retrieve_kwargs is None:\n",
    "        retrieve_kwargs = {}\n",
    "    query = state[\"reformulated_query\"]\n",
    "    docs = vector_store.as_retriever(\n",
    "        search_type=\"similarity\",\n",
    "        search_kwargs=retrieve_kwargs,\n",
    "    ).invoke(query)\n",
    "    context = format_context(docs)\n",
    "    print(f\"[retrieve] {len(docs)} docs fetched\")\n",
    "    print(context)\n",
    "    return {\"context\": context}\n",
    "\n",
    "\n",
    "def generate(llm, state: AgentState) -> AgentState:\n",
    "    \"\"\"Generate the final answer using retrieved context.\"\"\"\n",
    "    prompt = SystemMessage(\n",
    "        content=GENERATE_PROMPT.content.format(context=state[\"context\"])\n",
    "    )\n",
    "    resp = llm.invoke([prompt] + state[\"messages\"])\n",
    "    return {\"messages\": [resp]}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 53,
   "id": "d5001041",
   "metadata": {},
   "outputs": [],
   "source": [
    "def agent(llm, tools, state: AgentState) -> AgentState:\n",
    "    llm_with_tools = llm.bind_tools(tools)\n",
    "    return {\"messages\": [llm_with_tools.invoke([SystemMessage(content=AGENTIC_PROMPT.content)] + state[\"messages\"])]}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "538f812d",
   "metadata": {},
   "source": [
    "# Code"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 54,
   "id": "89786481",
   "metadata": {},
   "outputs": [],
   "source": [
    "langfuse = Langfuse()\n",
    "\n",
    "llm = create_chat_model(\n",
    "    provider=\"ollama\",\n",
    "    model=OLLAMA_MODEL_NAME,\n",
    "    temperature=0,\n",
    "    validate_model_on_init=True,\n",
    ")\n",
    "embeddings = create_embedding_model(\n",
    "    provider=\"ollama\",\n",
    "    model=OLLAMA_EMB_MODEL_NAME,\n",
    ")\n",
    "vector_store = ElasticsearchStore(\n",
    "    es_url=ELASTICSEARCH_LOCAL_URL,\n",
    "    index_name=ELASTICSEARCH_INDEX,\n",
    "    embedding=embeddings,\n",
    "    query_field=\"text\",\n",
    "    vector_query_field=\"vector\",\n",
    "    # strategy=ElasticsearchStore.ApproxRetrievalStrategy(\n",
    "    #     hybrid=True,\n",
    "    #     rrf={\"rank_constant\": 60, \"window_size\": 100}\n",
    "    # )\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22115cdc",
   "metadata": {},
   "source": [
    "## Tool"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "id": "42df0acc",
   "metadata": {},
   "outputs": [],
   "source": [
    "retrieve_kwargs = {\"k\": 3}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 56,
   "id": "a132e0e7",
   "metadata": {},
   "outputs": [],
   "source": [
    "@tool\n",
    "def context_retrieve(query: str) -> str:\n",
    "    \"\"\"Consults vector store to respond AVAP related questions\n",
    "    Args:\n",
    "        query (str): The input query for which to retrieve relevant documents.\n",
    "    \"\"\"\n",
    "    retriever = vector_store.as_retriever(\n",
    "        search_type=\"similarity\",\n",
    "        search_kwargs=retrieve_kwargs,\n",
    "    )\n",
    "    docs = retriever.invoke(query)\n",
    "    return format_context(docs)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0165d8d7",
   "metadata": {},
   "source": [
    "## Graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 57,
   "id": "70fdd80f",
   "metadata": {},
   "outputs": [],
   "source": [
    "memory = InMemorySaver()\n",
    "\n",
    "graph_builder = StateGraph(AgentState)\n",
    "\n",
    "graph_builder.add_node(\"reformulate\", reformulate)\n",
    "graph_builder.add_node(\"retrieve\", retrieve)\n",
    "graph_builder.add_node(\"generate\", generate)\n",
    "\n",
    "graph_builder.set_entry_point(\"reformulate\")\n",
    "graph_builder.add_edge(\"reformulate\", \"retrieve\")\n",
    "graph_builder.add_edge(\"retrieve\", \"generate\")\n",
    "graph_builder.add_edge(\"generate\", END)\n",
    "\n",
    "guided_graph = graph_builder.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 58,
   "id": "be526413",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Failed to export span batch code: 404, reason: <!DOCTYPE html><html lang=\"en\"><head><meta charSet=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width\"/><meta name=\"next-head-count\" content=\"2\"/><link rel=\"preload\" href=\"/_next/static/css/1d1bf8ebf039f876.css\" as=\"style\"/><link rel=\"stylesheet\" href=\"/_next/static/css/1d1bf8ebf039f876.css\" data-n-g=\"\"/><noscript data-n-css=\"\"></noscript><script defer=\"\" nomodule=\"\" src=\"/_next/static/chunks/polyfills-42372ed130431b0a.js\"></script><script src=\"/_next/static/chunks/webpack-fafe7122277f5772.js\" defer=\"\"></script><script src=\"/_next/static/chunks/framework-d2dcb18632b956b2.js\" defer=\"\"></script><script src=\"/_next/static/chunks/main-19694d19b6f6c228.js\" defer=\"\"></script><script src=\"/_next/static/chunks/pages/_app-9e6c56ce79ebaf0a.js\" defer=\"\"></script><script src=\"/_next/static/chunks/pages/_error-881d11b9e6da73d1.js\" defer=\"\"></script><script src=\"/_next/static/Eu5QEyLpa3Avvo-CHkMDG/_buildManifest.js\" defer=\"\"></script><script src=\"/_next/static/Eu5QEyLpa3Avvo-CHkMDG/_ssgManifest.js\" defer=\"\"></script></head><body><div id=\"__next\"><script>!function(){try{var d=document.documentElement,c=d.classList;c.remove('light','dark');var e=localStorage.getItem('theme');if('system'===e||(!e&&true)){var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);if(m.media!==t||m.matches){d.style.colorScheme = 'dark';c.add('dark')}else{d.style.colorScheme = 'light';c.add('light')}}else if(e){c.add(e|| '')}if(e==='light'||e==='dark')d.style.colorScheme=e}catch(e){}}()</script><div class=\"flex min-h-full flex-1 flex-col justify-center py-12 sm:px-6 lg:px-8\" data-sentry-component=\"Spinner\" data-sentry-source-file=\"spinner.tsx\"><div class=\"sm:mx-auto sm:w-full sm:max-w-md\"><img src=\"/icon.svg\" width=\"42\" height=\"42\" alt=\"Langfuse Icon\" class=\"mx-auto motion-safe:animate-spin\" data-sentry-component=\"LangfuseIcon\" data-sentry-source-file=\"LangfuseLogo.tsx\"/><h2 class=\"mt-5 text-center text-2xl font-bold leading-9 tracking-tight text-primary\">Loading<!-- --> ...</h2></div></div></div><script id=\"__NEXT_DATA__\" type=\"application/json\">{\"props\":{\"pageProps\":{\"statusCode\":404}},\"page\":\"/_error\",\"query\":{},\"buildId\":\"Eu5QEyLpa3Avvo-CHkMDG\",\"nextExport\":true,\"isFallback\":false,\"gip\":true,\"locale\":\"en\",\"locales\":[\"en\"],\"defaultLocale\":\"en\",\"scriptLoader\":[]}</script></body></html>\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 14976 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "try:\n",
    "    display(Image(guided_graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "id": "fe35e0c0",
   "metadata": {},
   "outputs": [],
   "source": [
    "tools = [context_retrieve]\n",
    "tool_node = ToolNode(tools=tools)\n",
    "memory = InMemorySaver()\n",
    "\n",
    "graph_builder = StateGraph(AgenticAgentState)\n",
    "\n",
    "graph_builder.add_node(\"agent\", agent)\n",
    "graph_builder.add_node(\"tools\", tool_node)\n",
    "\n",
    "graph_builder.set_entry_point(\"agent\")\n",
    "graph_builder.add_conditional_edges(\n",
    "    \"agent\",\n",
    "    tools_condition,\n",
    ")\n",
    "graph_builder.add_edge(\"tools\", \"agent\")\n",
    "\n",
    "agentic_graph = graph_builder.compile()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "id": "f48a5599",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 12472 characters]",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "try:\n",
    "    display(Image(agentic_graph.get_graph().draw_mermaid_png()))\n",
    "except Exception:\n",
    "    pass"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "id": "4626c9cb",
   "metadata": {},
   "outputs": [],
   "source": [
    "config = {\"configurable\": {\"thread_id\": \"5\"}, \n",
    "          #\"callbacks\": [langfuse_handler],\n",
    "          #\"run_name\": \"rag-local-test\"differences between getDatetime() and getTimeStamp() functions in AVAP\n",
    "          }\n",
    "\n",
    "def stream_graph_updates(user_input: str, graph: StateGraph):\n",
    "    for event in graph.stream(\n",
    "        {\"messages\": [{\"role\": \"user\", \"content\": user_input}]},\n",
    "        #config=config,\n",
    "        stream_mode=\"values\",\n",
    "    ):\n",
    "        event[\"messages\"][-1].pretty_print()\n",
    "        # last_msg = event[\"messages\"][-1]\n",
    "        # if isinstance(last_msg, AIMessage):\n",
    "        #     last_msg.pretty_print()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 62,
   "id": "ec8fe643",
   "metadata": {},
   "outputs": [],
   "source": [
    "user_input = \"\"\"Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. How would you do that in AVAP?\"\"\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ec565fa2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. How would you do that in AVAP?\n",
      "[reformulate] 'Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. How would you do that in AVAP?' → '```sql\n",
      "CREATE TABLE IF NOT EXISTS `myDatabase`.`users` (\n",
      "  `username` VARCHAR(255) NULL,\n",
      "  `age` INT NULL,\n",
      "  PRIMARY KEY (`username`)\n",
      ");\n",
      "```'\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. How would you do that in AVAP?\n",
      "[retrieve] 4 docs fetched\n",
      "[1] id=chunk-1 source=21_Persistance_connectors_orm.txt\n",
      "SECTION V: Persistence, Connectors, and Native ORM AVAP is designed to be database-agnostic. It enables data manipulation through three layers: the universal connector, simplified ORM commands, and direct SQL execution. 5.1 The Universal Connector (avapConnector) The avapConnector command is the entry point for any external integration. It uses a Connection Token system (Base64) that encapsulates configuration details (host, port, credentials, driver) to keep code clean and secure. Interface connector_variable = avapConnector(\"BASE64_TOKEN\") Connector Object Capabilities Once instantiated, the variable behaves as an object with dynamic methods: Database Connectors: Expose the .query(sql_string) method, which returns objects or lists depending on the result set. API Connectors (Twilio, Slack, etc.): Expose native service methods (e.g., .send_sms()). Example: Dynamic Assignment with Connectors // Instantiate the connection db = avapConnector(\"REJfQ09OTkVDVE9SM...\") // Execute query and use Section I dynamic evaluation users = db.query(\"SELECT * FROM users\") first_admin = users[0].name if users[0].role == 'admin' else 'N/A' addResult(first_admin) 5.2 Native ORM Layer (ormCheckTable / ormDirect) For quick operations on the local or default database cluster, AVAP provides system-level commands that do not require prior instantiation. 5.2.1 ormCheckTable Verifies the existence of a database structure. It is critical for installation scripts or automated migrations. Interface: ormCheckTable(table_name, target_var) Response: target_var receives the string values \"True\" or \"False\". 5.2.2 ormDirect Executes SQL statements directly. Unlike .query(), it is optimized for statements that do not necessarily return rows (such as INSERT, UPDATE, or CREATE TABLE). Interface: ormDirect(statement, target_var) Interpolation Usage Example: ormDirect(\"UPDATE users SET login = '%s' WHERE id = %s\" % (now, id), result) 5.3 Data Access Abstraction (Implicit Commands) AVAP includes specialized commands for common CRUD operations, reducing the need to write manual SQL and mitigating injection risks. ormAccessSelect Performs filtered queries returning a list-of-objects structure. Syntax: ormAccessSelect(table, filters, target) ormAccessInsert / ormAccessUpdate Manages data persistence. If used on an object that already has an ID, Update synchronizes changes; otherwise, Insert creates the record. 5.4 Dynamic Query Formatting (Injection Prevention) As detailed in Section I, the AVAP engine processes SQL strings before sending them to the database engine. The official recommendation is to always use interpolation with the % operator to ensure proper handling of data types (Strings vs Integers) by the driver. Recommended Secure Pattern sql = \"SELECT * FROM %s WHERE status = '%s'\" % (table_name, recovered_status) res = db.query(sql) 5.5 Cryptographic Security Integration (encodeSHA256) Within the persistence flow, AVAP provides native tools to secure sensitive data before it is written to disk. Interface encodeSHA256(source_text, target_variable) Complete Registration Flow (Final Example) This example integrates Sections I, II, III, and V: // II: Input capture addParam(\"pass\", p) addParam(\"user\", u) // I & V: Processing and security encodeSHA256(p, secure_pass) // V: Insertion sql = \"INSERT INTO users (username, password) VALUES ('%s', '%s')\" % (u, secure_pass) ormDirect(sql, db_result) // III & II: Response if(db_result, \"Success\", \"=\") addVar(msg, \"User created\") addResult(msg) end() Examples 1. Connector Instantiation Code snippet my_db = avapConnector(\"VE9LRU5fREVCX0RFU0FSUk9MTE8=\") 2. Record Retrieval Code snippet rows = my_db.query(\"SELECT id, name FROM users\") addResult(rows) 3. Direct Command Execution Code snippet ormDirect(\"TRUNCATE TABLE temp_cache\", status) 4. Structure Verification Code snippet ormCheckTable(\"inventory\", exists) if(exists, \"False\", \"==\") ormDirect(\"CREATE TABLE inventory...\", r) end() 5. Secure Update (Interpolation) Code snippet sql = \"UPDATE users SET login_count = %s WHERE email = '%s'\" % (count, email) ormDirect(sql, res) 6. JSON/DB Object Navigation Code snippet found_id = query_result[0].id addResult(found_id) 7. ORM Select with Filter Code snippet ormAccessSelect(\"orders\", {\"status\": \"pending\"}, list_result) addResult(list_result) 8. Processing Database Results Code snippet records = db.query(\"SELECT...\") startLoop(i, 0, len(records)) name = records[i].name endLoop() 9. Cryptographic Persistence Code snippet encodeSHA256(password_raw, hashed) ormDirect(\"INSERT INTO logins (hash) VALUES ('%s')\" % hashed, r) 10. Third-Party Connector (e.g., Slack) Code snippet slack_api = avapConnector(\"U0xBQ0tfQVBJX1RPS0VO\")\n",
      "\n",
      "[2] id=chunk-2 source=22_System_utilities_transformation.txt\n",
      "SECTION VI: System Utilities and Transformation This section documents the native commands for advanced string manipulation, precise time handling, and dynamic data generation. 6.1 Time and Date Management (getDateTime / stampToDatetime) AVAP handles time in two formats: Epoch/Timestamp (numeric): Ideal for calculations. Formatted Datetime (string): Ideal for human readability and database storage. 6.1.1 getDateTime Generates the current time with high precision. Interface: getDateTime(format, timeDelta, timeZone, targetVar) Parameters format: Example: \"%Y-%m-%d %H:%M:%S\". If left empty, returns the current Epoch timestamp. timeDelta: Seconds to add (positive) or subtract (negative). Particularly useful for calculating token expiration times. timeZone: Time zone region (e.g., \"Europe/Madrid\"). 6.1.2 stampToDatetime Converts a numeric value (Unix Timestamp) into a human-readable string. Interface: stampToDatetime(timestamp, format, offset, targetVar) Common Use Case: Formatting dates retrieved from the database (Section V) before sending them to the client (Section II). 6.2 Advanced String Manipulation (replace / randomString) 6.2.1 replace Allows text cleaning and transformation. Essential when receiving client data that requires sanitization. Interface: replace(sourceText, oldText, newText, targetVar) Example Use Case: Removing spaces or unwanted characters from a username before executing a SQL query. 6.2.2 randomString Generates secure random alphanumeric strings. Interface: randomString(length, targetVar) Applications: Temporary password generation Session ID creation Unique file name generation 6.3 Security and Hash Operations (encodeSHA256) Although previously mentioned in the persistence section, this is fundamentally a data transformation utility. Mechanics Deterministic one-way function. AVAP uses an optimized implementation ensuring that the same input always produces the same hash. This enables secure login comparisons without storing or exposing the actual password. 6.4 The Return Command (return) Within functions and execution flows, return not only stops execution but can also inject the result of a subroutine back into the main flow. Complete Utility Flow Example // 1. Generate a temporary token randomString(16, token_raw) // 2. Calculate expiration (within 1 hour = 3600 seconds) getDateTime(\"%Y-%m-%d %H:%M:%S\", 3600, \"UTC\", expiration_date) // 3. Format a system message using Section I message = \"Your token %s expires on %s\" % (token_raw, expiration_date) // 4. Send to client (Section II) addResult(message) 6.5 Common Format Tokens (Cheat Sheet) Token Description Example %Y Full year 2026 %m Month (01–12) 02 %d Day (01–31) 23 %H Hour (00–23) 21 %M Minute (00–59) 45 Examples 1. Unix Timestamp Retrieval Code snippet getDateTime(\"\", 0, \"UTC\", now) addResult(now) 2. Database-Formatted Date Code snippet getDateTime(\"%Y-%m-%d %H:%M:%S\", 0, \"Europe/Madrid\", sql_date) addResult(sql_date) 3. Expiration Calculation (1 Day) Code snippet getDateTime(\"\", 86400, \"UTC\", expires_at) addResult(expires_at) 4. Timestamp to Readable Conversion Code snippet stampToDatetime(1708726162, \"%d/%m/%Y\", 0, human_date) addResult(human_date) 5. String Cleaning (Replace) Code snippet replace(\"REF_1234_OLD\", \"OLD\", \"NEW\", updated_ref) addResult(updated_ref) 6. Random Token Generator Code snippet randomString(32, security_token) addResult(security_token) 7. SHA256 Hash for Integrity Code snippet encodeSHA256(\"payload_data\", checksum) addResult(checksum)\n",
      "\n",
      "[3] id=chunk-3 source=16_Function_glossary.txt\n",
      "Function Glossary randomString() The randomString() command generates a random string based on a specified pattern and stores it in a target variable. It is especially useful when random strings are needed to conform to a specific format, such as passwords or identifiers. Parameters Pattern Type: var Description: A regular expression (regex) pattern that defines the characters and structure of the string to be generated. It can be a direct value or a variable containing the pattern. For example, [a-zA-Z0-9] will generate a string that includes uppercase letters, lowercase letters, and numbers. Length Type: var Description: An integer value specifying the length of the random string to be generated. It can be a direct value or a variable containing the desired length. This value determines how many characters the resulting string will have. TargetVariable Type: var Description: The variable where the generated string will be stored. This variable should be used later in the program. Unlike the other parameters, this must be a variable and not a direct value. Usage Example // Direct call with values: randomString('[a-zA-Z0-9]', 8, generatedPassword) // Call using variables: pattern = '[a-zA-Z0-9]' length = 8 randomString(pattern, length, generatedPassword) stampToDatetime() The stampToDatetime() command converts a timestamp value to a date and time according to a specified format, applying a possible time difference, and stores the result in a target variable. It is useful for manipulating and formatting time values into different representations. Parameters timestamp Type: var Description: A value representing a timestamp, which can be provided directly or through a variable. This value is the starting point for conversion to a date and time format. Format Type: var Description: A format string that defines how the resulting date and time should be presented. This string follows the same conventions used in Python for formatting dates and times. Common symbols include: %Y: Year with four digits (e.g., 2024) %m: Month with two digits (01 to 12) %d: Day of the month with two digits (01 to 31) %H: Hour in 24-hour format (00 to 23) %M: Minutes (00 to 59) %S: Seconds (00 to 59) For example, the format %Y-%m-%d %H:%M:%S converts a timestamp into a string like 2024-08-25 14:30:00. It can be a direct value or a variable containing the desired format. TimeDelta Type: var Description: An optional value representing a time adjustment (positive or negative) applied to the timestamp before conversion. This value can be provided directly or through a variable and is expressed in seconds. TargetVariable Type: var Description: The variable where the resulting date and time from the conversion will be stored. Unlike the other parameters, this must be a variable and not a direct value. Usage Example // Direct call with values: stampToDatetime(1692966600, '%Y-%m-%d %H:%M:%S', 3600, convertedDatetime) // Call using variables: timestamp = 1692966600 format = '%Y-%m-%d %H:%M:%S' adjustment = 3600 stampToDatetime(timestamp, format, adjustment, convertedDatetime) In the first example, a timestamp is converted to a date and time in the format \"%Y-%m-%d %H:%M:%S\", applying a 3600-second (1-hour) adjustment, and the result is stored in the variable convertedDatetime. In the second example, variables are used to define the timestamp, format, and adjustment. getTimeStamp() The getTimeStamp() command converts a date and time string, given in a specific format, to a timestamp value. Additionally, it allows for an optional time adjustment before storing the result in a target variable. This command is useful for converting human-readable date and time representations to a numeric timestamp format, which can be used in calculations or time comparisons. Parameters DateString Type: var Description: A string representing a date and time. This string must follow the format specified in the Format parameter. It can be a direct value or a variable containing the date string. Format Type: var Description: A format string that defines how to interpret the date and time string (DateString). This string follows Python's conventions for formatting and parsing dates and times. Some common symbols include: %Y: Year with four digits (e.g., 2024) %m: Month with two digits (01 to 12) %d: Day of the month with two digits (01 to 31) %H: Hour in 24-hour format (00 to 23) %M: Minutes (00 to 59) %S: Seconds (00 to 59) For example, to interpret the string \"2024-08-25 14:30:00\", the format %Y-%m-%d %H:%M:%S would be used. It can be a direct value or a variable containing the format. TimeDelta Type: var Description: An optional value representing a time adjustment (positive or negative) applied to the timestamp after conversion. This value can be provided directly or through a variable and is expressed in seconds. TargetVariable Type: var Description: The variable where the resulting timestamp from the conversion will be stored. Unlike the other parameters, this must be a variable and not a direct value. Usage Example // Direct call with values: getTimeStamp('2024-08-25 14:30:00', '%Y-%m-%d %H:%M:%S', 3600, generatedTimestamp) // Call using variables: date = '2024-08-25 14:30:00' format = '%Y-%m-%d %H:%M:%S' adjustment = 3600 getTimeStamp(date, format, adjustment, generatedTimestamp) In the first example, the date and time string \"2024-08-25 14:30:00\" is converted to a timestamp, applying a 3600-second (1-hour) adjustment, and the result is stored in the variable generatedTimestamp. In the second example, variables are used to define the date, format, and adjustment. getRegex() The getRegex() command searches for matches in a source string using a regular expression (regex) pattern and stores the result in a target variable. This command is useful for extracting specific parts of a string that match a defined pattern, such as email addresses, phone numbers, or any other structure defined by a regex. Parameters SourceVariable Type: variable Description: The variable containing the source string in which to search for regex pattern matches. This string is the text on which the regex search will be applied. rePattern Type: variable Description: The variable containing the regular expression (regex) pattern that defines what to search for in the source string. This pattern should follow standard regex rules, allowing the specification of sequences of characters to identify in the source string. TargetVariable Type: variable Description: The variable where the search result will be stored. Depending on the context and the pattern used, the result could be the first match found, all matches, or even specific groups within the match. Usage Example // Direct call with values: sourceText = \"Email: user@example.com and phone: 123-456-7890\" pattern = r\"\\b\\d{3}-\\d{3}-\\d{4}\\b\" getRegex(sourceText, pattern, phoneNumber) // Call using variables: sourceText = \"Visit our website at https://www.example.com for more information.\" regexPattern = r\"https?://\\S+\" getRegex(sourceText, regexPattern, foundURL) In the first example, a phone number in the format 123-456-7890 is searched in the sourceText string and the result is stored in the phoneNumber variable. In the second example, a URL is extracted from the sourceText string using a regex that identifies URL patterns, and the result is stored in the foundURL variable. getDateTime() The getDateTime() command retrieves the current date and time, formats it according to a specified format, applies an optional time adjustment, and converts it to a specific time zone before storing the result in a target variable. It is useful for obtaining and manipulating the current date and time in different formats and time zones. Parameters Format Type: var Description: A format string that defines how the resulting date and time should be presented. This string follows the date and time formatting conventions used in Python. Some of the most common symbols include: %Y: Year with four digits (e.g., 2024) %m: Month with two digits (01 to 12) %d: Day of the month with two digits (01 to 31) %H: Hour in 24-hour format (00 to 23) %M: Minutes (00 to 59) %S: Seconds (00 to 59) For example, the format \"%Y-%m-%d %H:%M:%S\" will present the date and time as 2024-08-25 14:30:00. It can be a direct value or a variable containing the desired format. TimeDelta Type: var Description: An optional value representing a time adjustment (positive or negative) applied to the current date and time before conversion. This value can be provided directly or through a variable and is expressed in seconds. TimeZone Type: var Description: The time zone to which the date and time should be converted. This value can be a time zone identifier provided directly or through a variable. Some common time zones include: \"UTC\": Coordinated Universal Time \"America/New_York\": U.S. Eastern Time (EST/EDT) \"America/Los_Angeles\": U.S. Pacific Time (PST/PDT) \"Europe/London\": London Time (GMT/BST) \"Europe/Madrid\": Madrid Time (CET/CEST) \"Asia/Tokyo\": Tokyo Time (JST) \"Australia/Sydney\": Sydney Time (AEST/AEDT) You can use any time zone recognized by the pytz library in Python, which includes most time zones worldwide. TargetVariable Type: var Description: The variable in which the resulting date and time from the operation will be stored. Unlike the other parameters, this must be a variable and not a direct value. Usage Example // Direct call with values: getDateTime('%Y-%m-%d %H:%M:%S', 3600, 'UTC', currentTime) // Call using variables: format = '%Y-%m-%d %H:%M:%S' adjustment = 3600 timeZone = 'America/New_York' getDateTime(format, adjustment, timeZone, currentDateTime) In the first example, the current date and time are retrieved, adjusted by 3600 seconds (1 hour), converted to UTC, and stored in the variable currentTime. In the second example, variables are used to define the format, time adjustment, and time zone, with the result stored in the currentDateTime variable. encodeMD5() The encodeMD5() command generates an MD5 hash of the provided string and stores the result in a target variable. MD5 is a cryptographic hash function that produces a 128-bit value (32 hexadecimal characters), commonly used to verify data integrity. Parameters SourceVariable Type: var Description: The variable containing the text string to be encoded in MD5. It can be a direct value or a variable storing the input string. TargetVariable Type: var Description: The variable in which the resulting MD5 hash will be stored. Unlike the SourceVariable parameter, this must be a variable and not a direct value. Usage Example // Direct call with values: encodeMD5('example_string', md5Hash) // Call using variables: text = 'example_string' hashVariable = 'md5Hash' encodeMD5(text, hashVariable) In the first example, an MD5 hash is generated from the string 'example_string' and stored in the md5Hash variable. In the second example, a variable text is used to define the input string and another variable hashVariable is used to store the resulting MD5 hash. encodeSHA256() The encodeSHA256() command generates a SHA-256 hash of the provided string and stores the result in a target variable. SHA-256 is a cryptographic hash function that produces a 256-bit value (64 hexadecimal characters), offering greater security compared to MD5. Parameters SourceVariable Type: var Description: The variable containing the text string to be encoded in SHA-256. It can be a direct value or a variable storing the input string. TargetVariable Type: var Description: The variable in which the resulting SHA-256 hash will be stored. Unlike the SourceVariable parameter, this must be a variable and not a direct value. Usage Example // Direct call with values: encodeSHA256('example_string', sha256Hash) // Call using variables: text = 'example_string' hashVariable = 'sha256Hash' encodeSHA256(text, hashVariable) In the first example, a SHA-256 hash is generated from the string 'example_string' and stored in the sha256Hash variable. In the second example, a variable text is used to define the input string, and another variable hashVariable is used to store the resulting SHA-256 hash. getQueryParamList() The getQueryParamList() command extracts the query parameters from the current HTTP request and stores a list of these parameters in a target variable. This is useful for handling and processing query parameters in web applications. Parameters TargetVariable Type: var Description: The variable in which the extracted query parameter list will be stored. This should be a variable where the command's result will be saved. Command Flow Parameter Extraction: Accesses the query parameters from the current HTTP request. List Construction: Creates a list containing dictionaries, where each dictionary represents a query parameter and its associated value. Result Storage: Saves the list of parameters in the variable specified by TargetVariable. Usage Example Suppose the HTTP query has the following parameters: ?user=alice&age=30. // Define the variable to store the result queryParamsList = [] // Call the command to extract query parameters getQueryParamList(queryParamsList) // Return the list of query parameters via addResult addResult(queryParamsList) Given the query string ?user=alice&age=30, the getQueryParamList() command will generate the following list of parameters: [ {\"user\": \"alice\"}, {\"age\": \"30\"} ] getListLen() The getListLen() command calculates the length of a list and stores the result in a target variable. This command is useful for determining the number of elements in a list. Parameters SourceVariable Type: var Description: The variable containing the list whose length you want to calculate. It can be a variable that stores the list or a direct value representing the list. TargetVariable Type: var Description: The variable where the result of the list length will be stored. This should be a variable that will receive the integer value representing the number of elements in the list. Command Flow Retrieve the List: Access the list stored in the SourceVariable. Calculate the Length: Calculate the number of elements in the list. Store the Result: Save the calculated length in the variable specified by TargetVariable. Usage Example Suppose the list in myList is ['apple', 'banana', 'cherry']. // Variable definitions myList = ['apple', 'banana', 'cherry'] listLength = 0 // Call the command to calculate the length of the list getListLen(myList, listLength) // Return the list length through addResult addResult(listLength) Since the list myList has 3 elements, the getListLen() command will calculate that the length is 3. This value will be stored in the listLength variable and returned through addResult(listLength), resulting in the following output: 3 itemFromList() The itemFromList() command extracts a specific element from a list based on a given index and stores the result in a target variable. This is useful for accessing individual elements within a list. Parameters SourceVariable Type: var Description: The variable containing the list from which an element is to be extracted. It can be a variable that stores the list or a direct value representing the list. index Type: value Description: The index of the element to be extracted from the list. It must be an integer value that indicates the position of the element within the list. TargetVariable Type: var Description: The variable where the extracted element will be stored. It must be a variable that will receive the value of the element at the specified index position. Command Flow Access the List: Access the list stored in the SourceVariable. Extract the Element: Retrieve the element at the position specified by the index. Store the Result: Save the extracted element in the variable specified by TargetVariable. Usage Example Suppose the list in myList is ['apple', 'banana', 'cherry'] and you want to extract the element at index 1. // Variable definitions myList = ['apple', 'banana', 'cherry'] element = '' // Call the command to extract the element at index 1 itemFromList(myList, 1, element) // Return the extracted element through addResult addResult(element) Since index 1 corresponds to the element 'banana' in the myList, the itemFromList() command will extract 'banana' and store it in the variable element. The element variable will be returned through addResult(element), resulting in the following output: \"banana\" variableFromJSON() The variableFromJSON() command extracts the value associated with a specific key from a JSON object and stores the result in a target variable. This command is useful for accessing values within a JSON object. Parameters SourceVariable Type: var Description: The variable containing the JSON object from which a value is to be extracted. It can be a variable that stores the JSON object or a direct value representing the JSON object. key Type: value Description: The key whose value is to be extracted from the JSON object. It must be a value that represents the key within the JSON object. TargetVariable Type: var Description: The variable where the extracted value will be stored. It must be a variable that will receive the value associated with the specified key in the JSON object. Command Flow Access the JSON Object: Access the JSON object stored in the SourceVariable. Extract the Value: Retrieve the value associated with the key within the JSON object. Store the Result: Save the extracted value in the variable specified by TargetVariable. Usage Example Suppose the JSON object in jsonData is \"name\": \"Alice\", \"age\": 30 and you want to extract the value associated with the key \"name\". // Variable definitions jsonData = {\"name\": \"Alice\", \"age\": 30} nameValue = '' // Call the command to extract the value associated with the key \"name\" variableFromJSON(jsonData, \"name\", nameValue) // Return the extracted value through addResult addResult(nameValue) Since the value associated with the key \"name\" in the JSON object jsonData is \"Alice\", the variableFromJSON() command will extract \"Alice\" and store it in the variable nameValue. The nameValue variable will be returned through addResult(nameValue), resulting in the following output: \"Alice\" AddVariableToJSON() The AddVariableToJSON() command adds a new key and its corresponding value to a JSON object and stores the result in a target variable. This command is useful for updating a JSON object with new key-value pairs. Parameters Key Type: variable Description: The key to be added to the JSON object. It must be a variable that stores the key to be added. Value Type: variable Description: The value associated with the key to be added to the JSON object. It must be a variable that stores the corresponding value. TargetVariable Type: variable Description: The variable where the updated JSON object will be stored. It must be a variable that will receive the JSON object with the new key and its added value. Command Flow Access the JSON Object: Access the JSON object stored in the TargetVariable. Add the Key and Value: Add the new key and its associated value to the JSON object. Store the Result: Save the updated JSON object in the variable specified by TargetVariable. Usage Example Suppose the initial JSON object in jsonData is \"name\": \"Alice\", \"age\": 30, and you want to add a new key \"email\" with the value \"alice@example.com\". // Variable definitions jsonData = {\"name\": \"Alice\", \"age\": 30} newKey = \"email\" newValue = \"alice@example.com\" // Call the command to add the new key and value to the JSON object AddVariableToJSON(newKey, newValue, jsonData) // Return the updated JSON object through addResult addResult(jsonData) This updated JSON object will be stored in the variable jsonData and will be returned through addResult(jsonData), resulting in the following output: { \"name\": \"Alice\", \"age\": 30, \"email\": \"alice@example.com\" } variableToList() The variableToList() command converts an element into a list that contains only that element and stores the resulting list in a target variable. This command is useful to ensure that a single value is handled as a list in subsequent processing. Parameters element Type: variable Description: The variable that contains the element to be converted into a list. It can be any type of value that you want to include as the only item in the list. TargetVariable Type: variable Description: The variable in which the resulting list will be stored. It must be a variable that will receive the list with the included element. Command Flow Access the Element: Access the element stored in the element variable. Create the List: Create a list that contains only the provided element. Store the Result: Save the resulting list in the variable specified by TargetVariable. Usage Example Suppose the element in myElement is \"apple\" and you want to convert it into a list. // Variable definitions myElement = \"apple\" myList = [] // Call the command to convert the element into a list variableToList(myElement, myList) // Return the resulting list through addResult addResult(myList) Since myElement is \"apple\", the variableToList() command will convert this element into a list with a single item: [\"apple\"]. This list will be stored in the variable myList, and myList will be returned through addResult(myList), resulting in the following output: [\"apple\"] addParam() The addParam() command retrieves the value associated with a specific key from the query string of the current request and assigns this value to a target variable. This command is useful for extracting values from query parameters in an HTTP request and storing them in variables for processing. Parameters param Type: value Description: The key of the query string whose value you want to retrieve. It should be a value that represents the key in the query string. variable Type: var Description: The variable in which the retrieved value from the query string will be stored. It must be a variable that will receive the value associated with the specified key. Command Flow Retrieve the Value: Access the value associated with the param key from the query string of the current request. Assign the Value: Assign the retrieved value to the variable specified by variable. Usage Example Suppose the query string of the current request is ?user=alice&age=30, and you want to retrieve the value associated with the key \"user\". // Variable definitions userName = '' // Call the command to retrieve the value for the \"user\" key and assign it to the variable addParam(\"user\", userName) // Return the retrieved value through addResult addResult(userName) Given the query string ?user=alice&age=30, the addParam() command will retrieve the value \"alice\" associated with the key \"user\" and store it in the userName variable. The userName variable will be returned through addResult(userName), resulting in the following output: \"alice\" addResult() The addResult() command is used to return the content of a variable as part of the command or function response. It is the way to present results or processed data from commands and operations performed in the language. Parameters variable Type: var Description: The variable whose content is to be returned as the result. It should be a variable that contains the value or data you want to include in the response. Command Flow Access the Content: Access the content of the variable provided as a parameter. Return the Result: Include the content of the variable in the final response. Example Usage Suppose we have performed an operation and want to return the result stored in the result variable. // Define the variable with the result of an operation result = \"Operation completed successfully.\" // Call the command to return the content of the variable addResult(result) In this example, the addResult(result) command will return the content of the result variable, which is \"Operation completed successfully.\". This content will be presented as part of the response. Note The addResult() command is the primary mechanism for returning information and results in the language. Make sure that the variable passed to the command contains the desired data or result before calling addResult(). RequestPost() The RequestPost() command performs an HTTP POST request to a specified URL, sending a query string, headers, and a request body, and stores the result of the request in a destination variable. This command is useful for sending data to a server and handling the responses from the request. Parameters url Type: variable Description: The URL to which the POST request will be sent. It should be a variable containing the address of the resource to which the request is to be made. querystring Type: variable Description: The query string that will be appended to the URL. It should be a variable containing the query parameters in string format. headers Type: variable Description: The HTTP headers that will be included in the POST request. It should be a variable containing a dictionary of headers and their values. body Type: variable Description: The body of the POST request that will be sent to the server. It should be a variable containing the data to be sent in the request. o_result Type: variable Description: The variable in which the result of the POST request will be stored. It should be a variable that will receive the server's response. Command Flow Build the Request: Uses the provided URL, query string, headers, and body to construct the POST request. Send the Request: Sends the POST request to the specified server. Store the Result: Saves the server's response in the variable specified by o_result. Example Usage Suppose you want to send a POST request to https://api.example.com/data, with a query string userId=123, headers including Content-Type: application/json, and a body with JSON data. // Define variables url = \"https://api.example.com/data\" querystring = \"userId=123\" headers = {\"Content-Type\": \"application/json\"} body = '{\"name\": \"Alice\", \"age\": 30}' response = '' // Call the command to perform the POST request RequestPost(url, querystring, headers, body, response) // Return the request result via addResult addResult(response) In this example, the RequestPost() command will send a POST request to https://api.example.com/data with the provided query string, headers, and body. The server's response will be stored in the response variable, and this variable will be returned via addResult(response). The result of the request will be included in the final response. ormCreateTable() The ormCreateTable() command creates a new table in a database using the specified ORM (Object-Relational Mapping). This command defines the columns of the table and their data types, and stores a reference to the created table in a destination variable. Parameters fields Type: value Description: A string containing the names of the table columns, separated by commas. Each column name should correspond to a field in the table. fieldsType Type: value Description: A string containing the data types for each column, separated by commas. The data types should be in the same order as the column names in fields. dbaseName Type: value Description: The name of the database where the table will be created. It should be a string indicating the target database. varTarget Type: variable Description: The variable in which the reference to the created table will be stored. It should be a variable that will receive the reference to the new table. Command Flow Define the Table: Uses the column names (fields) and their data types (fieldsType) to define the structure of the new table. Create the Table: Creates the table in the database specified by dbaseName using the provided definition. Store the Result: Saves the reference to the created table in the variable specified by varTarget. Example Usage Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. // Define variables fields = \"username,age\" fieldsType = \"VARCHAR,INTEGER\" dbaseName = \"myDatabase\" tableReference = '' // Call the command to create the table ormCreateTable(fields, fieldsType, dbaseName, tableReference) // Return the reference to the created table via addResult addResult(tableReference) In this example, the ormCreateTable() command will create a table in the myDatabase database with the specified columns and data types. The reference to the new table will be stored in the tableReference variable, and this variable will be returned via addResult(tableReference). The output will include the reference to the created table. ormCheckTable() The ormCheckTable() command checks for the existence of a table in a specific database and stores the result in a destination variable. This command is useful for verifying if a table already exists before attempting further operations on it. Parameters dbaseName Type: value Description: The name of the database in which the table's existence should be checked. It should be a string indicating the database to check. varTarget Type: variable Description: The variable in which the result of the check will be stored. It should be a variable that will receive a value indicating whether the table exists or not. Command Flow Check Existence: Accesses the database specified by dbaseName to verify if the requested table exists. Store the Result: Saves the result of the check in the variable specified by varTarget. The stored value will indicate whether the table exists (True or False). Example Usage Suppose you want to check if a table called users exists in a database called myDatabase. // Define variables dbaseName = \"myDatabase\" tableExists = '' // Call the command to check the existence of the table ormCheckTable(dbaseName, tableExists) // Return the result of the check via addResult addResult(tableExists) In this example, the ormCheckTable() command will check for the existence of the users table in the myDatabase database. The result of the check (whether the table exists or not) will be stored in the tableExists variable, and this variable will be returned via addResult(tableExists). The output will reflect whether the table exists (True) or not (False). ormAccessUpdate() The ormAccessUpdate() command updates records in a database table based on the provided selection criteria. This command modifies the values of specified fields in a database using the corresponding values from variables. Parameters fields Type: variable Description: A string containing the names of the fields to be updated. The field names should be separated by commas. fieldsValuesVariables Type: variable Description: A string containing the names of the variables holding the new values for the specified fields. The variable names should be separated by commas, in the same order as the fields in fields. dbase Type: variable Description: The name of the database where the table to be updated is located. It should be a variable containing the name of the database. selector Type: variable Description: A condition to select the records to be updated. It should be a string specifying the selection criteria in SQL format, such as id = 1. varTarget Type: variable Description: The variable in which the result of the update operation will be stored. It should be a variable that will receive a value indicating whether the update was successful or not. Command Flow Define Fields and Values: Uses the field names (fields) and the variables with the values to be updated (fieldsValuesVariables) to define which records should be modified and with what data. Select Records: Uses the condition provided in selector to identify the records to be updated. Update the Database: Performs the update in the database specified by dbase, applying the changes to the records that meet the selector condition. Store the Result: Saves the result of the update operation in the variable specified by varTarget. The stored value will indicate whether the update was successful (True) or failed (False). Example Usage Suppose you want to update the age field to 31 for the user with id equal to 1 in a database called myDatabase. // Define variables fields = \"age\" fieldsValuesVariables = \"newAge\" dbase = \"myDatabase\" selector = \"id = 1\" updateSuccess = '' // Define the variable holding the new value newAge = 31 // Call the command to update the record ormAccessUpdate(fields, fieldsValuesVariables, dbase, selector, updateSuccess) // Return the result of the update via addResult addResult(updateSuccess) In this example, the ormAccessUpdate() command will update the age field in the myDatabase database for the record where id = 1. The new value for age is 31, stored in the newAge variable. The updateSuccess variable will store the result of the operation (whether it was successful or not), and this variable will be returned via addResult(updateSuccess). ormAccessSelect() The ormAccessSelect() command retrieves records from a table in a database based on the provided selection criteria. This command selects the desired fields and stores the results in a target variable. Parameters fields Type: variable Description: A string containing the names of the fields to be retrieved. The field names should be separated by commas. dbase Type: variable Description: The name of the database from which records should be retrieved. It must be a variable containing the name of the database. selector Type: variable Description: A condition to select the records to be retrieved. It must be a string specifying the selection criteria in SQL format, such as id = 1. varTarget Type: variable Description: The variable in which the query results will be stored. It must be a variable that will receive a list of dictionaries, each representing a retrieved record. Command Flow Defining the Fields: Use the field names (fields) to specify which data should be retrieved. Selecting Records: Use the condition provided in selector to identify which records should be selected from the database. Retrieving Data: Access the database specified by dbase and retrieve the records that meet the selector condition, including only the specified fields. Storing the Result: Save the query results in the variable specified by varTarget. The stored value will be a list of dictionaries, where each dictionary represents a retrieved record with the requested fields. Example Usage Suppose you want to retrieve the username field for all users where age is greater than 25 from a database called myDatabase. // Define variables fields = \"username\" dbase = \"myDatabase\" selector = \"age > 25\" usersList = '' // Call the command to retrieve the records ormAccessSelect(fields, dbase, selector, usersList) // Return the query results via addResult addResult(usersList) In this example, the ormAccessSelect() command will retrieve the username field for all users in the myDatabase database where age is greater than 25. The results will be stored in the usersList variable, and this variable will be returned via addResult(usersList). The output will be a list of dictionaries, each representing a user whose username has been retrieved. ormAccessInsert() The ormAccessInsert() command inserts a new record into a database table using the provided values for the fields. This command defines the fields and their corresponding values, and stores the result of the operation in a target variable. Parameters fields Type: variable Description: A string containing the names of the fields into which the values will be inserted. The field names should be separated by commas. fieldsValuesVariables Type: variable Description: A string containing the names of the variables that hold the values to be inserted into the specified fields. The variable names should be separated by commas, in the same order as the fields in fields. dbase Type: variable Description: The name of the database where the table into which the new record should be inserted is located. It must be a variable containing the name of the database. varTarget Type: variable Description: The variable in which the result of the insertion operation will be stored. It must be a variable that will receive a value indicating whether the insertion was successful or not. Command Flow Defining the Fields and Values: Use the field names (fields) and the variables with the values to be inserted (fieldsValuesVariables) to define what data should be inserted. Inserting into the Database: Perform the insertion of the new record into the database specified by dbase, using the provided values. Storing the Result: Save the result of the insertion operation in the variable specified by varTarget. The stored value will indicate whether the insertion was successful (True) or failed (False). Example Usage Suppose you want to insert a new record into a table called users in a database called myDatabase, with values for username and age coming from the variables newUsername and newAge. // Define variables fields = \"username,age\" fieldsValuesVariables = \"newUsername,newAge\" dbase = \"myDatabase\" insertSuccess = '' // Define the variables with the new values newUsername = \"Alice\" newAge = 31 // Call the command to insert the new record ormAccessInsert(fields, fieldsValuesVariables, dbase, insertSuccess) // Return the result of the insertion via addResult addResult(insertSuccess) In this example, the ormAccessInsert() command will insert a new record into the myDatabase database in the users table. The values for username and age are provided by the newUsername and newAge variables. The insertSuccess variable will store the result of the operation (whether it was successful or not), and this variable will be returned via addResult(insertSuccess). The output will reflect whether the insertion was successful (True) or failed (False). ormAI() The ormAI() command uses an artificial intelligence model to convert a natural language query into an SQL statement, which is then executed against a database. This command processes a natural language query to generate an SQL statement that is executed on the table specified in the source parameter, and stores the result in a target variable. Parameters prompt Type: variable Description: A string in natural language that describes the query to be made. For example, \"get the value of the row with id 5\". source Type: variable Description: The name of the table on which the generated query should be executed. It must be a variable containing the name of the table in the database. TargetVariable Type: variable Description: The variable in which the result of the query will be stored. It must be a variable that will receive the result of the generated and executed SQL query. Command Flow Generating SQL Query: Use the artificial intelligence model to convert the prompt into an SQL statement. For example, if the prompt is \"get the value of the row with id 5\", the AI will generate the SQL query SELECT * FROM source WHERE id = 5;. Executing the Query: Execute the generated SQL statement on the table specified in source. Storing the Result: Save the result of the query execution in the variable specified by TargetVariable. The result will be the dataset retrieved by the executed SQL statement. Example Usage Suppose you want to retrieve all the data from the row with id equal to 5 from a table called users. // Define variables prompt = \"get the value of the row with id 5\" source = \"users\" queryResult = '' // Call the command to process the query ormAI(prompt, source, queryResult) // Return the query result via addResult addResult(queryResult) In this example, the ormAI() command will convert the prompt into an SQL query: SELECT * FROM users WHERE id = 5;. This query will be executed on the users table, and the results will be stored in the queryResult variable. The queryResult variable will be returned via addResult(queryResult). The output will be the dataset retrieved by the executed SQL statement. functionAI() The functionAI() command uses an artificial intelligence model to convert a natural language description of a function or process into a code implementation, which is then executed and returns the result. This command converts a description provided in prompt into a function that operates on the data of the table specified in source, and stores the result in a target variable. Parameters prompt Type: variable Description: A string in natural language that describes the process or function to be executed. For example, \"calculate the average of the salary column\". source Type: variable Description: The name of the table on which the generated function should be executed. It must be a variable containing the name of the table in the database. TargetVariable Type: variable Description: The variable in which the result of the executed function or process will be stored. It must be a variable that will receive the result of the generated and executed code. Command Flow Generating Code: Use the artificial intelligence model to convert the prompt into a code implementation. For example, if the prompt is \"calculate the average of the salary column\", the AI will generate the code necessary to calculate the average of that column. Executing the Code: Execute the generated code on the table specified in source. Storing the Result: Save the result of the code execution in the variable specified by TargetVariable. The result will be the calculated value or the dataset produced by the executed code. Example Usage Suppose you want to calculate the average of the salary column in a table called employees. // Define variables prompt = \"calculate the average of the salary column\" source = \"employees\" averageSalary = '' // Call the command to process the function functionAI(prompt, source, averageSalary) // Return the result of the function via addResult addResult(averageSalary) In this example, the functionAI() command will convert the prompt into a code implementation to calculate the average of the salary column in the employees table. The result of the calculation will be stored in the averageSalary variable, and this variable will be returned via addResult(averageSalary). The output will be the calculated average of the salary column.\n",
      "\n",
      "[4] id=chunk-4 source=24_Master_example.txt\n",
      "Master Example (Combining Sections) This example shows how a real flow uses almost all sections: // SECTION I & II: Registration and Input registerEndpoint(\"/v1/user\", \"POST\", [], \"Create User\", main, final_res) function main(){ addParam(\"user\", u) addParam(\"pass\", p) // SECTION III & VI: Validation and Security if(u, None, \"==\") addVar(_status, 400) return(\"User is required\") end() encodeSHA256(p, pass_hash) // SECTION IV: Asynchrony (Audit log) go_async(\"audit\") ormDirect(\"INSERT INTO audit (event) VALUES ('User creation attempt')\", r) end() // SECTION V: Persistence db = avapConnector(\"TOKEN_DB\") res_db = db.query(\"INSERT INTO users (name, pass) VALUES ('%s', '%s')\" % (u, pass_hash)) // SECTION II: Response addVar(_status, 201) addResult(res_db) return(res_db) }\n",
      "================================\u001b[1m Human Message \u001b[0m=================================\n",
      "\n",
      "Suppose you want to create a table called users in a database called myDatabase, with two columns: username of type VARCHAR and age of type INTEGER. How would you do that in AVAP?\n"
     ]
    },
    {
     "ename": "TypeError",
     "evalue": "generate() missing 1 required positional argument: 'state'",
     "output_type": "error",
     "traceback": [
      "\u001b[31m---------------------------------------------------------------------------\u001b[39m",
      "\u001b[31mTypeError\u001b[39m                                 Traceback (most recent call last)",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[63]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m a = \u001b[43mstream_graph_updates\u001b[49m\u001b[43m(\u001b[49m\u001b[43muser_input\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mguided_graph\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[61]\u001b[39m\u001b[32m, line 7\u001b[39m, in \u001b[36mstream_graph_updates\u001b[39m\u001b[34m(user_input, graph)\u001b[39m\n\u001b[32m      6\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mstream_graph_updates\u001b[39m(user_input: \u001b[38;5;28mstr\u001b[39m, graph: StateGraph):\n\u001b[32m----> \u001b[39m\u001b[32m7\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mevent\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mgraph\u001b[49m\u001b[43m.\u001b[49m\u001b[43mstream\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m      8\u001b[39m \u001b[43m        \u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmessages\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43m[\u001b[49m\u001b[43m{\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mrole\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43muser\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mcontent\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43muser_input\u001b[49m\u001b[43m}\u001b[49m\u001b[43m]\u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m      9\u001b[39m \u001b[43m        \u001b[49m\u001b[38;5;66;43;03m#config=config,\u001b[39;49;00m\n\u001b[32m     10\u001b[39m \u001b[43m        \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m=\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mvalues\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\n\u001b[32m     11\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m     12\u001b[39m \u001b[43m        \u001b[49m\u001b[43mevent\u001b[49m\u001b[43m[\u001b[49m\u001b[33;43m\"\u001b[39;49m\u001b[33;43mmessages\u001b[39;49m\u001b[33;43m\"\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m[\u001b[49m\u001b[43m-\u001b[49m\u001b[32;43m1\u001b[39;49m\u001b[43m]\u001b[49m\u001b[43m.\u001b[49m\u001b[43mpretty_print\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n",
      "\u001b[36mFile \u001b[39m\u001b[32m~/VsCodeProjects/assistance-engine/.venv/lib/python3.12/site-packages/langgraph/pregel/main.py:2646\u001b[39m, in \u001b[36mPregel.stream\u001b[39m\u001b[34m(self, input, config, context, stream_mode, print_mode, output_keys, interrupt_before, interrupt_after, durability, subgraphs, debug, **kwargs)\u001b[39m\n\u001b[32m   2644\u001b[39m \u001b[38;5;28;01mfor\u001b[39;00m task \u001b[38;5;129;01min\u001b[39;00m loop.match_cached_writes():\n\u001b[32m   2645\u001b[39m     loop.output_writes(task.id, task.writes, cached=\u001b[38;5;28;01mTrue\u001b[39;00m)\n\u001b[32m-> \u001b[39m\u001b[32m2646\u001b[39m \u001b[43m\u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mrunner\u001b[49m\u001b[43m.\u001b[49m\u001b[43mtick\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   2647\u001b[39m \u001b[43m    \u001b[49m\u001b[43m[\u001b[49m\u001b[43mt\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mfor\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mt\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;129;43;01min\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mloop\u001b[49m\u001b[43m.\u001b[49m\u001b[43mtasks\u001b[49m\u001b[43m.\u001b[49m\u001b[43mvalues\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[38;5;129;43;01mnot\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mt\u001b[49m\u001b[43m.\u001b[49m\u001b[43mwrites\u001b[49m\u001b[43m]\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2648\u001b[39m \u001b[43m    \u001b[49m\u001b[43mtimeout\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mstep_timeout\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2649\u001b[39m \u001b[43m    \u001b[49m\u001b[43mget_waiter\u001b[49m\u001b[43m=\u001b[49m\u001b[43mget_waiter\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2650\u001b[39m \u001b[43m    \u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m=\u001b[49m\u001b[43mloop\u001b[49m\u001b[43m.\u001b[49m\u001b[43maccept_push\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m   2651\u001b[39m \u001b[43m\u001b[49m\u001b[43m)\u001b[49m\u001b[43m:\u001b[49m\n\u001b[32m   2652\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;66;43;03m# emit output\u001b[39;49;00m\n\u001b[32m   2653\u001b[39m \u001b[43m    \u001b[49m\u001b[38;5;28;43;01myield from\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43m_output\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m   2654\u001b[39m \u001b[43m        \u001b[49m\u001b[43mstream_mode\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mprint_mode\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43msubgraphs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mstream\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mqueue\u001b[49m\u001b[43m.\u001b[49m\u001b[43mEmpty\u001b[49m\n\u001b[32m   2655\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m   2656\u001b[39m loop.after_tick()\n",
      "\u001b[36mFile \u001b[39m\u001b[32m~/VsCodeProjects/assistance-engine/.venv/lib/python3.12/site-packages/langgraph/pregel/_runner.py:167\u001b[39m, in \u001b[36mPregelRunner.tick\u001b[39m\u001b[34m(self, tasks, reraise, timeout, retry_policy, get_waiter, schedule_task)\u001b[39m\n\u001b[32m    165\u001b[39m t = tasks[\u001b[32m0\u001b[39m]\n\u001b[32m    166\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m167\u001b[39m     \u001b[43mrun_with_retry\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    168\u001b[39m \u001b[43m        \u001b[49m\u001b[43mt\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    169\u001b[39m \u001b[43m        \u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    170\u001b[39m \u001b[43m        \u001b[49m\u001b[43mconfigurable\u001b[49m\u001b[43m=\u001b[49m\u001b[43m{\u001b[49m\n\u001b[32m    171\u001b[39m \u001b[43m            \u001b[49m\u001b[43mCONFIG_KEY_CALL\u001b[49m\u001b[43m:\u001b[49m\u001b[43m \u001b[49m\u001b[43mpartial\u001b[49m\u001b[43m(\u001b[49m\n\u001b[32m    172\u001b[39m \u001b[43m                \u001b[49m\u001b[43m_call\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    173\u001b[39m \u001b[43m                \u001b[49m\u001b[43mweakref\u001b[49m\u001b[43m.\u001b[49m\u001b[43mref\u001b[49m\u001b[43m(\u001b[49m\u001b[43mt\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    174\u001b[39m \u001b[43m                \u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m=\u001b[49m\u001b[43mretry_policy\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    175\u001b[39m \u001b[43m                \u001b[49m\u001b[43mfutures\u001b[49m\u001b[43m=\u001b[49m\u001b[43mweakref\u001b[49m\u001b[43m.\u001b[49m\u001b[43mref\u001b[49m\u001b[43m(\u001b[49m\u001b[43mfutures\u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    176\u001b[39m \u001b[43m                \u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m=\u001b[49m\u001b[43mschedule_task\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    177\u001b[39m \u001b[43m                \u001b[49m\u001b[43msubmit\u001b[49m\u001b[43m=\u001b[49m\u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43msubmit\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    178\u001b[39m \u001b[43m            \u001b[49m\u001b[43m)\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    179\u001b[39m \u001b[43m        \u001b[49m\u001b[43m}\u001b[49m\u001b[43m,\u001b[49m\n\u001b[32m    180\u001b[39m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    181\u001b[39m     \u001b[38;5;28mself\u001b[39m.commit(t, \u001b[38;5;28;01mNone\u001b[39;00m)\n\u001b[32m    182\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m \u001b[38;5;167;01mException\u001b[39;00m \u001b[38;5;28;01mas\u001b[39;00m exc:\n",
      "\u001b[36mFile \u001b[39m\u001b[32m~/VsCodeProjects/assistance-engine/.venv/lib/python3.12/site-packages/langgraph/pregel/_retry.py:42\u001b[39m, in \u001b[36mrun_with_retry\u001b[39m\u001b[34m(task, retry_policy, configurable)\u001b[39m\n\u001b[32m     40\u001b[39m     task.writes.clear()\n\u001b[32m     41\u001b[39m     \u001b[38;5;66;03m# run the task\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m42\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mtask\u001b[49m\u001b[43m.\u001b[49m\u001b[43mproc\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m(\u001b[49m\u001b[43mtask\u001b[49m\u001b[43m.\u001b[49m\u001b[43minput\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m     43\u001b[39m \u001b[38;5;28;01mexcept\u001b[39;00m ParentCommand \u001b[38;5;28;01mas\u001b[39;00m exc:\n\u001b[32m     44\u001b[39m     ns: \u001b[38;5;28mstr\u001b[39m = config[CONF][CONFIG_KEY_CHECKPOINT_NS]\n",
      "\u001b[36mFile \u001b[39m\u001b[32m~/VsCodeProjects/assistance-engine/.venv/lib/python3.12/site-packages/langgraph/_internal/_runnable.py:656\u001b[39m, in \u001b[36mRunnableSeq.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m    654\u001b[39m     \u001b[38;5;66;03m# run in context\u001b[39;00m\n\u001b[32m    655\u001b[39m     \u001b[38;5;28;01mwith\u001b[39;00m set_config_context(config, run) \u001b[38;5;28;01mas\u001b[39;00m context:\n\u001b[32m--> \u001b[39m\u001b[32m656\u001b[39m         \u001b[38;5;28minput\u001b[39m = \u001b[43mcontext\u001b[49m\u001b[43m.\u001b[49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[43mstep\u001b[49m\u001b[43m.\u001b[49m\u001b[43minvoke\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43minput\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mconfig\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    657\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m    658\u001b[39m     \u001b[38;5;28minput\u001b[39m = step.invoke(\u001b[38;5;28minput\u001b[39m, config)\n",
      "\u001b[36mFile \u001b[39m\u001b[32m~/VsCodeProjects/assistance-engine/.venv/lib/python3.12/site-packages/langgraph/_internal/_runnable.py:400\u001b[39m, in \u001b[36mRunnableCallable.invoke\u001b[39m\u001b[34m(self, input, config, **kwargs)\u001b[39m\n\u001b[32m    398\u001b[39m         run_manager.on_chain_end(ret)\n\u001b[32m    399\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n\u001b[32m--> \u001b[39m\u001b[32m400\u001b[39m     ret = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mfunc\u001b[49m\u001b[43m(\u001b[49m\u001b[43m*\u001b[49m\u001b[43margs\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m*\u001b[49m\u001b[43m*\u001b[49m\u001b[43mkwargs\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m    401\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mself\u001b[39m.recurse \u001b[38;5;129;01mand\u001b[39;00m \u001b[38;5;28misinstance\u001b[39m(ret, Runnable):\n\u001b[32m    402\u001b[39m     \u001b[38;5;28;01mreturn\u001b[39;00m ret.invoke(\u001b[38;5;28minput\u001b[39m, config)\n",
      "\u001b[31mTypeError\u001b[39m: generate() missing 1 required positional argument: 'state'",
      "During task with name 'generate' and id 'c4306dab-0608-b459-1e48-2e3f8bf6fec2'"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Failed to export span batch code: 404, reason: <!DOCTYPE html><html lang=\"en\"><head><meta charSet=\"utf-8\"/><meta name=\"viewport\" content=\"width=device-width\"/><meta name=\"next-head-count\" content=\"2\"/><link rel=\"preload\" href=\"/_next/static/css/1d1bf8ebf039f876.css\" as=\"style\"/><link rel=\"stylesheet\" href=\"/_next/static/css/1d1bf8ebf039f876.css\" data-n-g=\"\"/><noscript data-n-css=\"\"></noscript><script defer=\"\" nomodule=\"\" src=\"/_next/static/chunks/polyfills-42372ed130431b0a.js\"></script><script src=\"/_next/static/chunks/webpack-fafe7122277f5772.js\" defer=\"\"></script><script src=\"/_next/static/chunks/framework-d2dcb18632b956b2.js\" defer=\"\"></script><script src=\"/_next/static/chunks/main-19694d19b6f6c228.js\" defer=\"\"></script><script src=\"/_next/static/chunks/pages/_app-9e6c56ce79ebaf0a.js\" defer=\"\"></script><script src=\"/_next/static/chunks/pages/_error-881d11b9e6da73d1.js\" defer=\"\"></script><script src=\"/_next/static/Eu5QEyLpa3Avvo-CHkMDG/_buildManifest.js\" defer=\"\"></script><script src=\"/_next/static/Eu5QEyLpa3Avvo-CHkMDG/_ssgManifest.js\" defer=\"\"></script></head><body><div id=\"__next\"><script>!function(){try{var d=document.documentElement,c=d.classList;c.remove('light','dark');var e=localStorage.getItem('theme');if('system'===e||(!e&&true)){var t='(prefers-color-scheme: dark)',m=window.matchMedia(t);if(m.media!==t||m.matches){d.style.colorScheme = 'dark';c.add('dark')}else{d.style.colorScheme = 'light';c.add('light')}}else if(e){c.add(e|| '')}if(e==='light'||e==='dark')d.style.colorScheme=e}catch(e){}}()</script><div class=\"flex min-h-full flex-1 flex-col justify-center py-12 sm:px-6 lg:px-8\" data-sentry-component=\"Spinner\" data-sentry-source-file=\"spinner.tsx\"><div class=\"sm:mx-auto sm:w-full sm:max-w-md\"><img src=\"/icon.svg\" width=\"42\" height=\"42\" alt=\"Langfuse Icon\" class=\"mx-auto motion-safe:animate-spin\" data-sentry-component=\"LangfuseIcon\" data-sentry-source-file=\"LangfuseLogo.tsx\"/><h2 class=\"mt-5 text-center text-2xl font-bold leading-9 tracking-tight text-primary\">Loading<!-- --> ...</h2></div></div></div><script id=\"__NEXT_DATA__\" type=\"application/json\">{\"props\":{\"pageProps\":{\"statusCode\":404}},\"page\":\"/_error\",\"query\":{},\"buildId\":\"Eu5QEyLpa3Avvo-CHkMDG\",\"nextExport\":true,\"isFallback\":false,\"gip\":true,\"locale\":\"en\",\"locales\":[\"en\"],\"defaultLocale\":\"en\",\"scriptLoader\":[]}</script></body></html>\n"
     ]
    },
    {
     "ename": "",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31mThe Kernel crashed while executing code in the current cell or a previous cell. \n",
      "\u001b[1;31mPlease review the code in the cell(s) to identify a possible cause of the failure. \n",
      "\u001b[1;31mClick <a href='https://aka.ms/vscodeJupyterKernelCrash'>here</a> for more info. \n",
      "\u001b[1;31mView Jupyter <a href='command:jupyter.viewOutput'>log</a> for further details."
     ]
    }
   ],
   "source": [
    "a = stream_graph_updates(user_input, guided_graph)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "assistance-engine",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
