Friday, 16 May 2025

Agentic AI: A Progression of Language Model Usage



๐Ÿง  Agentic AI: A Progression of Language Model Usage















As large language models (LLMs) like GPT-4 and Claude revolutionize how we generate text, a new frontier is emerging: Agentic AI. This tutorial explores what Agentic AI means, why it matters, and how to build with it—step by step.


๐Ÿ” What Is Agentic AI?

Traditional LLMs operate in a stateless, input-output mode: you ask, they answer. Agentic AI takes this further by allowing the model to:

  • Reason through complex tasks

  • Act by calling tools, APIs, or searching documents

  • Plan its actions over multiple steps

  • Reflect on and improve its own outputs

In short, an agentic system isn't just a chatbot—it's an autonomous assistant that can think, decide, and interact with its environment.


๐Ÿงช Getting Started: LLM vs. Agentic LLM

Basic LLM Prompt (Traditional):

Q: What's the capital of France?
A: Paris

Agentic Prompt (With Tool Use):

{
  "function_call": {
    "name": "get_weather",
    "parameters": {
      "location": "San Francisco"
    }
  }
}

Here, instead of directly answering a query it doesn’t know (real-time weather), the model generates a function call that your software can interpret, execute via an API, and return results to the LLM for a complete answer.


๐Ÿ› ️ Core Components of Agentic AI

1. Reasoning with Chain-of-Thought

Break down complex tasks into smaller steps.

Example Prompt:

Question: Is 9 a prime number?
Let's think step by step.

Model Output:

- 9 is greater than 1.
- It has divisors other than 1 and itself (3).
- Therefore, 9 is not a prime number.

2. Retrieval-Augmented Generation (RAG)

Use your own documents to ground model responses.

Example Setup:

  • Chunk internal policies into small text blocks

  • Store in a vector database (e.g., ChromaDB or Pinecone)

  • On query: search for relevant chunks and insert them into the prompt

Prompt Template:

Answer the question using the following company policy:
[Retrieved Text]

Q: Can I get a refund for a used product?

3. Reflection for Quality Improvement

Have the model critique and refine its own output.

Step 1: Ask for critique

Here is the code snippet. Provide constructive feedback:
[Code]

Step 2: Ask to refactor

Based on this feedback, refactor the code to improve it.

4. Multi-Agent Collaboration

Assign different tasks to specialized agents (personas).

Example: Smart Home Agents

  • ClimateAgent: controls temperature

  • LightingAgent: handles lights

  • SecurityAgent: monitors doors

Each has its own prompt and logic. They communicate via a coordinator agent or software scaffold.


๐Ÿ” Full Workflow Example: Customer Support Agent

User: Can I get a refund for product X?

Agentic Flow:

  1. Plan:

    • Check refund policy

    • Retrieve customer order

    • Validate product eligibility

  2. Act:

    • Query vector DB for policy

    • Call internal API for customer info

    • Confirm refund criteria

  3. Respond:

    • Draft and send a personalized message


✅ Best Practices

  • Start with simple prompts in a playground (OpenAI, Anthropic, etc.)

  • Use clear, contextual instructions

  • Log all outputs and evaluate them regularly

  • Use LLMs as “judges” or evaluators with structured templates

  • Add tool usage, memory, and planning as your app matures


๐Ÿš€ Conclusion: Why Agentic AI Matters

Agentic AI represents the future of intelligent automation. It transforms LLMs from passive responders into active participants—able to reason, research, act, and adapt. Whether you’re building customer support agents, smart assistants, or research bots, agentic design patterns give you a blueprint for doing more with LLMs.


Let me know if you'd like this as a polished blog draft with visuals, or adapted for Medium, LinkedIn, or your website format.

Credits : 

www.youtube.com/@stanfordonline


Agentic AI in Action: A Python Tutorial for LLM Reasoning and Tool Use



๐Ÿง  Agentic AI in Action: A Python Tutorial for LLM Reasoning and Tool Use

Agentic AI moves beyond static question-answering by enabling models to reason, plan, and take action. In this tutorial, you'll learn how to implement Agentic AI features using Python and the OpenAI API, including tool use, reflection, and retrieval-augmented generation.


๐Ÿš€ 1. Setup

✅ Install Requirements

pip install openai faiss-cpu langchain

๐Ÿ” Set Your API Key

