diff --git a/ingestion/docs/10.3_Statements.txt b/ingestion/docs/10.3_Statements.txt index 2e4c423..4287273 100644 --- a/ingestion/docs/10.3_Statements.txt +++ b/ingestion/docs/10.3_Statements.txt @@ -81,12 +81,12 @@ startLoop() try: print(1 / 0) except: raise RuntimeError("Something went wrong") Break Statement In AVAP, the break statement is used to terminate the closest enclosing loop. The syntax for the break statement is as follows: -break +break() When a break statement is encountered, it causes the loop to exit immediately, regardless of the loop's condition or any remaining iterations. This effectively transfers control to the statement following the loop. The break statement is typically used within for or while loops to provide a way to exit the loop prematurely based on a certain condition. -for i in range(10): if i == 5: break print(i) print("Loop ended") +addVar(_status, "OK") startLoop(idx, 0, 9) if(idx, 4, "==") idx = -1 break() end() endLoop() addResult(idx) addStatus("OK") In this example, the loop will terminate when i equals 5, and "Loop ended" will be printed. The numbers 0 through 4 will be printed before the loop is exited. Break Statement @@ -109,16 +109,16 @@ When continue is used within a loop that is also handling exceptions with a try for i in range(10): try: if i % 2 == 0: continue print(i) finally: print("In finally clause") print("Loop ended") In this example, the continue statement will skip the current iteration when i is even, but before moving to the next iteration, the finally clause will print "In finally clause." For odd numbers, the loop will print the number and then "In finally clause." After the loop finishes, "Loop ended" will be printed. -Import Statement -In AVAP, the import statement is used to import an entire code file and define names in the local namespace. The syntax for the import statement is as follows: +Include Statement +In AVAP, the include statement is used to include an entire code file and define names in the local namespace. The syntax for the include statement is as follows: -import file.avap -The import statement in AVAP imports an entire code file and makes it available in the local namespace. No alias is assigned to the imported file; the file is simply referred to by its name. +include file.avap +The include statement in AVAP includes an entire code file and makes it available in the local namespace. No alias is assigned to the included file; the file is simply referred to by its name. For example: -# In the 'module.avap' file example_variable = 10 # In the main file import module.avap print(module.avap.example_variable) # Will print 10 -In this example, the main file imports the module.avap file and can access the example_variable defined in that file using the module.avap syntax. +# In the 'module.avap' file example_variable = 10 # In the main file include module.avap addResult(example_variable) # Will print 10 +In this example, the main file includess the module.avap file and can access the example_variable defined in that file using the module.avap syntax. Compound Statements In AVAP, compound statements contain (groups of) other statements; these affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, though in simpler representations a complete compound statement might be contained within a single line. @@ -133,7 +133,7 @@ In AVAP, control flow structures include conditional statements and loops, which If Statements The syntax for an if statement in AVAP is: -if (variable, variableValue, comparator, expression): code to execute +if (variable, variableValue, comparator, expression) code to execute else() code to execute end() This structure checks if the condition (variable compared to variableValue with the given comparator) is true, and if so, executes the block of code. Loops @@ -145,13 +145,13 @@ This structure initiates a loop where the variable iterates from the 'from' valu The if Statement The if statement in AVAP is used for conditional execution. The syntax is as follows: -if (variable, variableValue, comparator, expression): code to execute +if (variable, variableValue, comparator, expression) code to execute else() code to execute end() This statement evaluates the condition specified by the variable, variableValue, comparator, and expression. It selects exactly one of the suites (blocks of code) by evaluating the expressions one by one until a true condition is found. The corresponding suite is then executed. If all conditions are false, no suites are executed. The try Statement The try statement in AVAP specifies exception handlers and/or cleanup code for a block of statements. The syntax is as follows: -try(): code to execute except(): code to execute -The try block contains code that might raise an exception. The except block contains code to handle exceptions raised by the try block. If an exception occurs, control is transferred to the except block. If no exception occurs, the except block is skipped. +try() code to execute exception() code to execute end() +The try block contains code that might raise an exception. The exception block contains code to handle exceptions raised by the try block. If an exception occurs, control is transferred to the except block. If no exception occurs, the except block is skipped. Additional information about exceptions can be found in the section Exceptions, and information about using the raise statement to throw exceptions can be found in the section The raise Statement. \ No newline at end of file diff --git a/ingestion/docs/10_Execution_model_in_avap.txt b/ingestion/docs/10_Execution_model_in_avap.txt index 21f9a58..d90e6d4 100644 --- a/ingestion/docs/10_Execution_model_in_avap.txt +++ b/ingestion/docs/10_Execution_model_in_avap.txt @@ -35,14 +35,15 @@ Example of import usage: avap // Content of the file main.avap -addVar(10, x) -import functions.avap +addVar(x, 10) +include functions.avap myFunction(x) // Content of the file functions.avap -def myFunction(y): - addVar(y + 5, result) - print(result) +function myFunction(y){ + addVar(result, y + 5) + addResult(result) +} 4.4. Exceptions Exceptions in AVAP allow for the handling of errors or exceptional conditions. An exception is raised when an error is detected; it can be handled by the surrounding code block or by any code block that directly or indirectly invoked the block where the error occurred. @@ -50,10 +51,11 @@ The AVAP interpreter raises an exception when it detects a runtime error. An AVA Example of exception handling: -try: +try() addVar(10 / 0, result) -except ZeroDivisionError: - print("Cannot divide by zero.") +except() + addResult("Cannot divide by zero.") +end() In this example, if a division by zero occurs, a ZeroDivisionError exception is raised and handled by the except block. This structure ensures that AVAP programs execute in a sequential and predictable manner, without advanced dynamic or deferred execution features, maintaining simplicity and clarity in name binding and import handling. @@ -61,26 +63,27 @@ This structure ensures that AVAP programs execute in a sequential and predictabl 5. The Import System in AVAP AVAP code in one file gains access to code in another file through the import process. The import statement is the only way to invoke the import machinery in AVAP. -The import statement inserts the contents of the specified file at the exact point where the import statement appears in the original file. There are no other ways to invoke the import system in AVAP. +The include statement inserts the contents of the specified file at the exact point where the import statement appears in the original file. There are no other ways to invoke the import system in AVAP. -When an import statement is executed, the contents of the imported file are processed as if they were part of the original file, ensuring that all functions and variables from the imported file are available in the context of the original file. If the specified file is not found, a FileNotFoundError is raised. +When an include statement is executed, the contents of the imported file are processed as if they were part of the original file, ensuring that all functions and variables from the imported file are available in the context of the original file. If the specified file is not found, a FileNotFoundError is raised. -Example of using the import statement in AVAP: +Example of using the include statement in AVAP: Content of file main.avap -addVar(10, x) -import functions.avap +addVar(x,10) +include functions.avap myFunction(x) Content of file functions.avap -def myFunction(y): - addVar(y + 5, result) - print(result) +function myFunction(y){ + addVar(result, y + 5) + addResult(result) +} In this example, the content of functions.avap is inserted into main.avap at the point of the import statement, ensuring that myFunction is defined before being called. 5.1. Import Rules -Position of Import: The import statement must be placed at the exact location where the content of the imported file is to be included. The content of the imported file is executed linearly along with the original file. -Import Error: If the file specified in the import statement is not found, a FileNotFoundError is raised. +Position of Import: The include statement must be placed at the exact location where the content of the imported file is to be included. The content of the imported file is executed linearly along with the original file. +Import Error: If the file specified in the include statement is not found, a FileNotFoundError is raised. Scope of Imports: The functions and variables from the imported file are added to the local scope of the original file at the point of import. This means they can be accessed as if they were defined in the same file. 5.2. Limitations and Considerations No Packages: Unlike other languages, AVAP does not have a hierarchical package system. Each file is imported independently and treated as an autonomous unit. @@ -91,18 +94,19 @@ Consider the following example where multiple files are imported: Content of the file main.avap addVar(5, a) -import utilities.avap -import operations.avap +include utilities.avap +include operations.avap -addVar(utilities.increment(a), b) -addVar(operations.multiply(b, 2), c) -print(c) +addVar(b, increment(a)) +addVar( c, multiply(b, 2)) +addResult(c) Content of the file utilities.avap -def increment(x): - return x + 1 - +function increment(x){ + return(x + 1) +} Content of the file operations.avap -def multiply(x, y): - return x * y -In this example, utilities.avap and operations.avap are imported into main.avap at the specified points, allowing the increment and multiply functions to be used in main.avap. +function multiply(x, y){ + return(x * y) +} +In this example, utilities.avap and operations.avap are imported into main.avap at the specified points, allowing the increment and multiply functions to be used in main.avap. \ No newline at end of file diff --git a/ingestion/docs/11_Conditional_statements.txt b/ingestion/docs/11_Conditional_statements.txt index d24ad22..fe842fd 100644 --- a/ingestion/docs/11_Conditional_statements.txt +++ b/ingestion/docs/11_Conditional_statements.txt @@ -4,9 +4,9 @@ The IF-THEN-ELSE statement in AVAP™ allows for decision-making based on specif 6.1 Syntax of the IF-THEN-ELSE Statement The basic syntax of the IF-THEN-ELSE statement in AVAP™ is as follows: -IF(condition, true_value, operator) - // Block of code if the condition is true ELSE - // Block of code if the condition is false END() +if(condition, true_value, operator) + // Block of code if the condition is true else() + // Block of code if the condition is false end() condition: This is an expression that evaluates to either true or false. true_value: This is the value assigned if the condition is true. operator: This is the operator used to compare the condition with the true value. @@ -17,9 +17,11 @@ Below is the description of each part of the IF-THEN-ELSE statement using the pr // IF, ELSE and END Sample Use addVar(selector,'yes') - IF(selector,'yes','=') - addVar(result,1) ELSE() - addVar(result,0) END() + if(selector,'yes','=') + addVar(result,1) + else() + addVar(result,0) + end() addResult(result) The variable selector is initialized with the value 'yes'. The statement IF(selector,'yes','=') evaluates whether the value of selector is equal to 'yes'. In this case, the condition is true. @@ -36,4 +38,4 @@ The result returned by the API after executing the above code is as follows: This result indicates that the execution was successful (status:true) and that the value of result is 1. 6.4 Conclusions -The IF-THEN-ELSE statement in AVAP™ provides an efficient way to make decisions based on specific conditions. Similar to other programming languages, it allows for executing different blocks of code based on the outcome of evaluating a condition. +The IF-THEN-ELSE statement in AVAP™ provides an efficient way to make decisions based on specific conditions. Similar to other programming languages, it allows for executing different blocks of code based on the outcome of evaluating a condition. \ No newline at end of file diff --git a/ingestion/docs/12_Loop_statement.txt b/ingestion/docs/12_Loop_statement.txt index 0fcd8e9..c9bb5e2 100644 --- a/ingestion/docs/12_Loop_statement.txt +++ b/ingestion/docs/12_Loop_statement.txt @@ -39,4 +39,4 @@ After executing the above code, the result returned by the API is as follows: } This result confirms that the execution was successful (status:true) and that the final value of counter is 5. -In summary, the loop statement in AVAP™ provides an efficient way to execute a block of code repeatedly within a specified range. By automating tasks that require repetition, such as processing a list of items or generating sequential numbers, this statement becomes a fundamental tool for programming in AVAP™. +In summary, the loop statement in AVAP™ provides an efficient way to execute a block of code repeatedly within a specified range. By automating tasks that require repetition, such as processing a list of items or generating sequential numbers, this statement becomes a fundamental tool for programming in AVAP™. \ No newline at end of file diff --git a/ingestion/docs/13_Api_inbound_interface.txt b/ingestion/docs/13_Api_inbound_interface.txt index aa78de0..814538f 100644 --- a/ingestion/docs/13_Api_inbound_interface.txt +++ b/ingestion/docs/13_Api_inbound_interface.txt @@ -12,9 +12,9 @@ Example Usage Below is a practical example illustrating how to use the addParam() function in an API call: # API call with addParam() -addParam(user, "john_doe") -addParam(password, "password123") -In this example, two parameters, user and password, are being added to an API call. The value of user is set to "john_doe" and the value of password is set to "password123". +addParam(user, user_var) +addParam(password, password_var) +In this example, two parameters, user and password, are being added to an API call. The value of user is set to user_var and the value of password is set to password_var. Internal Operation Internally, the addParam() function constructs the querystring for the API call by adding the specified parameters along with their corresponding values. This querystring is passed to the API, which uses it to process the request and return the appropriate response. @@ -23,4 +23,4 @@ Important Considerations It is important to ensure that the parameters added with addParam() are valid and correctly formatted according to the requirements of the API being called. Additionally, it is the developer's responsibility to ensure that the values assigned to the parameters are secure and do not contain malicious data that could compromise system security. Conclusions -The addParam() function in AVAP™ is an essential tool for constructing and managing API calls, facilitating communication between the client and the server. By understanding how this function works and how it is used in the context of an API call, developers can create more robust and secure applications that make the most of web services' potential. +The addParam() function in AVAP™ is an essential tool for constructing and managing API calls, facilitating communication between the client and the server. By understanding how this function works and how it is used in the context of an API call, developers can create more robust and secure applications that make the most of web services' potential. \ No newline at end of file diff --git a/ingestion/docs/14_Working_with_libraries.txt b/ingestion/docs/14_Working_with_libraries.txt index 54565b2..33281c6 100644 --- a/ingestion/docs/14_Working_with_libraries.txt +++ b/ingestion/docs/14_Working_with_libraries.txt @@ -39,4 +39,4 @@ With this understanding of the value and advantages of using includes in AVAP™ Function Libraries Function Products In AVAP™, there are a series of function libraries grouped by categories called Function Products that complement the base AVAP™ language and leverage the power of AVS servers for distribution. Through Function Products, developers can extend the functionality of AVAP™ by incorporating specialized libraries tailored to different needs and applications. -Function Products provide a way to access advanced features and capabilities not available in the core language, offering a robust framework for building complex and scalable solutions. These libraries are designed to integrate seamlessly with AVAP™, enhancing the development process and enabling more efficient and effective project execution. +Function Products provide a way to access advanced features and capabilities not available in the core language, offering a robust framework for building complex and scalable solutions. These libraries are designed to integrate seamlessly with AVAP™, enhancing the development process and enabling more efficient and effective project execution. \ No newline at end of file diff --git a/ingestion/docs/15_Function_declaration.txt b/ingestion/docs/15_Function_declaration.txt index a788aa5..3579c4b 100644 --- a/ingestion/docs/15_Function_declaration.txt +++ b/ingestion/docs/15_Function_declaration.txt @@ -3,14 +3,16 @@ Introduction Functions in AVAP™ are reusable blocks of code that perform a specific task. Just like in Python, functions in AVAP™ allow for code modularization, improved readability, easier maintenance, and code reuse. Function Construction -In AVAP™, similar to Python, functions are defined using the keyword def, followed by the function name and its parameters in parentheses. The function definition ends with a colon (:), followed by the block of code that forms the function body, indented with four spaces. +In AVAP™, similar to Python, functions are defined using the keyword function , followed by the function name and its parameters in parentheses. The function definition ends with a {, followed by the block of code that forms the function body, and closed by }. Defining a function in AVAP™ -def greet(name): - return "Hello, " + name + "!" +function greet(name){ + return("Hello, " + name + "!") + } + Calling the function message = greet("World") - print(message) + addResult(message) Output Hello, World! Technical Features @@ -22,13 +24,16 @@ Practical Example Below is a practical example illustrating the definition and invocation of a function in AVAP™: Definition of a Function to Calculate the Area of a Circle -def calculate_circle_area(radius): - return 3.14 * radius ** 2 +function calculate_circle_area(radius){ + return(3.14 * radius ** 2) + } Calling the Function circle_radius = 5 -area = calculate_circle_area(circle_radius) -print("The area of the circle is:", area) + area = calculate_circle_area(circle_radius) + result = "The area of the circle is: %s" % area + addResult(result) + Output: The area of the circle is: 78.5 Conclusions -Functions are a fundamental part of programming in AVAP™, allowing for effective organization and modularization of code. By understanding how to define, construct, and call functions in AVAP™, developers can write clearer, more concise, and maintainable code, facilitating the development and management of applications. +Functions are a fundamental part of programming in AVAP™, allowing for effective organization and modularization of code. By understanding how to define, construct, and call functions in AVAP™, developers can write clearer, more concise, and maintainable code, facilitating the development and management of applications. \ No newline at end of file diff --git a/ingestion/docs/16_Appendix.txt b/ingestion/docs/16_Function_glossary.txt similarity index 99% rename from ingestion/docs/16_Appendix.txt rename to ingestion/docs/16_Function_glossary.txt index e7b1b57..763a790 100644 --- a/ingestion/docs/16_Appendix.txt +++ b/ingestion/docs/16_Function_glossary.txt @@ -1,4 +1,3 @@ -Appendix 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. @@ -718,4 +717,4 @@ 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. +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. \ No newline at end of file diff --git a/ingestion/docs/1_Introduction.txt b/ingestion/docs/1_Introduction.txt index 42bd52a..ced3d03 100644 --- a/ingestion/docs/1_Introduction.txt +++ b/ingestion/docs/1_Introduction.txt @@ -45,4 +45,4 @@ The language also includes the capability to interact with databases using natur With this guide, we hope to provide you with all the necessary information to make the most of this dynamic language's capabilities. From variable management to automated result generation and simplified database access, this language is designed to transform the way you develop APIs. 1.5 Conclusions -The virtuality attribute in AVAP™ represents an innovative approach to virtual API development, allowing for greater flexibility, agility, and simplification in the software development and maintenance process. By decoupling language specifications from the interpreter and enabling dynamic code construction in real-time, AVAP™ offers a new paradigm in API design and management. +The virtuality attribute in AVAP™ represents an innovative approach to virtual API development, allowing for greater flexibility, agility, and simplification in the software development and maintenance process. By decoupling language specifications from the interpreter and enabling dynamic code construction in real-time, AVAP™ offers a new paradigm in API design and management. \ No newline at end of file diff --git a/ingestion/docs/2_Dynamic_Programming_Language.txt b/ingestion/docs/2_Dynamic_Programming_Language.txt index da501f5..0dcbd53 100644 --- a/ingestion/docs/2_Dynamic_Programming_Language.txt +++ b/ingestion/docs/2_Dynamic_Programming_Language.txt @@ -30,10 +30,12 @@ AVAP™ offers a wide range of features that promote flexibility in programming. # Example of a higher-order function -def operation(func, a, b): - return func(a, b) -def add(x, y): - return x + y +function operation(func, a, b){ + return(func(a, b)) + } +function add(x, y){ + return(x + y) + } result = operation(add, 3, 5) # The add function is passed as an argument @@ -45,4 +47,4 @@ Faster writing and execution of code. Facilitates experimentation and exploration of solutions. Allows for rapid feedback during development. 1.3 Summary -AVAP™ is a dynamic programming language that offers a wide range of features promoting flexibility, adaptability, and speed in application development. With its dynamic typing, automatic memory management, runtime interpreter, and programming flexibility, AVAP™ becomes a powerful and versatile tool for developers. +AVAP™ is a dynamic programming language that offers a wide range of features promoting flexibility, adaptability, and speed in application development. With its dynamic typing, automatic memory management, runtime interpreter, and programming flexibility, AVAP™ becomes a powerful and versatile tool for developers. \ No newline at end of file diff --git a/ingestion/docs/3_Notation.txt b/ingestion/docs/3_Notation.txt index 68b4c38..a7fea3b 100644 --- a/ingestion/docs/3_Notation.txt +++ b/ingestion/docs/3_Notation.txt @@ -63,10 +63,11 @@ Practical Example example_variable = 10 // Definition of a function -example_function(parameter): +function example_function(parameter){ // Function body result = parameter * 2 - return result + return(result) + } // Function call result = example_function(example_variable) @@ -75,4 +76,4 @@ In this example, notation conventions are used to define a variable, a function, Conclusions Notation in AVAP™ is a fundamental part of software development in the language. By following clear and consistent notation conventions, developers can write and maintain code more effectively, contributing to the readability, understanding, and maintainability of the code in projects of any size and complexity. -With this understanding of notation in AVAP™, developers can write clean and structured code that is easy to understand and maintain over time. +With this understanding of notation in AVAP™, developers can write clean and structured code that is easy to understand and maintain over time. \ No newline at end of file diff --git a/ingestion/docs/4_Lexics.txt b/ingestion/docs/4_Lexics.txt index a63407e..f1eaed3 100644 --- a/ingestion/docs/4_Lexics.txt +++ b/ingestion/docs/4_Lexics.txt @@ -54,9 +54,10 @@ Below is a practical example that illustrates lexical analysis in AVAP™: // Function definition -function_example(parameter): +function function_example(parameter){ result = parameter * 2 - return result + return(result) + } // Function call value = function_example(10) @@ -71,4 +72,4 @@ parameter, result, value: Variable identifiers. Conclusions Lexical analysis is a crucial step in the compilation or interpretation of a program in AVAP™. By breaking down the source code into tokens, it lays the foundation for subsequent syntactic and semantic analysis, allowing the program to be correctly understood and executed by the interpreter or compiler. -With a clear understanding of lexical analysis in AVAP™, developers can write clean and structured code, facilitating the software development process in the language. +With a clear understanding of lexical analysis in AVAP™, developers can write clean and structured code, facilitating the software development process in the language. \ No newline at end of file diff --git a/ingestion/docs/5_Data_Model.txt b/ingestion/docs/5_Data_Model.txt index 2ec0ede..bf05907 100644 --- a/ingestion/docs/5_Data_Model.txt +++ b/ingestion/docs/5_Data_Model.txt @@ -34,15 +34,15 @@ Below is a practical example that illustrates the use of the data model in AVAP example_list = [1, 2, 3, 4, 5] # Accessing individual elements -print(example_list[0]) # Output: 1 +addResult(example_list[0]) # Output: 1 # Slicing to get a sublist sublist = example_list[2:4] -print(sublist) # Output: [3, 4] +addResult(sublist) # Output: [3, 4] # List methods example_list.append(6) -print(example_list) # Output: [1, 2, 3, 4, 5, 6] +addResult(example_list) # Output: [1, 2, 3, 4, 5, 6] Conclusions -The data model in AVAP™ provides a flexible and dynamic structure for working with data in the language. By understanding the available data types, data structures, operations, and methods, developers can write efficient and effective code that manipulates and processes data effectively. +The data model in AVAP™ provides a flexible and dynamic structure for working with data in the language. By understanding the available data types, data structures, operations, and methods, developers can write efficient and effective code that manipulates and processes data effectively. \ No newline at end of file diff --git a/ingestion/docs/6_Data_Types.txt b/ingestion/docs/6_Data_Types.txt index d5ecc40..85f281f 100644 --- a/ingestion/docs/6_Data_Types.txt +++ b/ingestion/docs/6_Data_Types.txt @@ -59,4 +59,4 @@ text1 = "Hello" text2 = "world" concatenation = text1 + " " + text2 1.4 Summary -Data types in AVAP™ are fundamental for program development. They allow for the storage and manipulation of different types of values, such as numbers, text, and truth values. With a solid understanding of data types and how they are used in program development, developers can create robust and functional applications in AVAP™. +Data types in AVAP™ are fundamental for program development. They allow for the storage and manipulation of different types of values, such as numbers, text, and truth values. With a solid understanding of data types and how they are used in program development, developers can create robust and functional applications in AVAP™. \ No newline at end of file diff --git a/ingestion/docs/7_Working_With_Variables.txt b/ingestion/docs/7_Working_With_Variables.txt index e78de77..876e0c3 100644 --- a/ingestion/docs/7_Working_With_Variables.txt +++ b/ingestion/docs/7_Working_With_Variables.txt @@ -35,10 +35,10 @@ value is the initial value to be assigned to the variable. 2.3.3 Direct Initialization It is also possible to declare and initialize a global variable at the same time using the following syntax: -global variable_name=value +addVar(variable_name,value) Where: variable_name is the name of the variable to be declared. value is the initial value to be assigned to the variable, which automatically defines the variable's type. 2.4 Summary -Working with variables in AVAP™ is essential for developing efficient and scalable applications. Variables allow for storing and manipulating data during program execution, which facilitates calculations and communication between different parts of the program. With a solid understanding of variable types and the different ways to declare them in AVAP™, developers can create robust and functional applications. +Working with variables in AVAP™ is essential for developing efficient and scalable applications. Variables allow for storing and manipulating data during program execution, which facilitates calculations and communication between different parts of the program. With a solid understanding of variable types and the different ways to declare them in AVAP™, developers can create robust and functional applications. \ No newline at end of file diff --git a/ingestion/docs/8_How_to_work_with_comments.txt b/ingestion/docs/8_How_to_work_with_comments.txt index 86702de..0659352 100644 --- a/ingestion/docs/8_How_to_work_with_comments.txt +++ b/ingestion/docs/8_How_to_work_with_comments.txt @@ -37,4 +37,4 @@ Keep comments updated as the code evolves. Write clear and concise comments that are easy for other developers to understand. Avoid redundant or unnecessary comments that do not provide useful information to the reader. 3.5 Summary -Comments in AVAP™ are an essential tool for improving the readability and maintainability of source code. With line comments, block comments, and documentation comments, developers can add explanations, clarifications, and useful documentation to the code, making it easier to understand and collaborate within development teams. +Comments in AVAP™ are an essential tool for improving the readability and maintainability of source code. With line comments, block comments, and documentation comments, developers can add explanations, clarifications, and useful documentation to the code, making it easier to understand and collaborate within development teams. \ No newline at end of file diff --git a/ingestion/docs/9_Expressions_in_avap.txt b/ingestion/docs/9_Expressions_in_avap.txt index 6832836..d785782 100644 --- a/ingestion/docs/9_Expressions_in_avap.txt +++ b/ingestion/docs/9_Expressions_in_avap.txt @@ -50,4 +50,4 @@ total = sum(numbers) // Output: 15 // Checking if a number is present in the list is_present = 6 in numbers // Output: False Conclusions -Expressions in AVAP™ are a fundamental part of programming, allowing for a wide variety of data operations and manipulations. By understanding the different types of expressions and operators, as well as working with data structures such as lists, developers can write clear and effective code that meets the program's requirements. +Expressions in AVAP™ are a fundamental part of programming, allowing for a wide variety of data operations and manipulations. By understanding the different types of expressions and operators, as well as working with data structures such as lists, developers can write clear and effective code that meets the program's requirements. \ No newline at end of file diff --git a/scratches/acano/es_ingestion.ipynb b/scratches/acano/es_ingestion.ipynb index 469d888..89fb1f4 100644 --- a/scratches/acano/es_ingestion.ipynb +++ b/scratches/acano/es_ingestion.ipynb @@ -33,10 +33,7 @@ "OLLAMA_URL = os.getenv(\"OLLAMA_URL\")\n", "OLLAMA_LOCAL_URL = os.getenv(\"OLLAMA_LOCAL_URL\")\n", "OLLAMA_MODEL_NAME = os.getenv(\"OLLAMA_MODEL_NAME\")\n", - "OLLAMA_EMB_MODEL_NAME = os.getenv(\"OLLAMA_EMB_MODEL_NAME\")\n", - "\n", - "config = AutoConfig.from_pretrained(HF_EMB_MODEL_NAME)\n", - "embedding_dim = config.hidden_size" + "OLLAMA_EMB_MODEL_NAME = os.getenv(\"OLLAMA_EMB_MODEL_NAME\")" ] }, { @@ -222,7 +219,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": null, "id": "8e214f79", "metadata": {}, "outputs": [], @@ -263,7 +260,7 @@ "\n", "\n", "chunks = build_chunks_from_folder(\n", - " folder_path=\"/home/acano/PycharmProjects/assistance-engine/data/raw/docs\"\n", + " folder_path=\"/home/acano/PycharmProjects/assistance-engine/ingestion/docs\"\n", ")" ] }, diff --git a/scratches/acano/langgraph_agent_simple.ipynb b/scratches/acano/langgraph_agent_simple.ipynb index dbd1efb..29cfecd 100644 --- a/scratches/acano/langgraph_agent_simple.ipynb +++ b/scratches/acano/langgraph_agent_simple.ipynb @@ -10,7 +10,7 @@ }, { "cell_type": "code", - "execution_count": 1, + "execution_count": 19, "id": "9e974df6", "metadata": {}, "outputs": [], @@ -28,18 +28,17 @@ " 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.messages import BaseMessage, SystemMessage, AIMessage, ToolMessage\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.llm_factory import create_chat_model\n", - "from src.emb_factory import create_embedding_model\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", @@ -50,17 +49,17 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 2, "id": "30edcecc", "metadata": {}, "outputs": [], "source": [ - "langfuse = Langfuse()\n", + "# langfuse = Langfuse()\n", "\n", "llm = create_chat_model(\n", " provider=\"ollama\",\n", " model=OLLAMA_MODEL_NAME,\n", - " temperature=0,\n", + " temperature=0.5,\n", " validate_model_on_init=True,\n", ")\n", "embeddings = create_embedding_model(\n", @@ -82,38 +81,15 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "id": "ad98841b", "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "Failed to export span batch code: 404, reason:
\"Langfuse

