Friday, 16 May 2025

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!

No comments:

Post a Comment

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...