import openai
openai.api_key = "your-api-key"

๐Ÿ“˜ 2. Basic LLM Call (Traditional Use)

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[{"role": "user", "content": "What is the capital of Japan?"}]
)

print(response['choices'][0]['message']['content'])

๐Ÿ› ️ 3. Tool Usage (Function Calling)

Let’s simulate an agent that calls a tool to get weather info.

๐Ÿงฉ Define the Function

import json

def get_weather(location):
    # Simulated API response
    return f"The weather in {location} is sunny and 25°C."

๐Ÿ”ง Define Function Schema

functions = [
    {
        "name": "get_weather",
        "description": "Get weather for a given location",
        "parameters": {
            "type": "object",
            "properties": {
                "location": {"type": "string", "description": "City name"}
            },
            "required": ["location"]
        }
    }
]

๐Ÿง  Call LLM and Handle Function Call

user_query = "What's the weather in San Francisco?"

response = openai.ChatCompletion.create(
    model="gpt-4-0613",
    messages=[{"role": "user", "content": user_query}],
    functions=functions,
    function_call="auto"
)

message = response["choices"][0]["message"]

if "function_call" in message:
    fn_name = message["function_call"]["name"]
    args = json.loads(message["function_call"]["arguments"])
    
    if fn_name == "get_weather":
        tool_result = get_weather(args["location"])
        
        # Send the result back to LLM for final response
        followup = openai.ChatCompletion.create(
            model="gpt-4-0613",
            messages=[
                {"role": "user", "content": user_query},
                message,
                {"role": "function", "name": fn_name, "content": tool_result}
            ]
        )
        print(followup['choices'][0]['message']['content'])

๐Ÿง  4. Chain of Thought (Reasoning)

Ask the model to break down its reasoning:

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "user", "content": "Is 87 a prime number? Let's think step by step."}
    ]
)

print(response['choices'][0]['message']['content'])

๐Ÿ” 5. Reflection for Output Improvement

Step 1: Ask for Feedback

code = """
def add_numbers(a, b):
    return a - b
"""

feedback = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "user", "content": f"Here is some Python code:\n{code}\nPlease provide constructive feedback."}
    ]
)

critique = feedback['choices'][0]['message']['content']
print("Feedback:\n", critique)

Step 2: Refactor Based on Feedback

refactor = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "user", "content": f"Here is the code:\n{code}\nHere is the feedback:\n{critique}\nPlease refactor the code accordingly."}
    ]
)

print("Refactored Code:\n", refactor['choices'][0]['message']['content'])

๐Ÿ“š 6. Retrieval-Augmented Generation (Mini RAG with FAISS)

Prepare a Simple Vector Search Using FAISS

from langchain.vectorstores import FAISS
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.docstore.document import Document

# Sample data
texts = [
    "Our refund policy allows returns within 30 days of purchase.",
    "Shipping times vary by location, typically 3–5 business days.",
    "Support is available 24/7 via chat and email."
]

docs = [Document(page_content=text) for text in texts]

# Split and embed
splitter = CharacterTextSplitter(chunk_size=100, chunk_overlap=10)
chunks = splitter.split_documents(docs)

embedding_model = OpenAIEmbeddings()
db = FAISS.from_documents(chunks, embedding_model)

# Query
query = "Can I return my order after 3 weeks?"
results = db.similarity_search(query, k=1)

context = results[0].page_content
print("Retrieved context:\n", context)

Combine with LLM Prompt

response = openai.ChatCompletion.create(
    model="gpt-4",
    messages=[
        {"role": "system", "content": "Use the context to answer accurately."},
        {"role": "user", "content": f"Context: {context}\n\nQuestion: {query}"}
    ]
)

print("Answer:\n", response['choices'][0]['message']['content'])

๐Ÿง  Final Thoughts

Agentic AI in Python enables LLMs to:

  • Reason using chain-of-thought

  • Interact with external tools (function calling)

  • Use reflection for output improvement

  • Access private knowledge via retrieval

By combining these patterns, you can build intelligent, reliable assistants that go beyond Q&A.


Let me know if you'd like this exported as a Jupyter Notebook, blog-ready markdown, or demo project repo!

AI and Industrial IOT Solution

In this blog article we will discuss Industrial  IOT Solution Architecture and how AI can help achieve huge prodictivity. 1. Master Data Syn...