Loading ...

\n" - ] - }, - { - "ename": "ValidationError", - "evalue": "1 validation error for ParsingModel[Projects]\n__root__ -> data -> 0 -> metadata\n field required (type=value_error.missing)", - "output_type": "error", - "traceback": [ - "\u001b[31m---------------------------------------------------------------------------\u001b[39m", - "\u001b[31mValidationError\u001b[39m Traceback (most recent call last)", - "\u001b[36mCell\u001b[39m\u001b[36m \u001b[39m\u001b[32mIn[3]\u001b[39m\u001b[32m, line 1\u001b[39m\n\u001b[32m----> \u001b[39m\u001b[32m1\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[43mlangfuse\u001b[49m\u001b[43m.\u001b[49m\u001b[43mauth_check\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m:\n\u001b[32m 2\u001b[39m \u001b[38;5;28mprint\u001b[39m(\u001b[33m\"\u001b[39m\u001b[33mLangfuse client is authenticated and ready!\u001b[39m\u001b[33m\"\u001b[39m)\n\u001b[32m 3\u001b[39m \u001b[38;5;28;01melse\u001b[39;00m:\n", - "\u001b[36mFile \u001b[39m\u001b[32m~/PycharmProjects/assistance-engine/.venv/lib/python3.11/site-packages/langfuse/_client/client.py:1702\u001b[39m, in \u001b[36mLangfuse.auth_check\u001b[39m\u001b[34m(self)\u001b[39m\n\u001b[32m 1693\u001b[39m \u001b[38;5;250m\u001b[39m\u001b[33;03m\"\"\"Check if the provided credentials (public and secret key) are valid.\u001b[39;00m\n\u001b[32m 1694\u001b[39m \n\u001b[32m 1695\u001b[39m \u001b[33;03mRaises:\u001b[39;00m\n\u001b[32m (...)\u001b[39m\u001b[32m 1699\u001b[39m \u001b[33;03m This method is blocking. It is discouraged to use it in production code.\u001b[39;00m\n\u001b[32m 1700\u001b[39m \u001b[33;03m\"\"\"\u001b[39;00m\n\u001b[32m 1701\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m-> \u001b[39m\u001b[32m1702\u001b[39m projects = \u001b[38;5;28;43mself\u001b[39;49m\u001b[43m.\u001b[49m\u001b[43mapi\u001b[49m\u001b[43m.\u001b[49m\u001b[43mprojects\u001b[49m\u001b[43m.\u001b[49m\u001b[43mget\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\n\u001b[32m 1703\u001b[39m langfuse_logger.debug(\n\u001b[32m 1704\u001b[39m \u001b[33mf\u001b[39m\u001b[33m\"\u001b[39m\u001b[33mAuth check successful, found \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28mlen\u001b[39m(projects.data)\u001b[38;5;132;01m}\u001b[39;00m\u001b[33m projects\u001b[39m\u001b[33m\"\u001b[39m\n\u001b[32m 1705\u001b[39m )\n\u001b[32m 1706\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[38;5;28mlen\u001b[39m(projects.data) == \u001b[32m0\u001b[39m:\n", - "\u001b[36mFile \u001b[39m\u001b[32m~/PycharmProjects/assistance-engine/.venv/lib/python3.11/site-packages/langfuse/api/resources/projects/client.py:65\u001b[39m, in \u001b[36mProjectsClient.get\u001b[39m\u001b[34m(self, request_options)\u001b[39m\n\u001b[32m 63\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 64\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m \u001b[32m200\u001b[39m <= _response.status_code < \u001b[32m300\u001b[39m:\n\u001b[32m---> \u001b[39m\u001b[32m65\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mpydantic_v1\u001b[49m\u001b[43m.\u001b[49m\u001b[43mparse_obj_as\u001b[49m\u001b[43m(\u001b[49m\u001b[43mProjects\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43m_response\u001b[49m\u001b[43m.\u001b[49m\u001b[43mjson\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[43m)\u001b[49m \u001b[38;5;66;03m# type: ignore\u001b[39;00m\n\u001b[32m 66\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m _response.status_code == \u001b[32m400\u001b[39m:\n\u001b[32m 67\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m Error(pydantic_v1.parse_obj_as(typing.Any, _response.json())) \u001b[38;5;66;03m# type: ignore\u001b[39;00m\n", - "\u001b[36mFile \u001b[39m\u001b[32m~/PycharmProjects/assistance-engine/.venv/lib/python3.11/site-packages/pydantic/v1/tools.py:38\u001b[39m, in \u001b[36mparse_obj_as\u001b[39m\u001b[34m(type_, obj, type_name)\u001b[39m\n\u001b[32m 36\u001b[39m \u001b[38;5;28;01mdef\u001b[39;00m\u001b[38;5;250m \u001b[39m\u001b[34mparse_obj_as\u001b[39m(type_: Type[T], obj: Any, *, type_name: Optional[NameFactory] = \u001b[38;5;28;01mNone\u001b[39;00m) -> T:\n\u001b[32m 37\u001b[39m model_type = _get_parsing_type(type_, type_name=type_name) \u001b[38;5;66;03m# type: ignore[arg-type]\u001b[39;00m\n\u001b[32m---> \u001b[39m\u001b[32m38\u001b[39m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mmodel_type\u001b[49m\u001b[43m(\u001b[49m\u001b[43m__root__\u001b[49m\u001b[43m=\u001b[49m\u001b[43mobj\u001b[49m\u001b[43m)\u001b[49m.__root__\n", - "\u001b[36mFile \u001b[39m\u001b[32m~/PycharmProjects/assistance-engine/.venv/lib/python3.11/site-packages/pydantic/v1/main.py:347\u001b[39m, in \u001b[36mBaseModel.__init__\u001b[39m\u001b[34m(__pydantic_self__, **data)\u001b[39m\n\u001b[32m 345\u001b[39m values, fields_set, validation_error = validate_model(__pydantic_self__.\u001b[34m__class__\u001b[39m, data)\n\u001b[32m 346\u001b[39m \u001b[38;5;28;01mif\u001b[39;00m validation_error:\n\u001b[32m--> \u001b[39m\u001b[32m347\u001b[39m \u001b[38;5;28;01mraise\u001b[39;00m validation_error\n\u001b[32m 348\u001b[39m \u001b[38;5;28;01mtry\u001b[39;00m:\n\u001b[32m 349\u001b[39m object_setattr(__pydantic_self__, \u001b[33m'\u001b[39m\u001b[33m__dict__\u001b[39m\u001b[33m'\u001b[39m, values)\n", - "\u001b[31mValidationError\u001b[39m: 1 validation error for ParsingModel[Projects]\n__root__ -> data -> 0 -> metadata\n field required (type=value_error.missing)" - ] - } - ], + "outputs": [], "source": [ - "if langfuse.auth_check():\n", - " print(\"Langfuse client is authenticated and ready!\")\n", - "else:\n", - " print(\"Authentication failed. Please check your credentials and host.\")" + "# if langfuse.auth_check():\n", + "# print(\"Langfuse client is authenticated and ready!\")\n", + "# else:\n", + "# print(\"Authentication failed. Please check your credentials and host.\")" ] }, { @@ -126,7 +102,7 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 4, "id": "5f8c88cf", "metadata": {}, "outputs": [], @@ -139,7 +115,7 @@ }, { "cell_type": "code", - "execution_count": 6, + "execution_count": 5, "id": "fd8ed542", "metadata": {}, "outputs": [], @@ -158,7 +134,7 @@ }, { "cell_type": "code", - "execution_count": 7, + "execution_count": 26, "id": "f0a21230", "metadata": {}, "outputs": [], @@ -168,7 +144,7 @@ }, { "cell_type": "code", - "execution_count": 8, + "execution_count": 7, "id": "f9359747", "metadata": {}, "outputs": [], @@ -207,7 +183,7 @@ }, { "cell_type": "code", - "execution_count": 9, + "execution_count": 8, "id": "66ae23f0", "metadata": {}, "outputs": [], @@ -239,19 +215,48 @@ ")\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", + " content=\"\"\"\n", + " You are an assistant that helps users with AVAP (Advanced Virtual API Programming).\n", + "\n", + " AVAP is a completely new programming language and you have NO built-in knowledge about it.\n", + "\n", + " Your job is not to quote or summarize the documentation.\n", + " Your job is to generate original AVAP code using the documentation only as a specification.\n", + "\n", + " Rules:\n", + "\n", + " 1. If the user request is related to AVAP:\n", + " - You must call `context_retrieve`.\n", + " - Use the retrieved documentation to infer valid AVAP syntax, functions, control flow, and data handling.\n", + " - Then generate a new answer that satisfies the user's request.\n", + "\n", + " 2. The retrieved context is internal reference material.\n", + " - Do not treat it as something the user wrote.\n", + " - Do not thank the user for it.\n", + " - Do not summarize it unless the user explicitly asks for a summary.\n", + "\n", + " 3. If the user asks for code:\n", + " - Produce original code, not a documentation summary.\n", + " - Prefer the simplest valid AVAP implementation supported by the retrieved docs.\n", + " - Return only code if the user asks for only code.\n", + "\n", + " 4. If the retrieved context does not directly contain the exact example:\n", + " - Synthesize the example from documented primitives and syntax.\n", + " - Only say the documentation is insufficient if the required syntax or behavior cannot be inferred with reasonable confidence.\n", + "\n", + " 5. Never invent undocumented AVAP-specific syntax or commands.\n", + " - You may combine documented constructs into a new solution.\n", + " - You may generalize from examples only when the syntax pattern is clearly supported by the retrieved docs.\n", + "\n", + " 6. If the question is not related to AVAP:\n", + " - Answer normally using general knowledge.\n", " \"\"\"\n", ")" ] }, { "cell_type": "code", - "execution_count": 10, + "execution_count": 9, "id": "36d0f54e", "metadata": {}, "outputs": [], @@ -289,12 +294,14 @@ }, { "cell_type": "code", - "execution_count": 11, + "execution_count": 22, "id": "f073edc9", "metadata": {}, "outputs": [], "source": [ - "def agent(state: AgentState) -> AgentState:\n", + "tools = [context_retrieve]\n", + "\n", + "def agent(state: AgenticAgentState) -> AgenticAgentState:\n", " llm_with_tools = llm.bind_tools(tools)\n", " return {\"messages\": [llm_with_tools.invoke([SystemMessage(content=AGENTIC_PROMPT.content)] + state[\"messages\"])]}" ] @@ -361,7 +368,6 @@ "metadata": {}, "outputs": [], "source": [ - "tools = [context_retrieve]\n", "tool_node = ToolNode(tools=tools)\n", "memory = InMemorySaver()\n", "\n", @@ -382,7 +388,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 23, "id": "2fec3fdb", "metadata": {}, "outputs": [ @@ -414,7 +420,7 @@ }, { "cell_type": "code", - "execution_count": 15, + "execution_count": 16, "id": "8569cf39", "metadata": {}, "outputs": [], @@ -438,17 +444,17 @@ }, { "cell_type": "code", - "execution_count": 20, + "execution_count": 34, "id": "a1a1f3cf", "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?\"\"\"" + "user_input = \"\"\"What types of includes does AVAP have?\"\"\"" ] }, { "cell_type": "code", - "execution_count": 21, + "execution_count": 35, "id": "53b89690", "metadata": {}, "outputs": [ @@ -458,68 +464,150 @@ "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?' → 'CREATE TABLE myDatabase.users (username VARCHAR, age INTEGER);'\n", - "================================\u001b[1m Human Message \u001b[0m=================================\n", + "What types of includes does AVAP have?\n" + ] + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "Tool Calls:\n", + " context_retrieve (9329cb4e-5cb8-43e6-b2f5-d9a6a932b8e7)\n", + " Call ID: 9329cb4e-5cb8-43e6-b2f5-d9a6a932b8e7\n", + " Args:\n", + " query: AVAP includes types\n", + "=================================\u001b[1m Tool Message \u001b[0m=================================\n", + "Name: context_retrieve\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] 3 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", + "[1] id=chunk-1 source=10.1_Expressions.txt\n", + "6. Expressions in AVAP This chapter explains the meaning of expression elements in AVAP. 6.1. Arithmetic Conversions When describing an arithmetic operator in AVAP and using the phrase \"numeric arguments are converted to a common type,\" it means that the operator's implementation for built-in types works as follows: If either of the arguments is a complex number, the other is converted to complex. Otherwise, if either of the arguments is a floating-point number, the other is converted to floating-point. Otherwise, both must be integers, and no conversion is needed. Additional rules may apply for certain operators. 6.2. Atoms Atoms are the most basic elements of expressions in AVAP. The simplest atoms are identifiers or literals. Forms enclosed in parentheses, brackets, or braces are also syntactically categorized as atoms. The syntax for atoms is: atom ::= identifier | literal | enclosure enclosure ::= parenth_form | list_display | dict_display | set_display | generator_expression 6.2.1. Identifiers (Names) An identifier that appears as an atom is a name. When the name is bound to an object, evaluating the atom yields that object. When a name is not bound, an attempt to evaluate it raises a NameError exception. Private Name Mangling When an identifier that occurs literally in a class definition begins with two or more underscores and does not end with two or more underscores, it is considered a private name of that class. Private names are transformed into a longer form before code is generated for them. The transformation inserts the class name, with the initial underscores removed and a single underscore inserted, in front of the name. 6.2.2. Literals AVAP supports string and bytes literals, as well as various numeric literals: literal ::= stringliteral | bytesliteral | integer | floatnumber | imagnumber Evaluating a literal produces an object of the given type (string, bytes, integer, floating-point number, complex number) with the given value. All literals correspond to immutable data types. 6.2.3. Parenthesized Forms A parenthesized form is an optional list of expressions enclosed in parentheses: parenth_form ::= \"(\" [starred_expression] \")\" A parenthesized expression produces whatever the expression list produces: if the list contains at least one comma, it produces a tuple; otherwise, it produces the single expression that makes up the list of expressions. 6.2.4. Comprehensions for Lists, Sets and Dictionaries To construct a list, set, or dictionary, AVAP provides special syntax called \"comprehension,\" each in two flavors: The contents of the container are listed explicitly. They are computed using a set of loop and filtering instructions, called a \"comprehension.\" Common syntax elements for comprehensions are: comprehension ::= assignment_expression comp_for comp_for ::= \"for\" target_list \"in\" or_test [comp_iter] comp_iter ::= comp_for | comp_if comp_if ::= \"if\" or_test [comp_iter] A comprehension consists of a single expression followed by at least one for clause and zero or more for or if clauses. In this case, the elements of the new container are those produced by considering each for or if clause as a block, nested from left to right, and evaluating the expression to produce an element each time the innermost block is reached. 6.2.5. List Displays In AVAP, lists are generated and handled differently. To construct a list, the command variableToList(variable, list) is used, and an item from the list is retrieved with itemFromList(list, index, variable_to_store_item). To get the number of elements in the list, getListLen(list, var_to_store_list_length) is used. The syntax for list displays is: list_display ::= \"[\" [starred_list | comprehension] \"]\" A list display produces a new list object, whose content is specified by a list of expressions or a comprehension. When a list of expressions is provided, its elements are evaluated from left to right and placed in the list object in that order. 6.2.6. Set Displays A set display is denoted by curly braces and is distinguished from dictionary displays by the absence of colon characters separating keys and values: set_display ::= \"{\" (starred_list | comprehension) \"}\" A set display produces a new mutable set object, whose content is specified by a sequence of expressions or a comprehension. 6.2.7. Dictionary Displays In AVAP, objects are created and managed using specific commands. An object is created with AddvariableToJSON(key, value, object_variable), and a key from the object is retrieved with variableFromJSON(object_variable, key, var_to_store_key_value). The syntax for dictionary displays is: dict_display ::= \"{\" [dict_item_list | dict_comprehension] \"}\" dict_item_list ::= dict_item (\",\" dict_item)* [\",\"] dict_item ::= expression \":\" expression | \"**\" or_expr dict_comprehension ::= expression \":\" expression comp_for A dictionary display produces a new dictionary object. If a comma-separated sequence of dictionary items is provided, they are evaluated from left to right to define the dictionary entries. Slices A slice selects a range of elements in a sequence object (e.g., a string, tuple, or list). Slices can be used as expressions or as targets in assignments or statements. The syntax for a slice is as follows: slicing ::= primary \"[\" slice_list \"]\" slice_list ::= slice_item (\",\" slice_item)* [\",\"] slice_item ::= expression | proper_slice proper_slice ::= [lower_bound] \":\" [upper_bound] [ \":\" [stride] ] lower_bound ::= expression upper_bound ::= expression stride ::= expression There is ambiguity in the formal syntax here: anything that looks like a list expression also looks like a list slice, so any subscription might be interpreted as a slice. Instead of complicating the syntax further, this is disambiguated by defining that in this case, the interpretation as a subscription takes precedence over the interpretation as a slice (this is the case if the list slice does not contain a proper slice). The semantics for a slice are as follows. The primary is indexed (using the same __getitem__() method as in a normal subscription) with a key constructed from the slice list, as follows. If the slice list contains at least one comma, the key is a tuple that contains the conversion of the slice elements; otherwise, the conversion of the single slice element is the key. The conversion of a slice element that is an expression is that expression. The conversion of a proper slice is a slice object whose start, stop, and step attributes are the values of the expressions given as the lower bound, upper bound, and step, respectively, substituting None for missing expressions. Calls A call invokes a callable object (e.g., a function) with a possibly empty series of arguments: call ::= primary \"(\" [argument_list [\",\"] | comprehension] \")\" argument_list ::= positional_arguments [\",\" starred_and_keywords] [\",\" keywords_arguments] | starred_and_keywords [\",\" keywords_arguments] | keywords_arguments positional_arguments ::= positional_item (\",\" positional_item)* positional_item ::= assignment_expression | \"*\" expression starred_and_keywords ::= (\"*\" expression | keyword_item) (\",\" \"*\" expression | \",\" keyword_item)* keywords_arguments ::= (keyword_item | \"**\" expression) (\",\" keyword_item | \",\" \"**\" expression)* keyword_item ::= identifier \"=\" expression An optional trailing comma may be present after positional and keyword arguments but does not affect the semantics. The primary must evaluate to a callable object (user-defined functions, built-in functions, built-in object methods, class objects, class instance methods, and any object with a __call__() method are callable). All argument expressions are evaluated before attempting the call. Please refer to the Function Definitions section for the syntax of formal parameter lists. If keyword arguments are present, they are first converted into positional arguments as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Then, for each keyword argument, the identifier is used to determine the corresponding slot. If the slot is already filled, a TypeError exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is None, it fills the slot). When all arguments have been processed, any slots that are still empty are filled with the default value from the function definition. If there are unfilled slots for which no default value is specified, a TypeError exception is raised. Otherwise, the list of filled slots is used as the argument list for the call. Implementation Details in AVAP In AVAP, variables are stored as strings, and lists and objects are managed using specific commands: Lists: To generate a list, use variableToList(variable, list). To retrieve an item from the list, use itemFromList(list, index, variable_to_store_item). To get the number of items in the list, use getListLen(list, var_to_store_list_length). Objects (dictionaries): An object is created with AddvariableToJSON(key, value, object_variable). To retrieve a key from the object, use variableFromJSON(object_variable, key, var_to_store_key_value). Usage Example Creation and management of lists: // Creating a list variableToList(\"item1\", \"myList\") variableToList(\"item2\", \"myList\") variableToList(\"item3\", \"myList\") // Retrieving an item from the list itemFromList(\"myList\", 1, \"myVariable\") // Getting the length of the list getListLen(\"myList\", \"listLength\") Creation and management of objects (dictionaries): // Creating an object AddvariableToJSON(\"key1\", \"value1\", \"myObject\") AddvariableToJSON(\"key2\", \"value2\", \"myObject\") // Retrieving a value by key from the object variableFromJSON(\"myObject\", \"key1\", \"myVariable\") In this way, lists and objects in AVAP can be manipulated using the specific functions provided for working with variables stored as strings.\n", "\n", - "[2] id=chunk-2 source=16_Appendix.txt\n", - "Appendix 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", + "[2] id=chunk-2 source=9_Expressions_in_avap.txt\n", + "Expressions in AVAP™ Introduction Expressions in AVAP™ are combinations of values, variables, operators, and function calls that can be evaluated to produce a result. Just like in Python, expressions in AVAP™ can be simple or complex, and they can contain a variety of elements that manipulate and process data. Types of Expressions In AVAP™, as in Python, there are several types of expressions that can be used to perform different operations and calculations. Some of the most common types of expressions include: Arithmetic: Perform mathematical operations such as addition, subtraction, multiplication, and division. Logical: Evaluate logical conditions and return boolean values, such as True or False. Comparative: Compare two values and return a result based on their relationship, such as equality, inequality, greater than, less than, etc. Assignment: Assign a value to a variable. Function Calls: Invoke functions and methods to perform specific tasks. Operators In AVAP™, as in Python, expressions can include a variety of operators that perform specific operations on data. Some of the most common operators include: Arithmetic: +, -, *, /, %, etc. Logical: and, or, not. Comparative: ==, !=, >, <, >=, <=, etc. Assignment: =, +=, -=, *=, /=, etc. Working with Lists Lists are a very versatile data structure in AVAP™ that allows you to store collections of elements of different types. Expressions in AVAP™ can involve operations and manipulations of lists, such as accessing individual elements, concatenation, searching, deletion, and more. // Definition of a list my_list = [1, 2, 3, 4, 5] // Accessing individual elements first_element = my_list[0] // Output: 1 // Concatenation of lists another_list = [6, 7, 8] combined_list = my_list + another_list // Output: [1, 2, 3, 4, 5, 6, 7, 8] // Length of a list length = len(my_list) // Output: 5 // Searching in a list is_present = 5 in my_list // Output: True // Removing elements my_list.remove(3) // Removes the element 3 from the list Practical Example Below is a practical example that illustrates the use of expressions in AVAP™ with lists: // Definition of a list of numbers numbers = [1, 2, 3, 4, 5] // Calculation of the sum of the elements total = sum(numbers) // Output: 15 // Checking if a number is present in the list is_present = 6 in numbers // Output: False Conclusions Expressions in AVAP™ are a fundamental part of programming, allowing for a wide variety of data operations and manipulations. By understanding the different types of expressions and operators, as well as working with data structures such as lists, developers can write clear and effective code that meets the program's requirements.\n", "\n", - "[3] id=chunk-3 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", - "================================\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", + "[3] id=chunk-3 source=14_Working_with_libraries.txt\n", + "Function Libraries Introduction Includes are a fundamental feature in AVAP™ that allow for the efficient organization and reuse of code in software development projects. Just like in other programming languages, includes in AVAP™ enable the incorporation of functionalities from other files or libraries into the current file. This capability provides a number of significant advantages that make the development and maintenance of projects more efficient and effective. Purpose of Includes The primary purpose of includes in AVAP™ is to promote modularity and code reuse. By dividing code into separate modules or files and then including them in main files as needed, developers can write and maintain code in a more organized and structured manner. This facilitates the management of large and complex projects, as well as collaboration between development teams. Advantages of Using Includes Code Reuse: Includes allow for the reuse of functions, variables, and other code definitions in multiple parts of a project, reducing code duplication and promoting consistency and coherence in development. Facilitates Maintainability: By dividing code into smaller, more specific modules, it is easier to identify, understand, and modify parts of the code without affecting other parts of the project. This eases software maintenance over time. Promotes Modularity: The ability to include files selectively as needed encourages code modularity, which simplifies understanding and managing complex projects by breaking them down into smaller, manageable components. Improves Readability and Organization: The use of includes helps organize code in a logical and structured manner, improving readability and facilitating navigation through different parts of the project. Syntax of Includes In AVAP™, the syntax for including a file is similar to that of other languages like C. The keyword include is used followed by the name of the file to be included. There are two main ways to include files in AVAP™: Local Include: Used to include project-specific files located in the same directory or in subdirectories relative to the current file. The file name is specified within quotes. Example: include \"file_name.avap\" System Include: Used to include standard or system library files located in predefined or configured paths on the system. The file or library name is specified between angle brackets (< and >). Example: include Operation When an include is found in an AVAP™ file, the interpreter searches for the specified file and incorporates it into the current file at compile time. This means that all the code contained in the included file will be available for use in the current file. Common Uses Including Standard Libraries: Standard libraries that provide common functions and utilities can be included to simplify application development. Including Definition Files: Files containing definitions of variables, constants, or data structures used in multiple parts of the project can be included. Including Specific Functionality Modules: Modules providing additional features for the project, such as file handling, text processing, or data manipulation, can be included. Practical Example Suppose we have a file named utils.avap that contains utility functions we want to use in our main project. We can include this file in our main project as follows: include \"utils.avap\" // We can now use the functions defined in utils.avap With this understanding of the value and advantages of using includes in AVAP™, we will explore in detail their operation and practical application in project development. Practical Example Suppose we have a file named utils.avap that contains utility functions we want to use in our main project. We can include this file in our main project as follows: include \"utils.avap\" // We can now use the functions defined in utils.avap With this understanding of the value and advantages of using includes in AVAP™, we will explore in detail their operation and practical application in project development. Function Libraries Function Products In AVAP™, there are a series of function libraries grouped by categories called Function Products that complement the base AVAP™ language and leverage the power of AVS servers for distribution. Through Function Products, developers can extend the functionality of AVAP™ by incorporating specialized libraries tailored to different needs and applications. Function Products provide a way to access advanced features and capabilities not available in the core language, offering a robust framework for building complex and scalable solutions. These libraries are designed to integrate seamlessly with AVAP™, enhancing the development process and enabling more efficient and effective project execution.\n", "==================================\u001b[1m Ai Message \u001b[0m==================================\n", "\n", - "To create a table called `users` in the `myDatabase` database with two columns: `username` of type `VARCHAR` and `age` of type `INTEGER`, you can use the following command in AVAP:\n", + "Based on the documentation, AVAP has **two main types of includes** for incorporating external code:\n", "\n", - "```\n", - "createTable users (username VARCHAR, age INTEGER)\n", + "## 1. Local Include\n", + "- Used to include project-specific files located in the same directory or subdirectories relative to the current file\n", + "- Syntax: `include \"file_name.avap\"` (file name within quotes)\n", + "\n", + "## 2. System Include\n", + "- Used to include standard or system library files located in predefined or configured paths on the system\n", + "- Syntax: `include ` (file/library name between angle brackets)\n", + "\n", + "## Function Libraries\n", + "Additionally, AVAP includes **Function Products**, which are categorized function libraries that complement the base AVAP language. These specialized libraries leverage AVS servers for distribution and provide access to advanced features not available in the core language.\n", + "\n", + "### Key Advantages of Includes:\n", + "- **Code Reuse**: Functions, variables, and code definitions can be reused across multiple parts of a project\n", + "- **Maintainability**: Smaller, modular files make it easier to identify, understand, and modify specific sections\n", + "- **Modularity**: Enables structured organization of complex projects\n", + "- **Readability**: Improves navigation through different parts of the project\n", + "\n", + "### Example Usage:\n", + "```avap\n", + "// Local include (same directory)\n", + "include \"utils.avap\"\n", + "\n", + "// System include (predefined path)\n", + "include \n", "```\n", "\n", - "However, to specify that the table is in a specific database, you would need to use the `IN` keyword followed by the database name. For example:\n", - "\n", - "```\n", - "createTable IN myDatabase users (username VARCHAR, age INTEGER)\n", - "```\n", - "\n", - "This command will create a new table called `users` in the `myDatabase` database with the specified columns.\n", - "\n", - "Note that if you want to specify additional options or constraints for the table, such as primary keys or indexes, you can do so using additional keywords and parameters. For example:\n", - "\n", - "```\n", - "createTable IN myDatabase users (username VARCHAR PRIMARY KEY, age INTEGER)\n", - "```\n", - "\n", - "This command would create a new table called `users` in the `myDatabase` database with a primary key constraint on the `username` column.\n", - "\n", - "Also, if you want to specify the data type of the columns using the full syntax, you can use:\n", - "\n", - "```\n", - "createTable IN myDatabase users (username VARCHAR(255) PRIMARY KEY, age INTEGER)\n", - "```\n", - "\n", - "This command would create a new table called `users` in the `myDatabase` database with a primary key constraint on the `username` column and an integer data type for the `age` column.\n" + "These include types allow you to efficiently organize and reuse code while maintaining a structured, maintainable development workflow.\n" ] } ], "source": [ - "a = stream_graph_updates(user_input, guided_graph)" + "a = stream_graph_updates(user_input, agentic_graph)" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "id": "d6b4da6a", "metadata": {}, - "outputs": [], - "source": [] + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Final result:\n", + "==================================\u001b[1m Ai Message \u001b[0m==================================\n", + "\n", + "Based on the AVAP documentation provided, here's a comprehensive overview of the supported operators and expression types:\n", + "\n", + "## 1. Arithmetic Operators\n", + "AVAP supports standard mathematical operations including:\n", + "- **Addition**: `+` (e.g., `tax = subtotal * 0.21`)\n", + "- **Subtraction**: `-`\n", + "- **Multiplication**: `*`\n", + "- **Division**: `/`\n", + "- **Modulo**: `%`\n", + "\n", + "## 2. Comparison Operators\n", + "Supports relational comparisons:\n", + "- **Equality**: `==`, `!=`\n", + "- **Greater/Smaller**: `>`, `<`\n", + "- **Range Checks**: `>=`, `<=`\n", + "\n", + "Example: `level = 5 is_admin = level >= 10`\n", + "\n", + "## 3. Assignment Operators\n", + "AVAP supports multiple assignment types:\n", + "- **Direct Assignment**: `name = \"John\"`\n", + "- **Arithmetic Assignment**: `total += tax`\n", + "- **Multiplicative Assignment**: `value *= 2`\n", + "- **Division Assignment**: `price /= 10`\n", + "\n", + "## 4. Logical Operators\n", + "Supports boolean expressions:\n", + "- **AND**: `is_valid = (age > 18 and has_permission == True)`\n", + "- **OR**: `allowed = age >= 16 or status == \"active\"`\n", + "- **NOT**: `not_in_use = !is_active`\n", + "\n", + "## 5. String Formatting Operator\n", + "AVAP supports Python-style string formatting:\n", + "- `%` operator (e.g., `\"Event registered by: %s\" % name`)\n", + "\n", + "## 6. Object Property Access\n", + "Deep property access using dot notation:\n", + "- `customer_email = user_list[0].profile.email`\n", + "\n", + "## 7. List Operations\n", + "AVAP supports list manipulation:\n", + "```python\n", + "variableToList(\"item1\", \"myList\")\n", + "itemFromList(\"myList\", 1, \"myVariable\")\n", + "getListLen(\"myList\", \"listLength\")\n", + "```\n", + "\n", + "## 8. Keyword Arguments\n", + "Supports keyword argument syntax with comma separation:\n", + "```python\n", + "def handler(*args, **kwargs):\n", + " pass\n", + "```\n", + "\n", + "## Key Features\n", + "- **Dynamic Typing**: Variables can change type at runtime (e.g., numeric to string)\n", + "- **Scope Management**: Request session variables persist across API calls\n", + "- **Reference Operator**: `$` prefix for variable dereferencing\n", + "- **Middleware Support**: Built-in middleware execution before handlers\n", + "\n", + "These operators work together to create flexible, dynamic scripts that combine declarative commands with runtime expression evaluation.\n" + ] + } + ], + "source": [ + "result = agentic_graph.invoke({\"messages\": [{\"role\": \"user\", \"content\": user_input}]})\n", + "print(\"Final result:\")\n", + "result[\"messages\"][-1].pretty_print()" + ] }, { "cell_type": "code",