<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Savandi kodithuwakku on Medium]]></title>
        <description><![CDATA[Stories by Savandi kodithuwakku on Medium]]></description>
        <link>https://medium.com/@savandikodithuwakku?source=rss-509dfa0f76a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*164EsJ0UxM7YOT0JxyYyTQ.png</url>
            <title>Stories by Savandi kodithuwakku on Medium</title>
            <link>https://medium.com/@savandikodithuwakku?source=rss-509dfa0f76a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:38:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@savandikodithuwakku/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[What I Learned Building an AI Chatbot for a Workflow Management System]]></title>
            <link>https://medium.com/@savandikodithuwakku/what-i-learned-building-an-ai-chatbot-for-a-workflow-management-system-969e20953221?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/969e20953221</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[rags]]></category>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Thu, 10 Sep 2026 07:43:00 GMT</pubDate>
            <atom:updated>2026-09-10T07:43:00.628Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NgORlfhZP9a2un1ROcN9wA.png" /></figure><p>When I started working on the chatbot for our <strong>DocFlow</strong> project, I thought the idea was fairly simple.</p><p>A user asks a question.</p><p>The AI understands it.</p><p>If the question is related to our database, the AI generates an SQL query, retrieves the required information, and explains the result in natural language.</p><p>Simple, right?</p><p>Well… not exactly. 😅</p><p>Once I started implementing it, I realized that connecting an LLM to a real business application is much more complicated than sending a prompt to Gemini and receiving SQL in return.</p><p>The chatbot had to understand different types of questions, retrieve real-time KPI data, generate and validate SQL, search descriptive knowledge, handle multiple LLM providers, enforce permissions, and provide useful responses even when one part of the pipeline failed.</p><p>This project taught me a lot about:</p><ul><li>LLMs</li><li>SQL generation</li><li>SQL validation</li><li>KPI analytics</li><li>Keyword-based routing</li><li>Retrieval-augmented generation</li><li>Embeddings</li><li>Cosine similarity</li><li>Permissions</li><li>Fallback systems</li><li>API limitations</li><li>Local LLMs</li><li>Prompt design</li><li>Software architecture</li></ul><p>Most importantly, I learned how an AI system should fit into a traditional application instead of trying to replace the entire application.</p><h3>First, what problem were we trying to solve?</h3><p>Our project, DocFlow, is a document and workflow management system.</p><p>The system deals with things such as:</p><ul><li>Purchase Requisitions (PRs)</li><li>Purchase Orders (POs)</li><li>Workflow processes</li><li>Task instances</li><li>SLA tracking</li><li>Vendors</li><li>Document statuses</li><li>KPIs and analytics</li></ul><p>The system already stores a large amount of useful information in the database.</p><p>However, users normally need to navigate through the UI, apply filters, search for documents, open dashboards, and inspect workflow details manually.</p><p>We wanted to provide another way.</p><p>Instead of asking users to navigate through multiple screens, we wanted them to ask questions such as:</p><blockquote><em>“How many documents are currently running?”</em></blockquote><p>or:</p><blockquote><em>“Show me the POs that exceeded their SLA.”</em></blockquote><p>or:</p><blockquote><em>“What is the current status of PR 2000000214?”</em></blockquote><p>or:</p><blockquote><em>“Who is responsible for the Manager Approval task in the PO Approval — Payment Request instance in the Purchase Order Approval workflow?”</em></blockquote><p>or:</p><blockquote><em>“What is a purchase order?”</em></blockquote><p>The chatbot should understand the question, choose the correct processing method, retrieve the appropriate information, and provide a useful answer.</p><p>So the overall idea became:</p><p><strong>Natural language → Appropriate retrieval method → Reliable data or knowledge → Natural-language response</strong></p><p>The important part is that not every question should be handled in the same way.</p><p>That was one of the biggest lessons from this project.</p><h3>My initial approach</h3><p>Initially, I thought about the chatbot as a simple two-step LLM pipeline.</p><p>The first LLM would understand the user’s question and generate SQL.</p><p>For example:</p><blockquote><em>“Show me all delayed purchase orders.”</em></blockquote><p>The LLM might generate something like:</p><pre>SELECT ...<br>FROM purchase_orders<br>WHERE ...</pre><p>Then our backend would execute the SQL query.</p><p>After receiving the result, we would send it to the LLM again.</p><p>The second LLM call would convert the database result into a natural-language response.</p><p>The flow looked like this:</p><pre>User Question<br>      ↓<br>LLM #1<br>      ↓<br>SQL Query<br>      ↓<br>Database<br>      ↓<br>SQL Result<br>      ↓<br>LLM #2<br>      ↓<br>Natural-Language Response</pre><p>At first, this looked reasonable.</p><p>And technically, it worked for some questions.</p><p>But then I started noticing something important:</p><p><strong>Working is not the same as being reliable.</strong></p><p>The first SQL-based approach also failed for questions that were not really structured database questions.</p><p>For example, a question such as:</p><blockquote><em>“What is a purchase order?”</em></blockquote><p>is not asking for a row, count, filter, or relationship from a transactional table.</p><p>It is asking for a description.</p><p>Trying to answer every question through SQL was not the right design.</p><p>That led me to a more complete architecture based on four processing methods.</p><h3>The four methods used by the chatbot</h3><p>The chatbot uses four main methods:</p><ol><li><strong>KPI router with keyword-based analytics</strong></li><li><strong>Structured database questions using SQL generation</strong></li><li><strong>Descriptive or document-related questions using embeddings and cosine similarity</strong></li><li><strong>General questions and fallback handling</strong></li></ol><p>The high-level flow is:</p><pre>User Question<br>      ↓<br>KPI Keyword Router<br>      │<br>      ├── KPI-related keyword found<br>      │       ↓<br>      │   Analytics Function<br>      │       ↓<br>      │   Real-Time KPI Data<br>      │       ↓<br>      │   LLM Response Formatting<br>      │<br>      └── No KPI keyword<br>              ↓<br>          SQL Generation<br>              │<br>              ├── SQL succeeds<br>              │       ↓<br>              │   Validate and execute SQL<br>              │       ↓<br>              │   LLM Response Formatting<br>              │<br>              └── SQL fails or returns nothing<br>                      ↓<br>                  Vector Search<br>                      │<br>                      ├── Similarity &gt; 0.6<br>                      │       ↓<br>                      │   Retrieve top knowledge records<br>                      │       ↓<br>                      │   LLM Response Formatting<br>                      │<br>                      └── Similarity ≤ 0.6<br>                              ↓<br>                          General fallback response</pre><p>This design separates different types of questions instead of forcing every question through one pipeline.</p><h3>Method 1: KPI questions and keyword-based analytics</h3><p>The first method is used for questions related to KPI-based dashboard data.</p><p>Examples include:</p><blockquote><em>“How many documents are currently running?”</em></blockquote><blockquote><em>“How many workflows breached their SLA?”</em></blockquote><blockquote><em>“How many purchase orders are pending?”</em></blockquote><blockquote><em>“How many tasks are overdue?”</em></blockquote><p>These questions are usually connected to known dashboard metrics.</p><p>They do not necessarily require the LLM to generate SQL dynamically.</p><p>Instead, the system checks whether the question contains known KPI-related keywords or phrases.</p><p>For example:</p><pre>&quot;How many running documents are there?&quot;</pre><p>might contain the keyword:</p><pre>running documents</pre><p>The router identifies this as a KPI question and calls the corresponding analytics function.</p><p>The flow is:</p><pre>User Question<br>      ↓<br>Keyword-Based KPI Router<br>      ↓<br>Analytics Function<br>      ↓<br>Real-Time Database Calculation<br>      ↓<br>KPI Result<br>      ↓<br>Specific LLM<br>      ↓<br>Natural-Language Response</pre><p>For example:</p><pre>User:<br>&quot;How many documents are currently running?&quot;</pre><pre>        ↓</pre><pre>KPI Router:<br>Keyword detected: &quot;running documents&quot;</pre><pre>        ↓</pre><pre>Analytics Function:<br>Calculate the current number of running documents</pre><pre>        ↓</pre><pre>Database:<br>Returns the real-time count</pre><pre>        ↓</pre><pre>LLM:<br>&quot;Currently, there are 42 running documents.&quot;</pre><p>The analytics function is responsible for calculating the actual value from the database.</p><p>The LLM is not responsible for inventing or calculating the number.</p><p>It only receives the trusted result and converts it into a natural-language response.</p><p>This distinction is important.</p><p>The database and analytics function provide the factual answer.</p><p>The LLM improves the presentation.</p><h3>Why use keyword-based routing for KPIs?</h3><p>KPI questions are often predictable.</p><p>The application already knows which metrics are available on the dashboard.</p><p>For example:</p><pre>running documents<br>pending purchase orders<br>SLA breaches<br>overdue tasks<br>completed workflows<br>average processing time</pre><p>Because these metrics are known in advance, a deterministic analytics function is often more reliable than asking an LLM to generate a new SQL query every time.</p><p>The advantages are:</p><ul><li>More predictable results</li><li>Better performance</li><li>Lower LLM usage</li><li>Easier testing</li><li>Consistent KPI definitions</li><li>Reduced risk of incorrect SQL</li><li>Real-time calculations from the database</li></ul><p>This method is especially useful when the question maps directly to an existing dashboard metric.</p><h3>The role of the LLM in the KPI method</h3><p>The LLM is still useful, but it is used after the calculation.</p><p>For example, the backend might produce:</p><pre>{<br>  &quot;metric&quot;: &quot;running_documents&quot;,<br>  &quot;value&quot;: 42<br>}</pre><p>The LLM can convert that into:</p><blockquote><em>“There are currently 42 running documents in the system.”</em></blockquote><p>This is a much safer use of the LLM than asking it to calculate the value itself.</p><p>The LLM is acting as a response formatter, not as the source of truth.</p><h3>Method 2: Structured database questions using SQL generation</h3><p>If the question is not recognized as a KPI question, the chatbot checks whether it is a structured database-related question.</p><p>Structured questions usually ask for:</p><ul><li>A specific record</li><li>A status</li><li>A person responsible for a task</li><li>A relationship between entities</li><li>A filtered list</li><li>A count that is not already represented by a KPI</li><li>Data from multiple related tables</li></ul><p>For example:</p><blockquote><em>“Who is responsible for the Manager Approval task in the PO Approval — Payment Request instance in the Purchase Order Approval workflow?”</em></blockquote><p>This is a structured question because the answer must be retrieved from actual workflow and task data.</p><p>The system needs to identify relationships between entities such as:</p><ul><li>Workflow</li><li>Workflow instance</li><li>Task instance</li><li>Purchase order</li><li>Payment request</li><li>Assigned user</li><li>Task status</li></ul><p>The flow is:</p><pre>User Question<br>      ↓<br>SQL Generation Prompt<br>      ↓<br>Gemini or Ollama LLM<br>      ↓<br>Generated SQL<br>      ↓<br>Extract SQL Statement<br>      ↓<br>Clean SQL<br>      ↓<br>Validate SQL<br>      ↓<br>Execute SQL<br>      ↓<br>Database Result<br>      ↓<br>LLM Response Formatting<br>      ↓<br>Natural-Language Answer</pre><p>For the example question, the generated SQL might conceptually retrieve:</p><pre>The user assigned to the Manager Approval task<br>for the specified workflow instance<br>within the Purchase Order Approval workflow</pre><p>The exact SQL depends on the database schema.</p><p>The important point is that the answer comes from the live relational database, not from the LLM’s memory.</p><h3>Gemini and Ollama as SQL-generation providers</h3><p>For SQL generation, we support two LLM provider options:</p><ul><li>Gemini</li><li>Ollama</li></ul><p>The application can use Gemini as a cloud-based provider or Ollama as a local LLM provider.</p><p>The architecture can be represented as:</p><pre>SQL Generation Service<br>          ↓<br>   Provider Selection<br>          │<br>    ┌─────┴─────┐<br>    ↓           ↓<br> Gemini       Ollama</pre><p>The rest of the application should not need to know the internal details of the selected provider.</p><p>For example:</p><pre>LLM_PROVIDER = GEMINI</pre><p>or:</p><pre>LLM_PROVIDER = OLLAMA</pre><p>Both providers receive the question and database schema context and return a possible SQL statement.</p><p>This provider abstraction makes it easier to switch between cloud and local models.</p><h3>The SQL generation prompt</h3><p>The SQL generation prompt is one of the most important parts of the structured-question method.</p><p>The prompt should not simply say:</p><blockquote><em>“Generate SQL for this question.”</em></blockquote><p>The LLM needs enough context to understand the database.</p><p>The prompt generally includes:</p><ul><li>The user’s question</li><li>Relevant database tables</li><li>Column names</li><li>Column descriptions</li><li>Relationships between tables</li><li>Allowed SQL operations</li><li>Rules about read-only access</li><li>Formatting requirements</li><li>Instructions to return only SQL</li><li>Instructions not to invent tables or columns</li></ul><p>A simplified prompt might look like this:</p><pre>You are an SQL generation assistant.</pre><pre>Generate a read-only SQL query for the following user question.</pre><pre>Database schema:<br>- workflow(id, name)<br>- workflow_instance(id, workflow_id, reference_number)<br>- task_instance(id, workflow_instance_id, task_name, assigned_user_id)<br>- user(id, name)</pre><pre>Question:<br>Who is responsible for the Manager Approval task in the PO Approval - Payment Request instance in the Purchase Order Approval workflow?</pre><pre>Rules:<br>- Use only the tables and columns provided.<br>- Generate a read-only SELECT query.<br>- Do not use INSERT, UPDATE, DELETE, DROP, ALTER, or TRUNCATE.<br>- Return only the SQL statement.</pre><p>The quality of the generated SQL depends heavily on the quality of this context.</p><p>If the schema is incomplete or ambiguous, the LLM may generate SQL that is syntactically valid but logically incorrect.</p><p>That is why:</p><p><strong>Valid SQL does not necessarily mean correct SQL.</strong></p><h3>Extracting the SQL statement from the LLM response</h3><p>LLMs do not always return SQL in exactly the format we expect.</p><p>The response might contain:</p><pre>```sql<br>SELECT ...<br>FROM ...</pre><pre>or:</pre><pre>```text<br>Here is the query:</pre><pre>SELECT ...<br>FROM ...</pre><p>or even additional explanations before and after the query.</p><p>Because of this, the backend needs an <strong>SQL extraction step</strong>.</p><p>The extraction process identifies the actual SQL statement from the LLM response.</p><p>Conceptually:</p><pre>Raw LLM Response<br>      ↓<br>Find SQL code block<br>      ↓<br>Remove Markdown fences<br>      ↓<br>Remove explanatory text<br>      ↓<br>Extract SELECT statement<br>      ↓<br>Return clean SQL</pre><p>For example:</p><pre>Raw response:<br>&quot;Here is the query:<br>```sql<br>SELECT u.name<br>FROM users u<br>...<br>```&quot;</pre><pre>Extracted result:</pre><pre>```sql<br>SELECT u.name<br>FROM users u<br>...</pre><p>This step is important because the database driver should receive SQL, not a natural-language explanation.</p><h3>Cleaning the generated SQL</h3><p>After extracting the SQL statement, the backend cleans it before validation and execution.</p><p>Cleaning may include:</p><ul><li>Removing Markdown code fences</li><li>Removing unnecessary prefixes</li><li>Removing trailing semicolons when required</li><li>Removing extra whitespace</li><li>Normalizing line breaks</li><li>Removing comments if necessary</li><li>Extracting only the SQL statement</li><li>Ensuring the statement is not empty</li></ul><p>For example:</p><pre>```SQL<br>SELECT *<br>FROM workflow;</pre><pre>might be cleaned to:</pre><pre>```sql<br>SELECT *<br>FROM workflow</pre><p>The cleaning step does not make the query safe by itself.</p><p>It only prepares the query for validation.</p><h3>Making SQL validation case-insensitive</h3><p>SQL keywords can appear in different cases:</p><pre>SELECT *<br>FROM workflow</pre><p>or:</p><pre>select *<br>from workflow</pre><p>or:</p><pre>SeLeCt *<br>FrOm workflow</pre><p>If validation checks only one exact case, it may miss dangerous statements.</p><p>For example, checking only for:</p><pre>&quot;DROP&quot;</pre><p>would not detect:</p><pre>&quot;drop&quot;</pre><p>Therefore, the SQL is normalized before validation, usually by converting it to a consistent case such as uppercase or lowercase.</p><p>Conceptually:</p><pre>Original SQL<br>      ↓<br>Convert to uppercase<br>      ↓<br>Validate normalized SQL</pre><p>For example:</p><pre>drop table users</pre><p>becomes:</p><pre>DROP TABLE USERS</pre><p>This makes keyword detection case-insensitive.</p><p>However, simple keyword matching is only a basic safeguard.</p><p>A stronger implementation should parse the SQL structure and inspect:</p><ul><li>Statement type</li><li>Tables</li><li>Columns</li><li>Joins</li><li>Functions</li><li>Subqueries</li><li>Accessed schemas</li><li>User permissions</li></ul><h3>Validating the generated SQL</h3><p>The generated SQL should never be executed immediately.</p><p>The validation flow is:</p><pre>Generated SQL<br>      ↓<br>Extract SQL<br>      ↓<br>Clean SQL<br>      ↓<br>Normalize case<br>      ↓<br>Check statement type<br>      ↓<br>Check forbidden operations<br>      ↓<br>Check allowed tables<br>      ↓<br>Check allowed columns<br>      ↓<br>Check permissions<br>      ↓<br>Execute only if valid</pre><p>At a minimum, the system should reject statements containing operations such as:</p><pre>INSERT<br>UPDATE<br>DELETE<br>DROP<br>ALTER<br>TRUNCATE<br>CREATE<br>GRANT<br>REVOKE</pre><p>The chatbot should normally allow only read-only queries such as:</p><pre>SELECT ...</pre><p>A stronger validation approach is to use an SQL parser.</p><p>Conceptually:</p><pre>Generated SQL<br>     ↓<br>SQL Parser<br>     ↓<br>Check statement type<br>     ↓<br>Check tables<br>     ↓<br>Check columns<br>     ↓<br>Check joins<br>     ↓<br>Check user permissions<br>     ↓<br>Execute</pre><p>This gives the backend more control over what the LLM is allowed to do.</p><h3>Executing SQL and generating the final response</h3><p>Once the SQL has been cleaned and validated, the backend executes it against the relational database.</p><p>For example:</p><pre>Validated SQL<br>      ↓<br>Database<br>      ↓<br>Query Result</pre><p>The result might look like:</p><pre>{<br>  &quot;assigned_user&quot;: &quot;John Smith&quot;,<br>  &quot;task&quot;: &quot;Manager Approval&quot;,<br>  &quot;workflow&quot;: &quot;Purchase Order Approval&quot;<br>}</pre><p>The result is then sent to an LLM to produce a natural-language response:</p><blockquote><em>“The Manager Approval task is assigned to John Smith.”</em></blockquote><p>Again, the LLM is not responsible for discovering the data.</p><p>The database provides the result.</p><p>The LLM explains it.</p><p>This separation makes the system more reliable.</p><h3>Method 3: Descriptive and document-related questions using embeddings</h3><p>The third method is used when the question is descriptive, conceptual, or related to document knowledge.</p><p>Examples include:</p><blockquote><em>“What is a purchase order?”</em></blockquote><blockquote><em>“What is the purpose of the approval workflow?”</em></blockquote><blockquote><em>“What does SLA mean in this system?”</em></blockquote><blockquote><em>“Explain the purchase order process.”</em></blockquote><p>These questions are not necessarily asking for a specific row from a transactional table.</p><p>They require knowledge from documentation, business rules, schema descriptions, or other stored content.</p><p>This is where embeddings and vector similarity become useful.</p><p>The flow is:</p><pre>User Question<br>      ↓<br>Generate Query Embedding<br>      ↓<br>Search Knowledge Embeddings<br>      ↓<br>Calculate Cosine Similarity<br>      ↓<br>Retrieve Relevant Records<br>      ↓<br>Select Top Results<br>      ↓<br>Send Context to LLM<br>      ↓<br>Natural-Language Response</pre><p>For example:</p><pre>User:<br>&quot;What is a purchase order?&quot;</pre><pre>        ↓</pre><pre>Gemini Embedding Model</pre><pre>        ↓</pre><pre>Query Vector</pre><pre>        ↓</pre><pre>Cosine Similarity Search</pre><pre>        ↓</pre><pre>Relevant knowledge records</pre><pre>        ↓</pre><pre>LLM</pre><pre>        ↓</pre><pre>&quot;A purchase order is a formal document issued by a buyer...&quot;</pre><h3>What are embeddings?</h3><p>An embedding is a numerical representation of text.</p><p>A sentence such as:</p><blockquote><em>“A purchase order is a formal request issued to a vendor.”</em></blockquote><p>is converted into a vector containing many numerical values.</p><p>Conceptually:</p><pre>Text<br>  ↓<br>Embedding Model<br>  ↓<br>[0.12, -0.44, 0.87, 0.03, ...]</pre><p>The vector captures semantic information about the text.</p><p>Similar meanings tend to produce vectors that point in similar directions.</p><p>For example:</p><pre>&quot;What is a purchase order?&quot;</pre><p>and:</p><pre>&quot;Explain the meaning of a PO.&quot;</pre><p>use different words, but their embeddings should be relatively close because they have similar meanings.</p><h3>Storing knowledge embeddings</h3><p>The generated embeddings are stored in our database in the chatbot knowledge embeddings table.</p><p>A record may contain information such as:</p><pre>Knowledge ID<br>Text content<br>Embedding vector<br>Document type<br>Source<br>Metadata</pre><p>Conceptually:</p><pre>chatbot_knowledge_embeddings<br>--------------------------------<br>id<br>content<br>embedding<br>source<br>metadata<br>created_at</pre><p>Because our current system database is relatively small, storing these embeddings in the relational database is acceptable for now.</p><p>The database can store both:</p><ul><li>The original knowledge text</li><li>The corresponding embedding vector</li></ul><p>Later, as the knowledge base grows, we may move the embeddings to a dedicated vector database such as:</p><ul><li>Pinecone</li><li>ChromaDB</li><li>Qdrant</li><li>Weaviate</li><li>Milvus</li></ul><p>The relational database can still remain the source of truth for transactional business data.</p><h3>Cosine similarity: the mathematical idea</h3><p>To find relevant knowledge, we compare the embedding of the user’s question with the embeddings stored in the knowledge base.</p><p>One common comparison method is <strong>cosine similarity</strong>.</p><p>Suppose we have two vectors:</p><pre>A = (a₁, a₂, ..., aₙ)<br>B = (b₁, b₂, ..., bₙ)</pre><p>The cosine similarity is:</p><pre>cosine_similarity(A, B) =<br>(A · B) / (||A|| × ||B||)</pre><p>The dot product is:</p><pre>A · B = a₁b₁ + a₂b₂ + ... + aₙbₙ</pre><p>The magnitude, or length, of vector A is:</p><pre>||A|| = √(a₁² + a₂² + ... + aₙ²)</pre><p>The magnitude of vector B is:</p><pre>||B|| = √(b₁² + b₂² + ... + bₙ²)</pre><p>Therefore, the complete formula is:</p><pre>cosine_similarity(A, B) =<br>(a₁b₁ + a₂b₂ + ... + aₙbₙ)<br>/<br>(<br>√(a₁² + a₂² + ... + aₙ²)<br>×<br>√(b₁² + b₂² + ... + bₙ²)<br>)</pre><p>In simpler terms:</p><ol><li>Calculate the dot product of the two vectors.</li><li>Calculate the length of each vector.</li><li>Multiply the two lengths.</li><li>Divide the dot product by that product.</li></ol><h3>What does the cosine similarity value mean?</h3><p>Cosine similarity measures the angle between two vectors.</p><p>For normalized vectors, the value is usually between:</p><pre>-1 and +1</pre><p>The interpretation is:</p><pre>+1</pre><p>The vectors point in almost exactly the same direction.</p><p>Their meanings are highly similar.</p><pre>0</pre><p>The vectors are approximately unrelated or orthogonal.</p><pre>-1</pre><p>The vectors point in opposite directions.</p><p>In many text-embedding systems, values are commonly positive because the embedding space represents semantic relationships in a way that often produces non-negative or mostly positive similarities.</p><p>The important idea is that cosine similarity focuses on direction rather than absolute vector length.</p><p>For example, two vectors can have different magnitudes but still point in a similar direction.</p><p>That means their semantic meanings may be similar even if the numerical values are not identical.</p><p>A simplified geometric view is:</p><pre>Same direction:<br>A ─────────────►<br>B ─────────────►</pre><pre>Cosine similarity ≈ 1</pre><p>Different directions:</p><pre>A ─────────────►</pre><pre>B       ▲<br>        │</pre><pre>Cosine similarity ≈ 0</pre><p>Opposite directions:</p><pre>A ─────────────►</pre><pre>◄───────────── B</pre><pre>Cosine similarity ≈ -1</pre><h3>The similarity threshold</h3><p>After calculating similarity between the query embedding and stored knowledge embeddings, the system checks whether the similarity is high enough.</p><p>In our implementation, the threshold is:</p><pre>similarity &gt; 0.6</pre><p>This means that a knowledge record is considered relevant only if its similarity score is greater than 0.6.</p><p>Conceptually:</p><pre>Similarity score<br>      ↓<br>Is score &gt; 0.6?<br>      │<br>      ├── Yes → Relevant knowledge<br>      │<br>      └── No → Not sufficiently relevant</pre><p>The threshold helps prevent the chatbot from using unrelated knowledge.</p><p>For example:</p><pre>0.91 → Very relevant<br>0.78 → Relevant<br>0.64 → Possibly relevant<br>0.42 → Weak match<br>0.10 → Not relevant</pre><p>The exact meaning of a score depends on the embedding model and the data, so the threshold should be tested and adjusted using real examples.</p><p>A threshold that is too low may retrieve unrelated content.</p><p>A threshold that is too high may reject useful information.</p><h3>Retrieving the top five knowledge records</h3><p>After calculating similarity, the system sorts the knowledge records by similarity score.</p><p>It then retrieves the top five relevant records.</p><p>The process is:</p><pre>Query Embedding<br>      ↓<br>Compare with all stored embeddings<br>      ↓<br>Calculate similarity scores<br>      ↓<br>Filter records where similarity &gt; 0.6<br>      ↓<br>Sort by similarity descending<br>      ↓<br>Retrieve top five records<br>      ↓<br>Send them to the LLM</pre><p>For example:</p><pre>Knowledge Record A → 0.91<br>Knowledge Record B → 0.84<br>Knowledge Record C → 0.77<br>Knowledge Record D → 0.71<br>Knowledge Record E → 0.65<br>Knowledge Record F → 0.42</pre><p>The system would retrieve records A through E and ignore record F because its score is below the threshold.</p><p>The top five records provide context to the LLM.</p><p>The LLM then uses that context to generate the final answer.</p><h3>Why RAG is better for descriptive questions</h3><p>Retrieval-augmented generation, or RAG, is useful when the answer depends on descriptive knowledge.</p><p>For example:</p><blockquote><em>“What is a purchase order?”</em></blockquote><p>The answer may be stored in documentation or a knowledge base rather than in a transactional table.</p><p>RAG works by retrieving relevant content first and then giving that content to the LLM.</p><p>The flow is:</p><pre>Question<br>   ↓<br>Retrieve relevant knowledge<br>   ↓<br>Add knowledge to the prompt<br>   ↓<br>LLM generates answer</pre><p>This is better than asking the LLM to answer only from its general training because the retrieved content can be specific to our application.</p><p>It can include:</p><ul><li>Internal definitions</li><li>Workflow descriptions</li><li>Business rules</li><li>SLA explanations</li><li>Column descriptions</li><li>Process documentation</li><li>System-specific terminology</li></ul><h3>Why I did not implement only RAG</h3><p>One of the important design decisions was not to use RAG for every question.</p><p>RAG is useful for descriptive and document-related questions, but it is not the best method for retrieving live structured business data.</p><p>For example:</p><blockquote><em>“How many documents are currently running?”</em></blockquote><p>or:</p><blockquote><em>“Who is responsible for the Manager Approval task in the PO Approval — Payment Request instance?”</em></blockquote><p>These questions require current data from relational tables.</p><p>A vector search result may retrieve a description of a workflow or task, but it cannot reliably provide the current assigned user or real-time count.</p><p>For structured questions, we need to query the actual database.</p><p>That is why the system uses:</p><pre>Structured question → SQL and relational database<br>Descriptive question → Embeddings, vector search, and RAG</pre><p>This distinction is important.</p><p>RAG retrieves semantically relevant text.</p><p>SQL retrieves exact, current, structured records.</p><p>They solve different problems.</p><h3>Method 4: General questions and fallback handling</h3><p>The fourth method handles questions that do not match the KPI, SQL, or vector-search methods.</p><p>Examples include:</p><blockquote><em>“Hello”</em></blockquote><blockquote><em>“Good morning.”</em></blockquote><blockquote><em>“How are you?”</em></blockquote><blockquote><em>“Thank you.”</em></blockquote><p>These questions do not require database access or knowledge retrieval.</p><p>The system should not generate SQL for them.</p><p>It should also not perform unnecessary vector searches.</p><p>The flow is:</p><pre>User Question<br>      ↓<br>KPI Router<br>      ↓<br>SQL Method<br>      ↓<br>Vector Search<br>      ↓<br>No suitable result<br>      ↓<br>General Response</pre><p>For example:</p><pre>User:<br>&quot;Good morning.&quot;</pre><pre>        ↓</pre><pre>No KPI keyword</pre><pre>        ↓</pre><pre>No valid SQL result</pre><pre>        ↓</pre><pre>No vector similarity above 0.6</pre><pre>        ↓</pre><pre>General response:<br>&quot;Good morning! How can I help you?&quot;</pre><p>This is also a fallback path.</p><p>If the question is not structured, no SQL is returned, SQL execution fails, or vector similarity is too low, the system should return a safe and understandable response instead of pretending to know the answer.</p><h3>The complete four-method flow</h3><p>The complete architecture can be represented as:</p><pre>USER QUESTION<br>                                     │<br>                                     ▼<br>                              KPI Keyword Router<br>                                     │<br>                    ┌────────────────┴────────────────┐<br>                    │                                 │<br>          KPI keyword detected                 No KPI keyword<br>                    │                                 │<br>                    ▼                                 ▼<br>          Analytics Function                  SQL Generation<br>                    │                                 │<br>                    ▼                                 ▼<br>          Real-Time KPI Result              Gemini or Ollama<br>                    │                                 │<br>                    ▼                                 ▼<br>          LLM Response Formatter             Extract SQL<br>                                                      │<br>                                                      ▼<br>                                                Clean SQL<br>                                                      │<br>                                                      ▼<br>                                              Validate SQL<br>                                                      │<br>                                      ┌───────────────┴───────────────┐<br>                                      │                               │<br>                                SQL succeeds                    SQL fails<br>                                      │                               │<br>                                      ▼                               ▼<br>                              Execute SQL                    Vector Search<br>                                      │                               │<br>                                      ▼                               ▼<br>                              Database Result              Cosine Similarity<br>                                      │                               │<br>                                      ▼                               ▼<br>                              LLM Formatter                 Similarity &gt; 0.6?<br>                                                                      │<br>                                                        ┌─────────────┴─────────────┐<br>                                                        │                           │<br>                                                       Yes                          No<br>                                                        │                           │<br>                                                        ▼                           ▼<br>                                                Retrieve top five             General fallback<br>                                                        │<br>                                                        ▼<br>                                                LLM Formatter<br>                                                        │<br>                                                        ▼<br>                                                     RESPONSE</pre><p>This flow makes the responsibilities clearer.</p><ul><li>KPI analytics handles known dashboard metrics.</li><li>SQL handles structured, live database questions.</li><li>Vector search handles descriptive and document-related questions.</li><li>General fallback handles greetings, unsupported questions, and low-confidence cases.</li></ul><h3>Problem 1: The chatbot sometimes simply failed</h3><p>One of the biggest problems I faced was reliability.</p><p>Even though we had a fallback mechanism where different Gemini models could be used when one model failed, the chatbot would still sometimes respond with:</p><blockquote><em>“Sorry, we can’t process your request at this time.”</em></blockquote><p>This made me realize something important:</p><p><strong>Adding more models does not automatically make an AI system reliable.</strong></p><p>For example:</p><pre>Gemini Model A<br>      ↓<br>     FAIL<br>      ↓<br>Gemini Model B<br>      ↓<br>     FAIL<br>      ↓<br>Gemini Model C<br>      ↓<br>     FAIL</pre><p>At first, I thought:</p><blockquote><em>“Maybe I just need more fallback models.”</em></blockquote><p>But after looking deeper, I realized that the failure might not even be related to the model.</p><p>It could be:</p><ul><li>API rate limits</li><li>Token limits</li><li>Timeouts</li><li>Invalid requests</li><li>Network problems</li><li>Malformed SQL</li><li>Database errors</li><li>Permission failures</li><li>Errors in the second LLM call</li><li>No SQL returned</li><li>SQL execution failure</li><li>No relevant vector result</li></ul><p>This is why the four-method design is useful.</p><p>A failure in one method does not necessarily mean the entire chatbot must fail.</p><p>For example:</p><pre>SQL generation fails<br>      ↓<br>Try vector search<br>      ↓<br>If similarity &gt; 0.6, answer from knowledge<br>      ↓<br>Otherwise return a safe fallback</pre><h3>What I learned about fallback systems</h3><p>A better fallback system distinguishes between different types of errors.</p><p>For example:</p><pre>LLM Request Failed<br>       ↓<br>What type of error?<br>       │<br>       ├── Rate limit → Try fallback model<br>       │<br>       ├── Temporary server error → Retry<br>       │<br>       ├── Timeout → Retry or switch provider<br>       │<br>       ├── Invalid request → Fix or reject<br>       │<br>       ├── SQL generation failure → Try vector method<br>       │<br>       ├── SQL execution failure → Log and use fallback<br>       │<br>       ├── Low similarity → General response<br>       │<br>       └── Authentication error → Stop and report</pre><p>This is much better than simply doing:</p><pre>Model A failed → Model B</pre><p>I also learned about concepts such as:</p><ul><li>Retry strategies</li><li>Timeouts</li><li>Circuit breakers</li><li>Provider fallback</li><li>Deterministic response formatting</li><li>Error classification</li></ul><p>A circuit breaker can temporarily stop sending requests to a provider that is continuously failing instead of repeatedly making requests that are guaranteed to fail.</p><p>That was a new way of thinking for me.</p><p>I started realizing that an LLM is not just an AI model.</p><p>From a software engineering perspective, it is also an <strong>external dependency that can fail</strong>.</p><h3>Problem 2: Why do we need multiple LLM calls?</h3><p>The chatbot may use an LLM at different stages depending on the method.</p><p>For KPI questions, the analytics function calculates the value first, and an LLM formats the result.</p><p>For SQL questions, one LLM generates SQL and another LLM call may format the database result.</p><p>For vector-search questions, the embedding model creates the query vector, and a response LLM uses the retrieved knowledge to generate the answer.</p><p>This means the system may contain several specialized LLM responsibilities:</p><pre>Question<br>   ↓<br>Router or classifier<br>   ↓<br>SQL generation, embedding generation, or analytics selection<br>   ↓<br>Database or knowledge retrieval<br>   ↓<br>Response formatting</pre><p>At first, I questioned whether the final response-formatting LLM was necessary.</p><p>What happens if the database query succeeds but the second LLM call fails?</p><p>We already have the actual data.</p><p>Why should the entire chatbot fail?</p><p>For example, suppose the database returns:</p><pre>PO Issue → SLA Breached<br>GRN → SLA Met<br>SRN → SLA Breached</pre><p>Even if the second LLM is unavailable, the backend can still format this information into a readable response.</p><p>This led me to another important idea:</p><h3>The LLM should not control the entire system.</h3><p>The backend should control the workflow and use the LLM only where it adds value.</p><p>If the final LLM fails, we can still provide a deterministic response such as:</p><pre>PO Issue: SLA Breached<br>GRN: SLA Met<br>SRN: SLA Breached</pre><p>That makes the system more reliable.</p><h3>Problem 3: Not every question needs SQL</h3><p>Another thing I learned was that we should not send every question to the SQL pipeline.</p><p>For example:</p><blockquote><em>“Hello”</em></blockquote><p>does not need SQL.</p><p>Neither does:</p><blockquote><em>“Good morning.”</em></blockquote><p>And:</p><blockquote><em>“What is a purchase order?”</em></blockquote><p>is usually better handled through descriptive knowledge retrieval than through a transactional SQL query.</p><p>This is why the router needs to distinguish between:</p><pre>KPI_QUERY<br>STRUCTURED_DATABASE_QUERY<br>DESCRIPTIVE_KNOWLEDGE_QUERY<br>GENERAL_QUERY<br>UNSUPPORTED_QUERY</pre><p>For example:</p><pre>&quot;How many running documents are there?&quot;<br>   ↓<br>KPI_QUERY<br>   ↓<br>Analytics function</pre><pre>&quot;Who is responsible for the Manager Approval task?&quot;<br>   ↓<br>STRUCTURED_DATABASE_QUERY<br>   ↓<br>SQL pipeline</pre><pre>&quot;What is a purchase order?&quot;<br>   ↓<br>DESCRIPTIVE_KNOWLEDGE_QUERY<br>   ↓<br>Embedding and vector search</pre><pre>&quot;Good morning.&quot;<br>   ↓<br>GENERAL_QUERY<br>   ↓<br>Conversational response</pre><p>This makes the architecture cleaner and avoids unnecessary SQL generation.</p><h3>One of the most important things I learned: LLMs should not decide permissions</h3><p>This became especially important because DocFlow is not just a chatbot.</p><p>It is a real business application with different types of users and permissions.</p><p>Our system requirements include authentication and authorization, with permissions determining what users can access and what actions they can perform.</p><p>Imagine a user asks:</p><blockquote><em>“Show me all vendor payment information.”</em></blockquote><p>The LLM might generate a perfectly valid SQL query.</p><p>But that does not mean the user is allowed to see that information.</p><p>This is where I learned an important distinction:</p><p><strong>Understanding a question and authorizing a request are two completely different responsibilities.</strong></p><p>The LLM can help understand the question.</p><p>But the backend should decide whether the user is allowed to access the requested data.</p><p>The architecture should be:</p><pre>User<br> ↓<br>Authentication<br> ↓<br>User Role<br> ↓<br>Intent Detection<br> ↓<br>Determine Required Data<br> ↓<br>Permission Check<br> ↓<br>Allowed?<br> ├── No → Access Denied<br> │<br> └── Yes<br>       ↓<br>   Select appropriate method<br>       ↓<br>   Generate SQL or retrieve knowledge<br>       ↓<br>   Validate and execute</pre><p>This makes the chatbot <strong>role-aware and permission-aware</strong>.</p><p>For example:</p><pre>Manager<br>   ↓<br>Can access:<br>Workflow data<br>Task data<br>SLA data</pre><pre>Vendor<br>   ↓<br>Can access:<br>Own document and payment status</pre><pre>Admin<br>   ↓<br>Can access:<br>Broader system information</pre><p>The exact permissions depend on the application, but the important point is that the LLM should never be trusted to enforce them.</p><h3>SQL generation is not the same as SQL execution</h3><p>Another lesson I learned was that generating SQL is only one part of the problem.</p><p>The generated query should go through several stages before reaching the database:</p><pre>Generate SQL<br>      ↓<br>Extract SQL statement<br>      ↓<br>Clean SQL<br>      ↓<br>Normalize case<br>      ↓<br>Validate SQL<br>      ↓<br>Check permissions<br>      ↓<br>Execute SQL</pre><p>Initially, it is tempting to check whether the generated query contains dangerous words such as:</p><pre>DELETE<br>DROP<br>UPDATE<br>INSERT<br>ALTER<br>TRUNCATE</pre><p>That is useful as a basic safeguard.</p><p>But string matching alone is not enough for a robust system.</p><p>A better approach is to inspect the structure of the SQL query.</p><p>Conceptually:</p><pre>Generated SQL<br>     ↓<br>SQL Parser<br>     ↓<br>Check statement type<br>     ↓<br>Check tables<br>     ↓<br>Check columns<br>     ↓<br>Check joins<br>     ↓<br>Check user permissions<br>     ↓<br>Execute</pre><p>This gives us much more control over what the AI is actually allowed to do.</p><h3>Another thing I learned: the database should remain the source of truth</h3><p>One thing I really wanted from this chatbot was the ability to ask questions about <strong>actual current system data</strong>.</p><p>For example:</p><blockquote><em>“How many workflows breached their SLA?”</em></blockquote><p>The answer should not come from what the LLM remembers.</p><p>It should come from the actual database.</p><p>Similarly:</p><blockquote><em>“Who is responsible for the Manager Approval task?”</em></blockquote><p>must be answered using the current task assignment stored in the database.</p><p>The LLM should be treated as an interface between the user and the database.</p><p>The database remains the source of truth.</p><p>The LLM helps translate:</p><pre>Human language<br>      ↓<br>Structured query</pre><p>and then:</p><pre>Database result<br>      ↓<br>Human language</pre><p>For descriptive questions, the knowledge base becomes the source of truth:</p><pre>Human language<br>      ↓<br>Semantic retrieval<br>      ↓<br>Stored documentation<br>      ↓<br>Human language</pre><p>This changed the way I thought about an AI chatbot.</p><p>It does not always have to be an AI that knows everything.</p><p>Sometimes, it is better to make the AI a <strong>natural-language interface to reliable application data and knowledge</strong>.</p><h3>API LLM vs Local LLM</h3><p>Another major area I explored was LLM provider switching.</p><p>For SQL generation, we support both Gemini and Ollama.</p><p>Gemini is an API-based cloud model.</p><p>Ollama allows us to run a local model.</p><p>That means the rest of the chatbot should not depend directly on Gemini.</p><p>Instead, the application should use an abstraction such as:</p><pre>LLM Service<br>     ↓<br>Provider Adapter<br>     ├── Gemini<br>     ├── Ollama<br>     └── Other Providers</pre><p>Then the application can use configuration such as:</p><pre>LLM_PROVIDER = GEMINI</pre><p>or:</p><pre>LLM_PROVIDER = OLLAMA</pre><p>The rest of the application does not need to know how the selected model works internally.</p><p>This taught me a very important software engineering concept:</p><p><strong>Do not tightly couple your business logic to a specific external provider.</strong></p><p>If Gemini changes, becomes expensive, reaches a limit, or we later decide to use a local model, we should not have to rewrite the entire chatbot.</p><h3>Why use a local LLM?</h3><p>A local LLM can be useful for several reasons:</p><ul><li>Less dependency on external APIs</li><li>Better control over sensitive data</li><li>Potentially lower API costs</li><li>Offline or private environments</li><li>More control over model selection</li><li>Reduced dependency on network availability</li></ul><p>But there are trade-offs too.</p><p>Local models require computational resources and may not perform as well as larger cloud models for some tasks.</p><p>So I do not see it as:</p><blockquote><em>API is bad and local is good</em></blockquote><p>Instead, I see them as <strong>different deployment options</strong>.</p><p>For our project, having the ability to switch between them through configuration gives us more flexibility.</p><h3>I also learned that prompt design matters a lot</h3><p>When working with natural-language-to-SQL, the prompt cannot simply say:</p><blockquote><em>“Generate SQL for this question.”</em></blockquote><p>The model needs context.</p><p>It needs to understand:</p><ul><li>What tables exist</li><li>What columns exist</li><li>Relationships between tables</li><li>What the columns represent</li><li>What type of SQL is allowed</li><li>What the user is asking</li><li>What the system considers a valid query</li><li>Which tables the current user is allowed to access</li></ul><p>For example, if the database contains:</p><pre>workflow<br>workflow_instance<br>task_instance<br>sla</pre><p>the model needs to understand how these entities relate to each other.</p><p>Otherwise, it might generate syntactically valid SQL that is logically wrong.</p><p>And this is an important lesson:</p><p><strong>Valid SQL does not necessarily mean correct SQL.</strong></p><p>The same principle applies to descriptive questions.</p><p>The embedding and knowledge-retrieval process also depends on the quality of the stored content.</p><p>If the knowledge base contains incomplete or poorly written descriptions, the final answer may also be incomplete.</p><h3>The problem with sending the entire schema</h3><p>Another thing I started thinking about was the size of the database schema.</p><p>If the database becomes larger, we do not necessarily want to send the entire schema to the LLM for every question.</p><p>Imagine having:</p><pre>100 tables<br>500 columns<br>Hundreds of relationships</pre><p>and sending all of that in every request.</p><p>That is inefficient.</p><p>It increases:</p><ul><li>Prompt size</li><li>Token usage</li><li>Latency</li><li>Cost</li><li>Possibility of the model getting confused</li></ul><p>So I started researching the idea of retrieving only the relevant schema information.</p><p>For example:</p><pre>User:<br>&quot;Which workflows breached SLA?&quot;</pre><pre>        ↓</pre><pre>Schema Retrieval</pre><pre>        ↓</pre><pre>Relevant tables:<br>workflow<br>workflow_instance<br>task_instance<br>sla</pre><pre>        ↓</pre><pre>LLM</pre><pre>        ↓</pre><pre>SQL</pre><p>This is where embeddings and vector retrieval can also help with SQL generation.</p><p>The system can store descriptions of tables and columns as knowledge records.</p><p>Then it can retrieve only the schema context relevant to the user’s question.</p><h3>Vector storage vs a normal database</h3><p>This is probably one of the most interesting things I learned while working on this.</p><p>At first, I thought:</p><blockquote><em>“Why would I need a vector database? We already have MySQL.</em></blockquote><p>For storing structured business data, a normal relational database is exactly what we need.</p><p>Our actual data contains things such as:</p><pre>PR number<br>PO number<br>status<br>dates<br>vendor<br>SLA<br>workflow<br>task<br>assigned user</pre><p>These are structured records.</p><p>A relational database is excellent for this.</p><p>But there is another type of information:</p><pre>Workflow documentation<br>Business rules<br>Column descriptions<br>Process descriptions<br>SLA definitions<br>System documentation<br>Previous explanations</pre><p>These are more semantic.</p><p>For example, the user might ask:</p><blockquote><em>“Which purchasing processes usually take longer than expected?”</em></blockquote><p>The system may need to understand concepts rather than simply match exact words.</p><p>This is where vector search becomes useful.</p><h3>What I would improve in the future</h3><p>From what I have learned, I would not replace the relational database with a vector database.</p><p>I would probably use both.</p><p>Something like:</p><pre>User<br>                  ↓<br>             AI Router<br>                  ↓<br>       ┌──────────┴──────────┐<br>       ↓                     ↓<br>Structured Data        Semantic Context<br>       ↓                     ↓<br>   SQL Database          Vector Store<br>       ↓                     ↓<br>       └──────────┬──────────┘<br>                  ↓<br>                 LLM<br>                  ↓<br>               Answer</pre><p>The relational database would remain the source of truth for actual business data.</p><p>The vector store could contain embeddings for:</p><ul><li>Database schema descriptions</li><li>Workflow documentation</li><li>Business rules</li><li>Process descriptions</li><li>SLA explanations</li><li>Other unstructured knowledge</li></ul><p>Then we could retrieve the relevant context before asking the LLM to generate SQL or answer a descriptive question.</p><p>So instead of:</p><pre>Entire database schema<br>       ↓<br>      LLM</pre><p>we could do:</p><pre>User question<br>       ↓<br>Semantic retrieval<br>       ↓<br>Relevant schema and business context<br>       ↓<br>LLM<br>       ↓<br>SQL<br>       ↓<br>Relational Database</pre><p>For descriptive questions, the flow would be:</p><pre>User question<br>       ↓<br>Query embedding<br>       ↓<br>Vector search<br>       ↓<br>Relevant documentation<br>       ↓<br>LLM<br>       ↓<br>Natural-language answer</pre><p>From my perspective, <strong>this hybrid approach is better than trying to replace the normal database with vector storage</strong>.</p><h3>The architecture I would aim for</h3><p>After going through all of these problems, the architecture I would aim for is something like:</p><pre>USER<br>                                │<br>                                ▼<br>                         Chatbot API<br>                                │<br>                                ▼<br>                         KPI Keyword Router<br>                                │<br>              ┌─────────────────┴─────────────────┐<br>              │                                   │<br>       KPI keyword found                    No KPI keyword<br>              │                                   │<br>              ▼                                   ▼<br>      Analytics Function                    Intent Router<br>              │                                   │<br>              ▼                    ┌──────────────┼──────────────┐<br>      Real-Time KPI Data            │              │              │<br>              │                     ▼              ▼              ▼<br>              │                  Structured   Descriptive     General<br>              │                  Database      Knowledge       Query<br>              │                  Question      Question          │<br>              │                     │              │              ▼<br>              │                     ▼              ▼       General Response<br>              │                Permission   Embedding<br>              │                   Check      Generation<br>              │                     │              │<br>              │                     ▼              ▼<br>              │                SQL Prompt    Vector Search<br>              │                     │              │<br>              │                     ▼              ▼<br>              │                Gemini or     Cosine Similarity<br>              │                Ollama              │<br>              │                     │              ▼<br>              │                     ▼       Similarity &gt; 0.6?<br>              │                Extract SQL          │<br>              │                     │       ┌────────┴────────┐<br>              │                     ▼       │                 │<br>              │                Clean SQL    Yes               No<br>              │                     │       │                 │<br>              │                     ▼       ▼                 ▼<br>              │                Validate   Top Five       Fallback Response<br>              │                     │     Records<br>              │                     ▼       │<br>              │                Execute SQL │<br>              │                     │       │<br>              │                     ▼       │<br>              │                Database    │<br>              │                  Result    │<br>              │                     │       │<br>              └──────────────┬──────┴───────┘<br>                             ▼<br>                    LLM Response Formatter<br>                             │<br>                             ▼<br>                          RESPONSE</pre><p>The LLM service itself can be represented as:</p><pre>LLM Service<br>                            │<br>                     Provider Adapter<br>                            │<br>             ┌──────────────┴──────────────┐<br>             │                             │<br>          Gemini                         Ollama<br>             │                             │<br>       Model fallback                 Local model</pre><p>The knowledge retrieval layer can be represented as:</p><pre>Knowledge Text<br>      ↓<br>Gemini Embedding Model<br>      ↓<br>Embedding Vector<br>      ↓<br>chatbot_knowledge_embeddings<br>      ↓<br>Cosine Similarity Search<br>      ↓<br>Top Five Relevant Records<br>      ↓<br>LLM Response</pre><h3>What this project taught me beyond “AI”</h3><p>The biggest thing I learned from this project is that building an AI feature is not only about choosing a good model.</p><p>There is a lot more around it.</p><p>You have to think about:</p><p><strong>Routing</strong></p><p>Which method should handle the question?</p><p><strong>KPI accuracy</strong></p><p>Can a known dashboard metric be calculated deterministically?</p><p><strong>Structured data</strong></p><p>Does the answer need to come from current relational tables?</p><p><strong>Semantic knowledge</strong></p><p>Does the answer require documentation or business context?</p><p><strong>Reliability</strong></p><p>What happens when the model fails?</p><p><strong>Security</strong></p><p>What happens if the user asks for data they should not access?</p><p><strong>Validation</strong></p><p>Can we trust the SQL generated by the model?</p><p><strong>Embeddings</strong></p><p>How do we find semantically relevant knowledge?</p><p><strong>Similarity thresholds</strong></p><p>How do we decide whether retrieved content is relevant enough?</p><p><strong>Architecture</strong></p><p>How tightly is our application coupled to a specific LLM provider?</p><p><strong>Performance</strong></p><p>Are we sending unnecessary context to the model?</p><p><strong>Data</strong></p><p>Should this information come from the LLM, the relational database, or the knowledge base?</p><p><strong>Fallbacks</strong></p><p>Can the application still provide a useful response when an AI service is unavailable?</p><p>These questions were honestly more interesting to me than simply getting the first SQL query to work.</p><h3>Final thoughts</h3><p>When I first started this chatbot, my thinking was basically:</p><blockquote><em>User asks → LLM answers.</em></blockquote><p>After working on it, my thinking has changed to:</p><blockquote><em>User asks → the system identifies the type of question → selects the appropriate method → verifies permissions → retrieves reliable data or knowledge → validates the result → and finally uses AI to explain it.</em></blockquote><p>That is a completely different way of looking at an AI-powered application.</p><p>The four methods helped clarify the responsibilities:</p><pre>KPI question<br>   → Keyword router<br>   → Analytics function<br>   → Real-time KPI data<br>   → LLM response</pre><pre>Structured question<br>   → SQL generation<br>   → SQL extraction<br>   → SQL cleaning<br>   → SQL validation<br>   → Database execution<br>   → LLM response</pre><pre>Descriptive question<br>   → Gemini embedding<br>   → Cosine similarity<br>   → Top five knowledge records<br>   → LLM response</pre><pre>General question<br>   → General conversational response</pre><p>I also realized that <strong>LLMs do not have to replace traditional software components</strong>.</p><p>In a real application, the best solution can be a combination of:</p><ul><li>Traditional backend logic</li><li>Keyword-based routing</li><li>Analytics functions</li><li>Relational databases</li><li>Authentication and authorization</li><li>SQL</li><li>Gemini</li><li>Ollama</li><li>Embeddings</li><li>Cosine similarity</li><li>Vector search</li><li>Validation</li><li>Fallback mechanisms</li></ul><p>Each technology has a job.</p><p>For our current implementation, the relational database is still the right place for structured workflow and document data. Since our knowledge base is currently small, storing embeddings in the relational database is also acceptable.</p><p>However, as the system grows, moving embeddings to a dedicated vector store such as Pinecone, ChromaDB, or Qdrant could provide a better search mechanism.</p><p>The most important design decision is not choosing one technology for everything.</p><p>It is choosing the right method for the right type of question.</p><p>For structured questions, we need real data from relational tables.</p><p>For descriptive questions, we need semantic retrieval from documentation and knowledge embeddings.</p><p>For known KPI questions, deterministic analytics functions are often more reliable than dynamic SQL generation.</p><p>For general questions, we should avoid unnecessary database and vector operations.</p><p>So, if I were to take this chatbot to the next level, I would not simply add <strong>more LLMs</strong>.</p><p>I would make the overall system smarter about:</p><ul><li>When to use an LLM</li><li>When to use a deterministic analytics function</li><li>When to generate SQL</li><li>When to use vector search</li><li>What information to provide to the model</li><li>What the user is allowed to access</li><li>How to validate generated SQL</li><li>What should happen when a method fails</li><li>How to provide a useful response even when the LLM is unavailable</li></ul><p>And honestly, that is probably the biggest lesson I took away from building this.</p><p><strong>Building an AI feature is not just about making the AI work. It is about making the whole system work reliably around the AI.</strong></p><h3>Explore the Project</h3><p>If you’d like to take a closer look at the implementation, the DocFlow project is available on GitHub:</p><ul><li><strong>Frontend:</strong> <a href="https://github.com/CodeCraft-Software-Project-46/DOC-Flow-Frontend-React">DOC-Flow-Frontend-React</a></li><li><strong>Backend:</strong> <a href="https://github.com/CodeCraft-Software-Project-46/Doc-Flow-Backend">Doc-Flow-Backend</a></li></ul><p>The repositories contain the React frontend and Django backend, including the analytics, working-hours configuration, SLA engine, and chatbot components I worked on.</p><p>Feel free to explore the code and share any suggestions or improvements. I’m always interested in learning how these systems can be designed and implemented better</p><h3>Final Thoughts</h3><p>When I first started this chatbot, my thinking was basically:</p><blockquote><em>User asks → LLM answers.</em></blockquote><p>After working on it, my thinking has changed to:</p><blockquote><em>User asks → the system understands the intent → verifies what the user is allowed to access → retrieves the right context → generates a controlled query → validates it → gets the actual data → and finally uses AI to explain the result.</em></blockquote><p>That is a completely different way of looking at an AI-powered application.</p><p>I also realized that <strong>LLMs don’t have to replace traditional software components</strong>.</p><p>In a real application, the best solution can be a combination of:</p><ul><li>Traditional backend logic</li><li>Relational databases</li><li>Authentication and authorization</li><li>SQL</li><li>LLMs</li><li>Local models</li><li>Vector search</li><li>Validation</li><li>Fallback mechanisms</li></ul><p>Each technology has a job.</p><p>For me, this project wasn’t just about building a chatbot. It was about learning how an AI component can actually fit into a larger software system.</p><p>And I know there is still a lot more for me to learn.</p><p>If you made it this far, <strong>thank you for reading!</strong> 🙌</p><p>If you have experience with systems like this, I’d love to hear your thoughts, corrections, or recommendations in the comments. I’m still learning, so your feedback would genuinely help me understand how these systems are designed in real-world applications.</p><p>Until the next one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=969e20953221" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bootstrap for Beginners]]></title>
            <link>https://medium.com/@savandikodithuwakku/bootstrap-for-beginners-1ce15a5b9bc5?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ce15a5b9bc5</guid>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 11:44:16 GMT</pubDate>
            <atom:updated>2026-09-02T11:44:16.199Z</atom:updated>
            <content:encoded><![CDATA[<h3>Buttons</h3><pre>&lt;div class=&quot;container&quot;&gt;<br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;h1&gt;Buttons&lt;/h1&gt;<br>                &lt;buttons class=&quot;btn btn-primary&quot;&gt;Primary&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-secondary&quot;&gt;Secondary&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-success&quot;&gt;Success&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-danger&quot;&gt;Danger&lt;/buttons&gt; <br>                &lt;buttons class=&quot;btn btn-warning&quot;&gt;Warning&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-info&quot;&gt;Info&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-light&quot;&gt;Light&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-dark&quot;&gt;Dark&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-link&quot;&gt;Dark&lt;/buttons&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*WbwPoA6-v3hqklsxjvMyNQ.png" /></figure><p>Buttons can also be created with the &lt;input&gt; tag, combining functionality with interactive and engaging design elements.</p><pre>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>               &lt;a href=&quot;www.google.com&quot; class=&quot;btn btn-primary&quot; role=&quot;button&quot;&gt;Google&lt;/a&gt;<br>               &lt;input type=&quot;button&quot; value=&quot;submit&quot; class=&quot;btn btn-primary&quot;&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*G_ngGC4sn-uIyNuuRW430A.png" /></figure><p>Outline buttons use btn-outline-* classes for a sleek, bordered look without a background.</p><pre>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;h1&gt;Buttons&lt;/h1&gt;<br>                &lt;buttons class=&quot;btn btn-outline-primary&quot;&gt;Primary&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-secondary&quot;&gt;Secondary&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-success&quot;&gt;Success&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-danger&quot;&gt;Danger&lt;/buttons&gt; <br>                &lt;buttons class=&quot;btn btn-outline-warning&quot;&gt;Warning&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-info&quot;&gt;Info&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-light&quot;&gt;Light&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-dark&quot;&gt;Dark&lt;/buttons&gt;<br>                &lt;buttons class=&quot;btn btn-outline-link&quot;&gt;Dark&lt;/buttons&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*kw1o6_R_PAI0bpziEztHXw.png" /></figure><p>Buttons can have interactive states like active for emphasis or disabled to make them unclickable.</p><pre>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;button class=&quot;btn btn-primary active&quot;&gt;Active&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot; disabled&gt;Disabled&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*CQncNhyRGn_5X6Llx-NTGA.png" /></figure><p>Buttons can be grouped horizontally with btn-group or vertically with btn-group-vertical for structured layouts.</p><pre>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;btn-group&quot; role=&quot;group&quot;&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Left&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot;&gt;Middle&lt;/button&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Right&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt; &lt;br&gt;<br><br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;btn-group-vertical&quot; role=&quot;group&quot;&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Left&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot;&gt;Middle&lt;/button&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Right&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*i2yIoTnbS43_2rH2nE1s5w.png" /></figure><p>buttons can be categorized into groups with adjustable sizes using classes like btn-group, btn-group-sm, and btn-group-lg. Additionally, buttons&#39; sizes can be customized with classes such as btn-lg, btn-sm</p><pre>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;col-12&quot;&gt;<br>                &lt;button class=&quot;btn btn-lg btn-primary&quot;&gt;Large&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot;&gt;Default&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-sm btn-primary&quot;&gt;Small&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt; &lt;br&gt;<br><br>&lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;btn-group btn-group-sm&quot; role=&quot;group&quot;&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Left&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot;&gt;Middle&lt;/button&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Right&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt; &lt;br&gt;<br><br>        &lt;div class=&quot;row&quot;&gt;<br>            &lt;div class=&quot;btn-group btn-group-lg&quot; role=&quot;group&quot;&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Left&lt;/button&gt;<br>                &lt;button class=&quot;btn btn-primary&quot;&gt;Middle&lt;/button&gt;<br>                &lt;button  class=&quot;btn btn-primary&quot;&gt;Right&lt;/button&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*dkb_nUsHZ90qiJ11iL0ouQ.png" /></figure><h3>Alerts</h3><pre> &lt;div class=&quot;alert alert-primary&quot; role=&quot;alert&quot;&gt;<br>            New features have been added to your account. Check them out in the dashboard!<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I3wLOe_Bu7QSo80thI4NWw.png" /></figure><pre>&lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>            &lt;a href=&quot;#&quot; class=&quot;alert-link&quot;&gt;Login&lt;/a&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HjAmsl5R_tnZ5YomrB4VfQ.png" /></figure><pre>&lt;div class=&quot;alert alert-success&quot; role=&quot;alert&quot;&gt;<br>            &lt;h1 class=&quot;alert-heading&quot;&gt; Registration Successful&lt;/h1&gt; <br>            &lt;p&gt;Your account is now active. &lt;/p&gt;<br>            &lt;hr&gt;<br>            &lt;p class=&quot;mb-0&quot;&gt;Start exploring our services immediately!&lt;/p&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0PXDyEiDDcNYSHzlfkl2OQ.png" /></figure><p>The alert-dismissible class adds a close button so users can remove the alert. The fade class makes the alert appear and disappear smoothly. The show class makes the alert visible when it first shows up. The close button is styled with the close class, and data-bs-dismiss=&quot;alert&quot; makes it close the alert when clicked. The aria-label=&quot;Close&quot; helps screen readers understand that it’s a close button, while aria-hidden=&quot;true&quot; hides the &quot;×&quot; symbol from screen readers to avoid repeating information. The &quot;×&quot; symbol (&amp;times;) is what we see as the close button.</p><pre><br>&lt;div class=&quot;alert alert-danger alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;<br>            Invalid username or password. Please try again.<br>            &lt;button type=&quot;button&quot; class=&quot;close&quot; data-bs-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;<br>                &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;<br>            &lt;/button&gt;<br>        &lt;/div&gt;<br>        &lt;br&gt; &lt;br&gt;<br><br>        &lt;div class=&quot;alert alert-warning alert-dismissible fade show&quot; role=&quot;alert&quot;&gt;<br>            Your session is about to expire due to inactivity  <br>            &lt;button type=&quot;button&quot; class=&quot;close&quot; data-bs-dismiss=&quot;alert&quot; aria-label=&quot;Close&quot;&gt;<br>                &lt;span aria-hidden=&quot;true&quot;&gt;&amp;times;&lt;/span&gt;<br>            &lt;/button&gt;<br>        &lt;/div&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qG6kMyD6TKMHJ-XQklWbIQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ce15a5b9bc5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript for Beginners]]></title>
            <link>https://medium.com/@savandikodithuwakku/javascript-for-beginners-e26e2fd5ec11?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/e26e2fd5ec11</guid>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 11:43:31 GMT</pubDate>
            <atom:updated>2026-09-02T11:43:31.464Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functions</h3><ul><li>Functions let you reuse code again and again throughout your program.</li><li>When declaring a function, you can specify parameters. These parameters should be provided as arguments when calling the function.</li><li>The number of arguments and parameters must be the same.</li></ul><pre>function add(num1, num2) {    // Declaring the function<br>    return num1 + num2;<br>}<br><br>console.log(add(5, 2));      // Calling the function<br>                              // 7</pre><p>The function keyword is used to define a function named add.num1 and num2 are parameters that the function will use.The function adds these two numbers together and returns the result.console.log(add(5, 2)); calls the add function with 5 and 2 as arguments. The function returns 7, which is then printed to the console.</p><h3>Local Vs Global variables</h3><ul><li><strong>Global variables</strong> are defined outside any function and can be used anywhere in the code.</li><li><strong>Local variables</strong> are defined within a function and can only be used inside that function.</li><li>When both global and local variables have the same name, the local variable takes priority within its function.</li></ul><pre>let x = 5;           <br><br>function ex1() {<br>    let y = 1;   <br>    console.log(x);  <br>}<br><br>function ex2() {<br>    let x = 2;    <br>    console.log(x);    <br>}<br><br>ex1();                     // 5      <br>ex2();                     // 2</pre><p>In this example, x=5 is a global variable because it&#39;s defined outside of any function. Inside ex1, the global x is accessed and printed. Inside ex2, a local variable x is defined, which takes priority over the global x within that function, so the local x is printed instead.</p><h3>Arrays</h3><p>An array is a variable structure that can store multiple values. In this example, we start with an array of fruits.</p><pre>let fruits=[&quot;apple&quot;,&quot;mango&quot;,&quot;banana&quot;];<br>console.log(fruits[1]);                      //mango<br>                                            <br><br>fruits[1]=&quot;orange&quot;;<br>console.log(fruits[1]);                      //orange<br><br>fruits.push(&quot;strawberry&quot;);<br>console.log(fruits);                         //[apple,orange,banana,strawberry]<br>                                 <br>fruits.pop();<br>console.log(fruits);                         //[apple,orange,banana]<br><br>fruits.unshift(&quot;strawberry&quot;);<br>console.log(fruits);                         //[strawberry,apple,orange,banana]<br><br>fruits.shift(&quot;strawberry&quot;);<br>console.log(fruits);                         //[apple,orange,banana]<br><br>console.log(fruits.length);                  //3<br>console.log(fruits.indexOf(&quot;banana&quot;));       //2<br>console.log(fruits.indexOf(&quot;kiwi&quot;));         //-1<br><br>console.log(fruits.sort());                  //[&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;]<br>console.log(fruits.sort().reverse());        //[&#39;orange&#39;, &#39;banana&#39;, &#39;apple&#39;]<br><br>//print items in array<br>let i;<br><br>for(i=0;i&lt;fruits.length;i++){<br>    console.log(fruits[i]);                  //orange banana apple<br>}<br><br>for(i of fruits){<br>    console.log(i)                           //orange banana apple<br>}</pre><p><strong>push</strong>: Adds an element to the end of the array.</p><p><strong>pop</strong>: Removes the last element from the array.</p><p><strong>unshift</strong>: Adds an element to the beginning of the array.</p><p><strong>shift</strong>: Removes the first element from the array.</p><p><strong>length</strong>: Returns the number of elements in the array.</p><p><strong>indexOf</strong>: Finds the index of an element in the array (returns -1 if not found).</p><p><strong>sort</strong>: Sorts the elements of the array alphabetically.</p><p><strong>reverse</strong>: Reverses the order of the elements in the array.</p><p><strong>for loop:</strong> Iterates over the array using an index.</p><p><strong>for…of loop</strong>: Iterates over the array directly by elements.</p><h3>Spread operator (…)</h3><p>The spread operator (...) is used to<strong><em> </em>unpack elements<em> </em></strong>from an array or string. This <strong>expands an array into separate elements</strong>. The join() method adds a specified separator between elements of an array, but it works with arrays only. Also we can combine 2 arrays using (…) thoough we can do the same using pop().</p><pre>let numbers1 = [10, 20, 30, 40, 50];<br><br>let max = Math.max(numbers1);                    <br>console.log(max);<br><br>max = Math.max(...numbers1);                     <br>console.log(max);                                // 50<br><br>console.log(...numbers1);                        // 10 20 30 40 50<br><br>let name1 = &quot;Savandi&quot;;<br>console.log([...name1].join(&quot;*&quot;));               // S*a*v*a*n*d*i<br><br>let numbers2 = [60, 70, 80, 90, 100];<br>console.log([...numbers1, ...numbers2]);         // [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]</pre><h3>Rest parameters</h3><h3>Regular Expressions</h3><p>A <strong>powerful tool</strong> used for <strong>pattern matching</strong> and <strong>searching</strong> within strings. This method is used to find <strong>all occurrences</strong> of a pattern in a string, rather than stopping at the first match. The <strong>g flag</strong> stands for <strong>global</strong>. Without the ‘g’ it ends the searching after first match. Syntax is like this</p><p>/pattern/g</p><p>Special characters that can be used as pattern</p><p>. Any char except new line</p><p>\d any digit</p><p>\s any white space</p><p>\w any word</p><pre>let text = &quot;Banana apple guava&quot;;<br>let matches = text.match(/a/g);<br>console.log(matches);          //[&quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;, &quot;a&quot;]<br><br>let text = &quot;Phone:1234567890&quot;;<br>let matches = text.match(/\d/g);<br>console.log(matches);         // [&quot;1&quot;, &quot;2&quot;, &quot;3&quot;, &quot;4&quot;, &quot;5&quot;, &quot;6&quot;, &quot;7&quot;, &quot;8&quot;, &quot;9&quot;, &quot;0&quot;]<br><br><br>let text = &quot;Hello World! Welcome to coding.&quot;;<br>let matches = text.match(/\s/g);<br>console.log(matches);        // [&quot; &quot;, &quot; &quot;, &quot; &quot;, &quot; &quot;]<br><br>let text = &quot;Hello World!&quot;;<br>let matches = text.match(/\S/g);<br>console.log(matches);        //[&quot;H&quot;, &quot;e&quot;, &quot;l&quot;, &quot;l&quot;, &quot;o&quot;, &quot;W&quot;, &quot;o&quot;, &quot;r&quot;, &quot;l&quot;, &quot;d&quot;, &quot;!&quot;]<br><br>let text = &quot;cat car cup clock&quot;;<br>let matches = text.match(/\bc\w*/g);<br>console.log(matches);        //[&quot;cat&quot;, &quot;car&quot;, &quot;cup&quot;, &quot;clock&quot;]<br><br></pre><p>We can use this regular expression in various methods as below</p><p>.match()</p><p>returns an array of all matches found in the string or null if no matches are found</p><pre>let text = &quot;(a + b) * (c - d)&quot;;<br>let matches = text.match(/\(/g);<br>console.log(matches); // Output: [&quot;(&quot;, &quot;(&quot;]</pre><p>.test()</p><p>returns true if the pattern is found in the string, otherwise false</p><pre>let text = &quot;Hello World!&quot;;<br>let hasOpeningParenthesis = /\(/g.test(text);<br>console.log(hasOpeningParenthesis); // Output: false</pre><p>.replace()</p><p>replace all occurrences of a pattern in a string</p><pre>let text = &quot;(a + b) * (c - d)&quot;;<br>let newText = text.replace(/\(/g, &quot;[&quot;);<br>console.log(newText); // Output: &quot;[a + b) * [c - d)&quot;</pre><p>.split()</p><p>to split a string into an array</p><pre>let text = &quot;(1,2),(3,4),(5,6)&quot;;<br>let splitArray = text.split(/\(/g);<br>console.log(splitArray); // Output: [&quot;&quot;, &quot;1,2),&quot;, &quot;3,4),&quot;, &quot;5,6)&quot;]</pre><p>Try Catch</p><p>When your code runs into a problem (like trying to evaluate an invalid mathematical expression), it can cause your program to crash or behave unexpectedly. Instead of stopping the entire program when an error occurs, try...catch lets you handle the error and continue running.</p><ul><li><strong>try</strong> Contains the code that you want to test for errors.</li><li><strong>catch </strong>Contains the code that runs if an error is thrown in the try block.</li></ul><pre>try {<br>    let result = eval(&#39;10 + 5)&#39;); // This is invalid due to the unmatched parenthesis<br>    console.log(&quot;Result:&quot;, result);<br>} catch (error) {<br>    console.error(&quot;An error occurred:&quot;, error.message);<br>}</pre><h3>setTimeout()</h3><p>setTimeout(function, delay, param1, param2, …);</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;This prints after 2 sec&quot;);<br>}, 2000);<br></pre><pre>function greet(name) {<br>  console.log(&quot;Hello &quot; + name);<br>}<br><br>setTimeout(greet, 3000, &quot;Savandi&quot;); // After 3s it prints Hello Savandi</pre><pre>let timeoutId = setTimeout(() =&gt; {<br>  console.log(&quot;User has been inactive for 5 minutes. Logging out...&quot;);<br>}, 300000); // 5 minutes<br><br>document.addEventListener(&quot;mousemove&quot;, () =&gt; {<br>  clearTimeout(timeoutId); // Cancel the logout<br>});</pre><h3>setInterval()</h3><p>setInterval(function, delay, param1, param2, …);</p><p>This function executes repeatedly after a fixed time s forever (until you stop it)</p><pre>setInterval(() =&gt; {<br>  console.log(&quot;This prints every 2 seconds&quot;);<br>}, 2000);</pre><pre>function greet(name) {<br>  console.log(&quot;Hello &quot; + name);<br>}<br><br>setInterval(greet, 1000, &quot;Savandi&quot;); //This prints every 1 sec</pre><p>❌ How to stop it? use clearInterval()</p><pre>let id = setInterval(() =&gt; {<br>  console.log(&quot;Repeating...&quot;);<br>}, 1000);<br><br>setTimeout(() =&gt; {<br>  clearInterval(id);<br>  console.log(&quot;Stopped the interval&quot;);<br>}, 5000);</pre><h3>Promises</h3><p>A <strong>Promise</strong> is used <strong>whenever you do something that takes time. </strong>Promise runs in the background, and meanwhile the main code keeps running. Then when the Promise finishes, it gives the output to .then() or .catch()</p><p>Promise is a class we have to create new object of it.</p><p>In a Promise, there is a selection.<br>If the condition is true, it runs the resolve() part, and then .then() runs.<br>If the condition is false, it runs the reject() part, and then .catch() runs.</p><pre>let pizza = new Promise((resolve, reject) =&gt; {<br>  let pizzaReady = true;<br><br>  if (pizzaReady) {<br>    resolve(&quot;Here is your pizza 🍕&quot;);<br>  } else {<br>    reject(&quot;Sorry, pizza is not available 😢&quot;);<br>  }<br>});<br><br>pizza<br>  .then((result) =&gt; {<br>    console.log(&quot;SUCCESS: &quot; + result);<br>  })<br>  .catch((error) =&gt; {<br>    console.log(&quot;FAILED: &quot; + error);<br>  });<br>  .finally(() =&gt; {<br>  console.log(&quot;I run no matter what 🚀&quot;);<br>});</pre><p>You <strong>only</strong> use new Promise() when you are making your own Promise manually.<br>But if a function like fetch() already gives you a Promise, you just use .then() on it</p><pre>fetch(&quot;https://api.example.com/user&quot;)<br>  .then((response) =&gt; response.json())<br>  .then((data) =&gt; console.log(data))<br>  .catch((error) =&gt; console.log(error));</pre><p>We can do the same thing by async/await. With async/await, you don’t use .then() and .catch() Instead, you use <strong>try...catch</strong> to handle success and errors</p><pre>async function getUser() {<br>  try {<br>    let response = await fetch(&quot;https://api.com/user&quot;); // <br>    let data = await response.json();<br>    console.log(data);<br>  } catch (err) {<br>    console.log(&quot;Error:&quot;, err);<br>  }<br>}</pre><p>fetch() returns a Promise await waits for that Promise If the fetch fails (e.g., no internet, 404 error, etc.), it throws an error</p><p>Both methods loads user data in the background without interrupting other tasks such as animations, clicks, or UI updates. But async await keeps the code clean.</p><p>setTimeout, setInterval and promises those are Asynchronous that means starts the task, then continues with the next line without waiting for first task to finish.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e26e2fd5ec11" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React JS]]></title>
            <link>https://medium.com/@savandikodithuwakku/react-js-52eeec62e9f0?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/52eeec62e9f0</guid>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 18:10:04 GMT</pubDate>
            <atom:updated>2026-08-27T18:10:04.558Z</atom:updated>
            <content:encoded><![CDATA[<p>React is a JavaScript library for building user interfaces</p><ol><li>Create a new react app- npm create vite@latest first-app</li></ol><p>2. Navigate into your project folder- cd first-app</p><p>3. Install dependencies- npm install</p><p>4. Start development server- npm run dev</p><p>If you have closed VS Code, reopen it and</p><ol><li>Navigate into your project folder- cd first-app</li></ol><p>2. Start development server- npm run dev</p><p>Your project will have these main folders:</p><h3>Folders and Their Purpose:</h3><ul><li><strong>src/</strong> – Contains your React components, styles, and logic.</li><li><strong>public/</strong> – Stores static assets (images, icons) and index.html, the main entry file.</li><li><strong>node_modules/</strong> – Holds installed dependencies (managed by npm).</li></ul><h3>📄 Important Files and Their Purpose:</h3><ul><li><strong>App.tsx / </strong><strong>App.jsx</strong> – The main React component where you build your app’s UI.</li><li><strong>App.css</strong> – Styles specific to App.tsx / App.jsx.</li><li><strong>index.css</strong> – Global styles applied across the entire app</li><li><strong>main.tsx / </strong><strong>main.jsx</strong> – The entry point of the React app; renders App.tsx inside index.html.</li><li><strong>package.json</strong> – Keeps track of project dependencies, scripts, and metadata(name,version no)</li><li><strong>vite.config.ts</strong> – Configuration file for Vite (handles optimizations and build settings).</li></ul><p>Index.html</p><pre>&lt;body&gt;<br>    &lt;div id=&quot;root&quot;&gt;&lt;/div&gt;                   <br>    &lt;script type=&quot;module&quot; src=&quot;/src/main.jsx&quot;&gt;&lt;/script&gt; <br>  &lt;/body&gt;</pre><p>&lt;div&gt; is like an empty container where our React app will be created and Then, the browser executes main.jsx because of the &lt;script&gt; tag in index.html</p><p>main.jsx</p><pre>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import &#39;./index.css&#39;<br>import App from &#39;./App.jsx&#39;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(        //finds id=root<br>  &lt;React.StrictMode&gt;<br>    &lt;App /&gt; <br>  &lt;/React.StrictMode&gt;<br>)</pre><p>Imports the App component from App.jsx here. A component is like a reusable building block for your UI . Now it finds the &lt;div id=”root”&gt;&lt;/div&gt; inside index.html and it starts to execute App.jsx</p><p>App.jsx</p><pre>import Header from &#39;./Header.jsx&#39; <br>function App() {          <br>  return(<br>    &lt;Header/&gt;  <br>  );<br>  <br>}<br><br>export default App </pre><p>This brings the Header component from Header.jsx into App.jsx, so we can use it here. Here it defines a React component called App. &lt;Header/&gt; This brings the Header component from Header.jsx here. So that code part will be replaced here from Header.jsx. So for that it processes Header.jsx now</p><p>Header.jsx</p><pre>function Header() {   <br>    return(<br>        &lt;header&gt;          <br>            &lt;h1&gt;My Website&lt;/h1&gt;<br>        &lt;/header&gt;<br>    );<br>}<br><br>export default Header;   <br></pre><p>This defines an another React component called Header. The function returns JSX (which looks like HTML but works inside JavaScript) and it export it so other files can use this. Also keep in your mind react components can return only single element here it returns the Header element.</p><p>So those JSX code will fetched to App.jsx. After replacing &lt;Header/&gt; by the relevant code part in Header.jsx, now the last line of App.jsx runs and it is also exported.</p><p>Now Main.jsx has read them and now it runs createRoot(document.getElementById(‘root’)).render( part. Lastly, because of this &lt;App /&gt; it inserts App.jsx to the root in index.html. So browser displays as “My Website”</p><p>If we add js code inside return we have to include them in {} But outside of the return no need</p><p>Footer.jsx</p><pre>function Footer(){<br>    return (<br>        &lt;footer&gt;<br>          &lt;p&gt;© {new Date().getFullYear()}My First App&lt;/p&gt;<br>        &lt;/footer&gt;<br>    );<br>}<br>export default Footer;  </pre><h3><strong>How to add styling?</strong></h3><blockquote>Using External CSS</blockquote><p>With jsx we use className instead of class and include the stylings in index.css you dont need to link them. You dont need to write &lt;link rel stylesheet&gt; here</p><pre>import profilepic from &#39;./assets/profile.jpg&#39;;                                                                             //we re taking profile.jpg as profilepic<br>function Card(){<br>    return (<br>        &lt;div className=&quot;card&quot;&gt;<br>            &lt;img src={profilepic} alt=&quot;Card Image&quot; className=&quot;cardImg&quot;/&gt;<br>            &lt;h1 className=&quot;cardTitle&quot;&gt;Sava&lt;/h1&gt;<br>            &lt;p&gt;Im a student of Information Technology&lt;/p&gt;<br>        &lt;/div&gt;<br>    );<br>}<br><br>export default Card</pre><p>Here profile.jpg inside assets is taken as profilepic and it is used.</p><blockquote>Using modules</blockquote><p>Create a new folder for the component and add the jsx file to it create a new css file inside it. In the Button folder there are Button.jsx and Button.module.css likewise. In the jsx file import that css file &amp; add class name with style.</p><pre>import styles from &#39;./Button.module.css&#39;;<br>function Button(){<br>    return (<br>        &lt;button className={styles.btn}&gt;Click Me&lt;/button&gt;<br>    );<br>}<br>export default Button</pre><blockquote>Inline CSS</blockquote><p>Without any other css file we can add stylings to the same jsx file. For that we have to define a new constant and in there include stylings keep in your mind to use camelCase here (backgroundColor not (background-color or backgroundcolor) and separate all stylings with , not with ; All values must be within “ “</p><pre>function Button(){<br>    const styles={<br>            backgroundColor: &quot;#4CAF50&quot;,<br>            border: &quot;none&quot;,<br>            color: &quot;white&quot;,<br>            padding: &quot;15px 32px&quot;,<br>            textAlign: &quot;center&quot;,<br>            textDecoration: &quot;none&quot;,<br>            display: &quot;inline-block&quot;,<br>            fontsize: &quot;16px&quot;,<br>            margin: &quot;4px 2px&quot;,<br>            cursor: &quot;pointer&quot;,<br>            borderRadius: &quot;8px&quot;,<br>    }<br>    return (<br>        &lt;button style={styles}&gt;Click Me&lt;/button&gt;<br>    );<br>}<br>export default Button</pre><h3><strong><em>Props</em></strong></h3><p>Properties are shared between components components. One component can send data to another component by key=value</p><p>Here App.jsx send data to Student.jsx</p><p>Key value pairs are assigned to object called prop in Student.jsx &amp; {props.name} this accesses only the name property from it.</p><p>If the value isnt a string that must be included within { } Values within “ “ are send as strings. For other data types use { }</p><p>prop-types package is a React. It&#39;s used to <strong>validate the types of props</strong> your components receive. This is used for debugging purposes.</p><h4>4 Common Ways to Create &amp; Use a Component</h4><ol><li><strong>Regular Function (</strong>you can use it before it’s defined<strong>)+ Default Export(</strong><em>No curly braces </em><em>{} in import , </em><strong>only one default export</strong> per file, can <strong>rename it freely</strong> during import<em>)</em></li></ol><pre>// 📄 Card.jsx<br>function Card() {<br>  return &lt;div&gt;This is a card&lt;/div&gt;;<br>}<br><br>export default Card;</pre><p>to import</p><pre>import Card from &#39;./components/Card&#39;;<br><br>function App() {<br>  return &lt;Card /&gt;;<br>}<br><br>export default App;</pre><p><strong>2. Regular Function + Named Export(multiple named exports</strong> from a single file, <em>Must use </em><em>{ Card } in import</em></p><p><em>Use the keyword </em><em>export in front of the function or variable name)</em></p><pre>// 📄 Card.jsx<br>export function Card() {<br>  return &lt;div&gt;This is a card&lt;/div&gt;;<br>}</pre><p>to import</p><pre>// 📄 App.jsx<br>import { Card } from &#39;./components/Card&#39;;<br><br>function App() {<br>  return &lt;Card /&gt;;<br>}<br><br>export default App;</pre><p><strong>3. Arrow Function (<em>const is used , </em></strong>must define before use<strong>)+ Default Export</strong></p><pre>// 📄 Card.jsx<br>const Card = () =&gt; {<br>  return &lt;div&gt;This is a card&lt;/div&gt;;<br>};<br><br>export default Card;</pre><p>to export</p><pre>// 📄 App.jsx<br>import Card from &#39;./components/Card&#39;;<br><br>function App() {<br>  return &lt;Card /&gt;;<br>}<br><br>export default App;</pre><p><strong>4. </strong>Arrow Function + Named Export</p><pre>// 📄 Card.jsx<br>export const Card = () =&gt; {<br>  return &lt;div&gt;This is a card&lt;/div&gt;;<br>};</pre><p>to import</p><pre>// 📄 App.jsx<br>import { Card } from &#39;./components/Card&#39;;<br><br>function App() {<br>  return &lt;Card /&gt;;<br>}<br><br>export default App;</pre><ul><li>Named exports are useful when you want to export multiple things from one file.</li><li>Default exports are simpler when the file only exports one component.</li></ul><p>index.css is generally used for <strong>global styles</strong>—styles that apply to the entire application</p><p>App.css is used to style the <strong>App component</strong> specifically</p><p>virtual DOM- lightweight JS representation is updated then actual DOM is updated later.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52eeec62e9f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ What is Artificial Intelligence (AI)?]]></title>
            <link>https://medium.com/@savandikodithuwakku/what-is-artificial-intelligence-ai-85861e036ffc?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/85861e036ffc</guid>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Thu, 27 Aug 2026 18:08:22 GMT</pubDate>
            <atom:updated>2026-08-27T18:08:22.672Z</atom:updated>
            <content:encoded><![CDATA[<p>Artificial Intelligence (AI) is when machines or computer systems are made to “think” or “act” like humans. They can understand information, make decisions, and even learn from experience.</p><p>Artificial Intelligence is no longer just a futuristic concept — it’s part of our daily lives. From voice assistants to research bots, AI is shaping how we work, learn, and connect. In this article, let’s break down what AI really is, how people create AI models, and how agents and multi-agent systems bring them to life.</p><p>Some common technologies in AI are:</p><ul><li><strong>AI Model</strong> — A trained <strong>computer program</strong> that can <strong>predict or generate outputs</strong> based on patterns it learned from data. It doesn’t “memorize” the data — it <strong>learns patterns</strong> from it. (e.g., If you trained an image recognition AI model with <strong>many photos of cats and dogs</strong>, then when you give a new image, it can <strong>predict</strong> whether it’s a cat or a dog. )</li><li><strong>Large Language Models (LLMs)</strong> — These are powerful types of AI models trained on huge amounts of text data — books, websites, articles, etc., to generate human-like responses. (e.g., GPT-4, Llama 3, Gemini, Claude). LLMs act like the <strong>brain</strong> for AI agents and AI assistants.</li><li><strong>Natural Language Processing (NLP)</strong> — This helps computers understand and use human language. (e.g., Siri understanding your voice)</li><li><strong>Computer Vision</strong> — This allows computers to understand images or videos. (e.g., Face unlock on your phone)</li><li><strong>Machine Learning (ML)</strong> — A part of AI where machines learn from data and improve over time.</li><li><strong>Deep Learning</strong> — An advanced type of machine learning that uses artificial neural networks, like the human brain.</li><li><strong>Prompt</strong> — A question or instruction given to an AI (especially in LLMs like ChatGPT).</li><li><strong>Generative AI</strong> — AI that can create new content like text, images, or music. (e.g., MidJourney for art or ChatGPT for text)</li><li><strong>Reinforcement Learning</strong> — A learning method where agents learn by trying things and getting rewards or penalties.</li><li><strong>Fine-Tuning</strong> — Customizing an existing AI model with your own data so it performs better for your specific needs. (e.g., Making GPT better at medical questions using hospital data rather than <strong>training</strong> a model from scratch )</li><li><strong>LangChain</strong> — A framework that helps developers connect LLMs with tools, memory, and external data to build smarter AI agents.</li><li><strong>LlamaIndex</strong> — A tool that connects AI models to large collections of information (like PDFs, websites, or databases) so the AI can give more accurate, specific answers. “<strong>bridge</strong>” between your <strong>data</strong> and your <strong>AI model</strong>.</li></ul><h3>How People Create AI Models</h3><h4>🥇 1. Train from Scratch</h4><ul><li>You collect a <strong>huge amount of data</strong> (like billions of text samples or images).</li><li>You use <strong>powerful computers (GPUs)</strong> to train the model for days or weeks.</li><li>You build a <strong>completely new AI model</strong> from zero.</li><li>This method is used by <strong>big companies</strong> (like OpenAI, Google, Meta).</li><li>💀 Very hard and expensive.</li></ul><h4>⚙️ 2. Fine-tune a Pre-trained Model</h4><ul><li>You start with an <strong>already-trained model</strong> (like GPT or Llama).</li><li>You give it a <strong>smaller, specific dataset</strong> related to your task.</li><li>The model <strong>learns your style or domain</strong> (e.g., medical, legal, or customer support).</li><li>You don’t need huge data or big computers — just moderate resources.</li></ul><h4>✅ 3. Use RAG (Retrieval-Augmented Generation)</h4><ul><li>You take a <strong>ready-made AI model</strong> (no retraining needed).</li><li>You <strong>connect your data</strong> (PDFs, databases, websites, etc.) to it.</li><li>When a user asks something, the model <strong>searches your data</strong> and then answers.</li><li>This is what <strong>LlamaIndex</strong> and <strong>LangChain</strong> help you do.</li><li>✅ Easiest and most practical for developers.</li></ul><h3>💡 What is an Agent?</h3><p>An <strong>AI agent</strong> is a computer system that can <strong>think, plan, learn</strong>, and act <strong>on its own</strong> to reach a goal. Agents are <strong>autonomous</strong>, which means they don’t need someone telling them what to do all the time.</p><p>Every agent uses a <strong>Large Language Model (LLM) </strong>which gives brain to agents. It can have short-term or long-term memory to remember things from users for future usage. They search the internet, do calculations, or fetch data to give answers to user.</p><p>🌟 Example</p><p>Imagine you want a <strong>“Research Assistant Agent”</strong>:</p><ol><li>Use <strong>GPT-4</strong> as the brain. start with a <strong>large language model</strong></li><li>Add a <strong>web search tool</strong> and a <strong>note-taking tool</strong>. Give the Agent Tools or Skills</li><li>Give it a goal: <em>“Find latest AI news and summarize it daily.”</em></li><li>Build it using <strong>LangChain</strong> or <strong>LangGraph</strong>.</li></ol><p>Agents usually work in a loop: reasoning and acting loop</p><ul><li>Read user input 🗣️</li><li>Decide what to do 🧠</li><li>Use a tool (if needed) ⚙️</li><li>Get results 🧾</li><li>Respond back 💬</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3wttheSjQ0epR7c7B_WiQ.png" /></figure><h3>🧠 What is a Large Language Model (LLM)?</h3><p>A <strong>Large Language Model</strong> is a special type of <strong>AI model</strong> trained using <strong>tons of text data</strong>. It’s the <strong>brain behind the agent or assistant</strong>.LLMs use <strong>natural language processing (NLP)</strong> to understand what you say. LLMs turn your words into <strong>mathematical patterns</strong>, and then generate smart replies.</p><p>Example: ChatGPT is powered by <strong>OpenAI’s LLM</strong>, called GPT.</p><p>✅ They can</p><ul><li>Make decisions by themselves</li><li>Learn from experience</li><li>Work towards goals without help</li><li>Collaborate with other agents</li></ul><p>📌 <strong>Example:</strong> Imagine a smart robot vacuum. It learns the shape of your home, decides when and where to clean, and avoids obstacles — all on its own.</p><p>Self driving cars , AI tutors</p><h3>🤝 What is an Assistant?</h3><p>An <strong>AI assistant</strong> is like a helpful friend. You ask it to do something, and it helps you. But <strong>you have to give the instructions</strong>.</p><p>✅ They can:</p><ul><li>Understand voice or text commands</li><li>Give you information</li><li>Perform tasks when asked</li></ul><p>But ❌ they don’t usually make big decisions on their own.</p><p>📌 <strong>Example:</strong> Google Assistant or Siri — you say, <em>“What’s the weather?”</em> or <em>“Set a reminder,”</em> and they respond.</p><p>AI assistant in a travel website when you ask what is the best time or related question it searches the website and give you answers</p><h3>💬 What is a Bot?</h3><p>A <strong>bot</strong> is a <strong>simple computer program</strong> that follows instructions written by a developer. It can’t learn or make decisions — it just does what it’s told.</p><p>✅ They can:</p><ul><li>Answer common questions</li><li>Do basic, pre-programmed tasks</li></ul><p>(They are programmed to give this to this question. But if you ask something outside its programming, it might get confused or give wrong info.)</p><p>❌ They don’t learn or reason from experience or make decisions by themselves. They don’t have a memory or they don’t use tools or internet to find info</p><p>📌 <strong>Example:</strong> A chatbot on a website that says, <em>“Hello! How can I help you?”</em> and gives fixed answers based on your question.</p><p>Chatbot will answer through text or voice</p><p>eg:- Website FAQ , Telegram whatsapp bots</p><h3>Retrieval-Augmented Generation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k1T5nP-W5AEvEbZ-WPI9BQ.png" /></figure><p>Large Language Models (LLMs) are powerful — they can answer questions and generate text. But there’s a problem: <strong>you shouldn’t give them your private or sensitive information directly</strong>.</p><ol><li><strong>Store your private data separately</strong> — PDFs, documents, or database info go into a <strong>vector database</strong>.</li><li><strong>Retrieve relevant info</strong> — When a question is asked, the AI fetches only the relevant data from this database.</li><li><strong>Generate answers</strong> — The LLM uses the retrieved info to create accurate, <strong>specific answers</strong> without exposing your private data.</li></ol><p>📌 <strong>Example:</strong><br> Imagine you have a company policy PDF. Instead of asking the LLM directly, your AI agent checks the PDF in the vector database and then gives the answer about the policy. This keeps your sensitive data safe.</p><p>Tools like <strong>LlamaIndex</strong> are used to connect your data to the LLM in this RAG setup, and <strong>LangChain</strong> can help the AI combine these tools and reasoning steps.</p><h3>🤖 Single Agent vs. Multi-Agent Systems</h3><p><strong>Single Agent</strong></p><ul><li>A single agent works independently to finish a task or reach a goal.</li><li>It can use different tools (like a calculator, search engine, or database).</li><li>But if you give one agent too many tools (more than 8 or 10), it might get confused about which tool to use for a question.</li><li>Example: A single travel booking agent that does <strong>everything</strong> — finding flights, hotels, car rentals, etc.</li></ul><p><strong>Multi-Agent System</strong></p><ul><li>Instead of one agent doing everything, we have <strong>multiple agents</strong>, each doing a specific job.</li><li>These agents <strong>collaboratively</strong> and share information to finish a big task faster and more accurately.</li><li>Example: In a travel booking system:</li></ul><p>Agent 1 → Finds the best flights</p><p>Agent 2 → Finds hotel deals</p><p>Agent 3 → Suggests activities at the destination</p><ul><li>Then they share their results and give one final answer to the user.</li></ul><p><strong>Advantages of Multi-Agent Systems</strong><br> ✅ <strong>Better focus</strong> — Each agent is an expert at one thing.<br> ✅ <strong>Less confusion</strong> — No tool overload for a single agent.<br> ✅ <strong>Faster results</strong> — Tasks can run in parallel.<br> ✅ <strong>Scalable</strong> — Easy to add more agents for new tasks.<br> ✅ <strong>More reliable</strong> — If one agent fails, others can still work.</p><p>Frameworks to Build Multi-Agent Systems</p><ul><li><strong>LangGraph</strong> — A framework that helps build agent workflows using graphs. It’s great for creating structured conversations between agents.</li><li><strong>Azure AI Foundry</strong> — A Microsoft platform that allows you to build, deploy, and manage AI agents easily, with access to Azure’s powerful cloud tools.</li><li><strong>CrewAI</strong> — Focuses on teamwork between agents. You can create multiple agents that collaborate just like human teammates.</li><li><strong>Microsoft Autogen</strong> — A framework that lets agents talk to each other automatically and solve problems together without needing much manual setup.</li></ul><h3>LangChain vs LangGraph</h3><p><strong>LangChain</strong></p><ul><li>Helps connect AI models (like ChatGPT) with tools, memory, and data.</li><li>Works best for simple, step-by-step (linear) agent systems.</li><li>Use cases:<br> 🪄 Chatbots<br> 📚 RAG systems<br> ⚙️ Simple automation tools</li></ul><p><strong>LangGraph</strong></p><ul><li>An advanced version of LangChain designed for complex agent systems.</li><li>Uses a graph-based structure instead of a straight line.</li><li>Better for agents that need to think, plan, and collaborate.</li><li>Use cases:<br> 🤖 Multi-agent systems<br> 🧠 Reasoning groups<br> 🌳 Decision trees<br> 🔁 Iterative workflows</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z9aRcoBfUgc1w5j1LdJ3Jg.png" /><figcaption>Types of Multi agents</figcaption></figure><p>AI is evolving faster than ever — and understanding its core ideas helps us keep up with this intelligent revolution.</p><p>💡 <em>Follow me on Medium to explore more beginner-friendly AI concepts, tools, and frameworks in upcoming blogs!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85861e036ffc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The New Age of Entrepreneurship: Unlocking Opportunities in a Digital-Driven World]]></title>
            <link>https://medium.com/@savandikodithuwakku/the-new-age-of-entrepreneurship-unlocking-opportunities-in-a-digital-driven-world-c4814c94746e?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4814c94746e</guid>
            <category><![CDATA[entrepreneur]]></category>
            <category><![CDATA[women-in-engineering]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[opportunity]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Sun, 24 Nov 2024 15:17:27 GMT</pubDate>
            <atom:updated>2024-11-24T16:18:38.149Z</atom:updated>
            <content:encoded><![CDATA[<p>In the 21st century, entrepreneurship has entered a new era, driven by technological advancements and the rise of digital platforms. Powerful tools like Artificial Intelligence (AI), blockchain, and the Internet of Things (IoT) has given countless opportunities for entrepreneurs to innovate and disrupt traditional industries. The growing demand for sustainability, remote work solutions, and personalized experiences is reshaping the way businesses operate, making it an exciting time for entrepreneurs to enter the market. In this blog, we will explore how technology is transforming entrepreneurship and the new opportunities it presents.</p><h3><strong>Technology-Driven Innovations</strong></h3><p>Technology is revolutionizing industries across the globe, offering entrepreneurs the ability to create new products and services that disrupt existing traditional systems. Technologies like AI, blockchain, IoT, and augmented/virtual reality (AR/VR) are providing endless possibilities for innovation.</p><p><strong>AI Opportunities</strong>: Entrepreneurs can develop AI-powered chatbots, data analysis tools, and automation systems to solve complex business challenges, and provide more personalized customer experiences. From healthcare to finance, AI is being utilized to improve decision-making and efficiency.</p><p><strong>IoT Innovations</strong>: The Internet of Things is at the forefront of innovation, enabling smart home devices, wearables, and connected healthcare solutions. IoT is not only transforming consumer products but is also being used to optimize business operations in industries like agriculture, logistics, and manufacturing.</p><p>By embracing these technologies, entrepreneurs can enhance business efficiency, reach wider audiences, and create value-driven solutions that resonate with modern consumers. The opportunities for innovation are limitless</p><h3>E-Commerce and Digital Marketplaces</h3><p>The e-commerce industry has observed explosive growth, especially in the after the pandemic. Entrepreneurs now have the ability to reach global customers with minimal infrastructure, thanks to the rise of digital marketplaces and online platforms.</p><p><strong>Niche Markets</strong>: One of the key opportunities in e-commerce is offering niche markets. Specialized products such as sustainable fashion, eco-friendly goods, or pet tech gadgets appeal to loyal customer bases that value unique, high-quality offerings.</p><p><strong>Subscription Models</strong>: Subscription-based businesses have seen an increase in popularity. Entrepreneurs can offer subscription boxes, recurring services, or digital subscriptions that create consistent revenue streams. The predictability of subscription models is attractive for business owners looking for stability.</p><p><strong>Social Commerce</strong>: Social media platforms like Youtube, Instagram and TikTok have transformed how businesses market and sell their products. With the ability to promote products through influencers and ads, these platforms make it easier for even small-scale entrepreneurs to access a global market. Social commerce is a powerful tool for reaching customers often with a smaller investment.</p><h3>Sustainability and Green Businesses</h3><p>In recent years, consumers have become more conscious of their environmental impact. As a result, sustainable and eco-friendly businesses have become a growing trend. Entrepreneurs can capitalize on this movement by offering products and services that prioritize sustainability.</p><p><strong>Sustainable Packaging</strong>: With an increasing demand for eco-conscious packaging, entrepreneurs can develop biodegradable or reusable materials to meet the growing market for sustainable products.</p><p><strong>Clean Energy Solutions</strong>: Renewable energy usage is increasing, creating opportunities for businesses that promote solar energy, energy-efficient appliances, and other green technologies. Entrepreneurs can invest in clean energy solutions to offer consumers who want to reduce their carbon footprint.</p><p><strong>Recycling Innovations</strong>: From converting waste into reusable materials to developing new recycling technologies, entrepreneurs can explore creative solutions that help reduce waste and promote sustainability.</p><h3>Remote Work and Freelance Platforms</h3><p>The shift to remote work has created new opportunities for entrepreneurs offer the needs of a decentralized workforce. With more individuals working from home, the demand for tools and services that enable remote work is higher than ever.</p><p><strong>Collaboration Tools</strong>: Developing platforms for team communication, project management, or workflow optimization is a key area for innovation. Entrepreneurs can build tools that enhance collaboration in a remote work environment.</p><p><strong>Freelance Marketplaces</strong>: With the rise of the gig economy, entrepreneurs can create niche freelance platforms that connect specialists with clients. For instance, building a platform for creatives or tech professionals can help entrepreneurs tap into the growing freelance workforce.</p><p><strong>Co-Working Spaces</strong>: While many people work remotely, some still prefer physical spaces to collaborate or hold meetings. Entrepreneurs can establish hybrid workspaces that offer both virtual and physical meeting locations for remote teams.</p><h3>Personalized Customer Experiences</h3><p>Consumers now expect highly personalized experiences. The ability to provide customized products, services, and interactions is a key factor in customer satisfaction and loyalty. Entrepreneurs can use data, AI, and technology to offer more personalized solutions.</p><p><strong>AI-Driven Recommendations</strong>: Using AI, entrepreneurs can create personalized shopping or entertainment experiences by analyzing customer behavior and preferences. Recommender systems can drive sales and enhance user engagement by suggesting products or services that are relevant to individual customers.</p><p><strong>Customizable Products</strong>: Allowing customers to design and customize their own products whether it’s clothing, jewelry, or digital content it offers a unique selling point for businesses and can drive customer satisfaction.</p><p><strong>Interactive Services</strong>: Virtual consultations, product demos, and interactive services allow businesses to engage customers in meaningful ways. Entrepreneurs can use these services to create more immersive and personalized experiences.</p><h3>Social Entrepreneurship</h3><p>As more people prioritize social and environmental causes, social entrepreneurship has become an exciting path for business owners looking to balance profit with purpose. Entrepreneurs can build businesses that create positive change in society or address global challenges.</p><p><strong>Education Technology</strong>: Offering affordable or free learning platforms to neglected students or marginalized communities can have a profound impact. Entrepreneurs can create online education platforms, digital tutoring services, or tools that make learning more accessible for everyone.</p><p><strong>Healthcare Access</strong>: Entrepreneurs can build telemedicine platforms, mobile clinics, or healthcare apps that increase access to medical services for rural areas.</p><p><strong>Community Development</strong>: Social entrepreneurs can also focus on projects that reinvest profits into local infrastructure, education, or healthcare. By addressing community needs, businesses can create lasting positive change while generating profits.</p><h3>Content Creation and Digital Media</h3><p>The digital content industry has exploded in recent years, providing numerous opportunities for entrepreneurs to create value through media and entertainment.</p><p><strong>Video Production</strong>: Platforms like YouTube, TikTok, and Instagram have provided video production, allowing anyone with a camera and creativity to reach millions. Entrepreneurs can create original content for various platforms, including product reviews, tutorials, and entertainment.</p><p><strong>Podcasting</strong>: Niche podcasts on topics like finance, fitness, or personal development attract dedicated audiences and reveal opportunities for monetization through sponsorships or advertising.</p><p><strong>E-Learning Platforms</strong>: The demand for online courses and educational content has increased. Entrepreneurs can build e-learning platforms to offer professional development, certifications, or skill-based courses to a global audience.</p><h3>Health and Wellness</h3><p>With a growing focus on personal health, wellness, and mental well-being, entrepreneurs have opportunity to innovate in this sector.</p><p><strong>Fitness Tech</strong>: Wearable fitness trackers, smart home gym equipment, or virtual fitness coaching services are in high demand as consumers increasingly invest in their health and wellness.</p><p><strong>Mental Health Apps</strong>: Mental health has become a priority for many people, and digital platforms offering therapy, stress management tips, and meditation sessions are growing now a days.</p><p><strong>Organic and Healthy Food</strong>: Consumers are turning toward organic, gluten-free, and plant-based options. Entrepreneurs can capitalize on this trend by offering meal kits, snack brands, or other health-focused food products</p><h3>Embrace the Digital Future</h3><p>The digital world offers incredible opportunities for entrepreneurs. By embracing technology, sustainability, and personalized experiences, you can create successful businesses that thrive in a competitive market and contribute to positive change in the society.</p><p>Those ready to innovate can lead the way!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4814c94746e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Difference between print() and return in Python]]></title>
            <link>https://medium.com/@savandikodithuwakku/difference-between-print-and-return-in-python-f1461b15aaa6?source=rss-509dfa0f76a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1461b15aaa6</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[coding-for-beginners]]></category>
            <category><![CDATA[print-function]]></category>
            <dc:creator><![CDATA[Savandi kodithuwakku]]></dc:creator>
            <pubDate>Mon, 27 May 2024 20:23:26 GMT</pubDate>
            <atom:updated>2024-05-27T23:19:15.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0bi42nS6FfeeMXWuPld_8w.png" /></figure><p><em>This article is for Python beginners. By reading this, you can understand the difference between ‘print()’ and ‘return’ in Python.</em></p><p>The main difference is that ‘print’ is a built-in function in Python, so we must write it as print(). On the other hand, ‘return’ is a keyword, not a function.</p><p>You can’t use the ‘return’ keyword outside of a function; it must be used within a function. However, you can use ‘print()’ inside a function, outside a function, or anywhere in your code.</p><p>When you use ‘print()’ , it writes the output to the console. In contrast, when you use ‘return’ , it sends the result to the caller or calling function. No output is printed through ‘return’ , so if you want to see the result, you need to assign it to a variable and then print that variable.</p><p>After a ‘return’ statement, the control immediately exits the function &amp; goes back to the calling function, and the code below the ‘return’ statement in the function does not execute. However, ‘print()’ does not affect the flow of the program; it simply executes respectively.</p><p>We can use ‘return’ to get a value from a function and assign it to a variable for further usage, such as performing calculations or passing arguments to another function. ‘print()’ is used solely for printing output to the console.</p><p>Let’s see this practically</p><pre>def function1():<br>    print(&#39;Hi&#39;)<br><br>def function2():<br>    return &#39;Hello&#39;<br><br>function1()     # Hi<br>function2()     </pre><p>In this example, when you call function1() , it prints &#39;Hi&#39; to the console. However, when you call function2() , it doesn&#39;t print anything because it returns &#39;Hello&#39; to the calling code, so function2()=‘Hello’. However, it&#39;s not visible to the user unless it printed.</p><p>To display the returned value, you need to assign it to a variable and then print that variable as below</p><pre>result1=function1()          #Hi<br>print(result1, &#39;python&#39;)     #None python<br>result2=function2()<br>print(result2, &#39;python&#39;)     #Hello python</pre><p>Let’s see what happens when we assign them to variables and print.</p><p>When function1() is called, there&#39;s nothing to return to the calling function. However, every function must return a value to the calling function. Since there&#39;s no such value, Python returns the ‘None’ keyword to the calling function. Therefore, result1= ‘None’. That&#39;s why it prints ‘None python’ here.</p><p>When function2() is called, it returns &#39;Hello&#39; to the calling function. So it doesn&#39;t send the ‘None’ keyword here. Therefore, result2= ‘Hello’. That’s why it prints ‘Hello python’ here.</p><p>And also using ‘return’ we can customize the output inside the print(). Rather than print ‘Hello’ we can return ‘Hello’ to the function and can make changes to that as shown above ‘Hello python’.</p><pre>print(function1(),&#39;world&#39;)        #Hi<br>                                  #None world<br>print(function2(),&#39;world&#39;)        #Hello world</pre><p>Let’s call above functions inside print() without assigning to variables. As explained above its also same, when you call function1(), it prints &#39;Hi&#39;. However, since function1() doesn&#39;t return anything, it returns ‘None’ to the caller. Thus, it prints &#39;None world&#39;.</p><p>On the other hand, function2() returns &#39;Hello&#39;, so it prints &#39;Hello world&#39;.</p><pre>def function1():<br>    print(&#39;Hi&#39;)                <br>    return &#39;I love coding&#39;<br>    print(&#39;coding is fun&#39;)<br><br>def function2():<br>    return &#39;Hello&#39;<br>    return &#39;I love coding&#39;<br>    print(&#39;coding is fun&#39;)<br><br>print(function1())   #Hi<br>                     #I love coding<br>print(function2())   #Hello</pre><p>In function1(), the print(‘Hi’) statement is executed first, printing &#39;Hi&#39; to the console. Then, it encounters the return ‘I love coding’ statement &amp; return that to calling function. Since ‘return’ immediately exits the function &amp; goes back to caller, though it prints ‘I love coding’ the subsequent line ‘coding is fun’ never executed.</p><p>In function2(), the return ‘Hello’ statement is executed first, returning &#39;Hello&#39; to the calling function. Similar to function1() , the subsequent lines after the return statement in the function are not executed.</p><p>That means, <strong>return affect the flow of the program while print() doesn’t affect.</strong></p><pre>def function1():<br>    return&#39;I love&#39;<br>    <br>def function2():<br>    x=100<br>    return x<br><br>def function3():<br>    print(function1(), &#39;python&#39;, function2(),&#39;%&#39;)<br><br>function3()           #I love python 100%</pre><p>In these cases, <strong>we must use ‘return’ when we need to pass a value to another function as argument or when we want to customize the output using print() as above or perform calculations</strong>. It’s better to use ‘return’ than print() for these purposes.</p><p><strong>In summary, understanding the difference between print() and return is crucial for writing effective Python code. Use return for further usage and use print to display output to the console.</strong></p><p><em>I hope you found this article helpful. Happy Coding!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1461b15aaa6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>