LANGCHAIN & LLAMAINDEX WITH GRADIO: 10 INTERACTIVE REAL-TIME RAG & AGENT EXAMPLES

Build production-grade AI agents, vector database retrievers, and RAG pipelines using LangChain and LlamaIndex integrated with Gradio web frontends. Test each example live below!

⚡ LangChain & LlamaIndex Orchestration in Gradio

LangChain and LlamaIndex provide powerful orchestration frameworks for building chains, agents, and document index retrievers. Pairing them with Gradio enables developers to deliver robust chat applications with memory, tool calling, and vector search.

Example 1: LangChain Conversational Chain with Gradio ChatInterface
Connects a LangChain ConversationalRetrievalChain directly into a Gradio chat interface with persistent memory.
Python (li_ex1.py)
import gradio as gr
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o", temperature=0.7)
memory = ConversationBufferMemory()
conversation = ConversationChain(llm=llm, memory=memory)

def langchain_chat(message, history):
    return conversation.predict(input=message)

demo = gr.ChatInterface(
    fn=langchain_chat,
    title="LangChain Memory-Enabled Chatbot"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LangChain Memory-Enabled Chatbot

Click 'Send to LangChain' to test conversational memory response.
Example 2: LlamaIndex Vector Store QA Query Engine
Builds a LlamaIndex vector store query engine over local documents and queries it via Gradio.
Python (li_ex2.py)
import gradio as gr
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

# Load documents and create index
documents = SimpleDirectoryReader("./docs").load_data()
index = VectorStoreIndex.from_documents(documents)
query_engine = index.as_query_engine()

def llamaindex_query(question):
    response = query_engine.query(question)
    return str(response)

demo = gr.Interface(
    fn=llamaindex_query,
    inputs=gr.Textbox(label="Ask Document Repository", value="What are the core modules of Nikita-Infotech?"),
    outputs=gr.Textbox(label="LlamaIndex Response", lines=4),
    title="LlamaIndex Document QA Engine"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LlamaIndex Document QA Engine

Click 'Query LlamaIndex' to retrieve grounded document answer.
Example 3: LangChain ReAct Agent with Custom Tools
Initializes a LangChain ReAct agent equipped with custom Python tools (calculator, database lookup).
Python (li_ex3.py)
import gradio as gr
from langchain.agents import initialize_agent, Tool, AgentType
from langchain_openai import ChatOpenAI

def search_database(query):
    return f"Database result for {query}: 1,420 registered visitors in Pune."

tools = [Tool(name="DB_Search", func=search_database, description="Search local database")]
llm = ChatOpenAI(model="gpt-4o", temperature=0)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)

def run_agent(prompt):
    return agent.run(prompt)

demo = gr.Interface(
    fn=run_agent,
    inputs=gr.Textbox(label="Agent Task Prompt", value="How many registered visitors are in Pune?"),
    outputs=gr.Textbox(label="Agent Thought & Final Answer", lines=5),
    title="LangChain ReAct Tool Agent"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LangChain ReAct Tool Agent

Click 'Run Agent' to execute ReAct tool reasoning loop.
Example 4: LlamaIndex Chat Engine with Memory
Creates an interactive LlamaIndex chat engine (`index.as_chat_engine()`) inside a Gradio ChatInterface.
Python (li_ex4.py)
import gradio as gr
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

index = VectorStoreIndex.from_documents(SimpleDirectoryReader("./data").load_data())
chat_engine = index.as_chat_engine(chat_mode="condense_plus_context")

def llamaindex_chat(message, history):
    response = chat_engine.chat(message)
    return str(response)

demo = gr.ChatInterface(
    fn=llamaindex_chat,
    title="LlamaIndex Stateful Chat Engine"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LlamaIndex Stateful Chat Engine

Click 'Send to Chat Engine' to test stateful context retrieval.
Example 5: LangChain Custom Prompt Template Selector
Allows users to test different LangChain PromptTemplate configurations dynamically with Gradio inputs.
Python (li_ex5.py)
import gradio as gr
from langchain.prompts import PromptTemplate
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(model="gpt-4o")

def run_prompt_template(topic, tone):
    template = "Write a {tone} explanation about {topic} for software developers."
    prompt = PromptTemplate(input_variables=["tone", "topic"], template=template)
    formatted = prompt.format(tone=tone, topic=topic)
    response = llm.invoke(formatted)
    return response.content

demo = gr.Interface(
    fn=run_prompt_template,
    inputs=[
        gr.Textbox(label="Topic", value="LangChain Expression Language (LCEL)"),
        gr.Dropdown(choices=["Professional", "Humorous", "Technical", "Concise"], value="Technical", label="Tone")
    ],
    outputs=gr.Textbox(label="Generated Response", lines=5),
    title="LangChain Prompt Template Studio"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LangChain Prompt Template Studio

Click 'Generate with LCEL' to execute prompt template.
Example 6: LlamaIndex Multi-Document Node Parser & Retriever
Demonstrates document chunking and node retrieval scores using LlamaIndex VectorStoreIndex.
Python (li_ex6.py)
import gradio as gr
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader

index = VectorStoreIndex.from_documents(SimpleDirectoryReader("./reports").load_data())
retriever = index.as_retriever(similarity_top_k=3)

def retrieve_nodes(query):
    nodes = retriever.retrieve(query)
    formatted = "\n\n".join([f"**Node Score:** {node.score:.4f}\n**Content:** {node.node.get_content()[:250]}..." for node in nodes])
    return formatted

demo = gr.Interface(
    fn=retrieve_nodes,
    inputs=gr.Textbox(label="Retrieval Query", value="Hostinger LAMP stack database configuration"),
    outputs=gr.Markdown(label="Top Retrieved Chunks"),
    title="LlamaIndex Node Retriever Inspector"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LlamaIndex Node Retriever Inspector

Click 'Retrieve Nodes' to view similarity scores and chunk previews.
Example 7: LangChain Structured Output Parser (`PydanticOutputParser`)
Enforces strict Pydantic JSON schemas on LLM outputs using LangChain output parsers.
Python (li_ex7.py)
import gradio as gr
from langchain.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI

class CourseInfo(BaseModel):
    course_name: str = Field(description="Title of the course")
    modules: int = Field(description="Total number of modules")
    technology: str = Field(description="Core programming language or framework")

parser = PydanticOutputParser(pydantic_object=CourseInfo)
llm = ChatOpenAI(model="gpt-4o", temperature=0)

def parse_course_data(prompt):
    format_instructions = parser.get_format_instructions()
    query = f"Extract course details from: '{prompt}'.\n{format_instructions}"
    result = llm.invoke(query)
    parsed = parser.parse(result.content)
    return f"✅ **Successfully Parsed JSON Schema:**\n```json\n{parsed.json(indent=2)}\n```"

demo = gr.Interface(
    fn=parse_course_data,
    inputs=gr.Textbox(label="Raw Input Text", value="Nikita-Infotech offers a comprehensive 12-module Python Data Science course."),
    outputs=gr.Markdown(label="Validated Pydantic JSON Output"),
    title="LangChain Structured Output Parser"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LangChain Structured Output Parser

Click 'Parse Structured Output' to validate schema JSON.
Example 8: LlamaIndex Web Page / HTML Scraper Data Loader
Loads online web pages using LlamaIndex SimpleWebPageReader and builds an instant RAG query engine.
Python (li_ex8.py)
import gradio as gr
from llama_index.readers.web import SimpleWebPageReader
from llama_index.core import VectorStoreIndex

def scrape_and_query(url, question):
    if not url or not question:
        return "Please provide both URL and question."
    documents = SimpleWebPageReader(html_to_text=True).load_data([url])
    index = VectorStoreIndex.from_documents(documents)
    engine = index.as_query_engine()
    return str(engine.query(question))

demo = gr.Interface(
    fn=scrape_and_query,
    inputs=[
        gr.Textbox(label="Target Web URL", value="https://nikita-infotech.com"),
        gr.Textbox(label="Question about Web Page", value="What services does Nikita-Infotech provide?")
    ],
    outputs=gr.Textbox(label="Scraped RAG Answer", lines=4),
    title="LlamaIndex Web Page RAG Scraper"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LlamaIndex Web Page RAG Scraper

Click 'Scrape & Query Web Page' to index URL and answer query.
Example 9: LangChain LCEL (LangChain Expression Language) Chain Streamer
Streams response tokens progressively using LangChain LCEL pipe syntax (`chain.stream()`) in Gradio.
Python (li_ex9.py)
import gradio as gr
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

prompt = ChatPromptTemplate.from_template("Write a detailed explanation of: {topic}")
model = ChatOpenAI(model="gpt-4o")
chain = prompt | model

def stream_lcel(topic):
    partial = ""
    for chunk in chain.stream({"topic": topic}):
        if chunk.content:
            partial += chunk.content
            yield partial

demo = gr.Interface(
    fn=stream_lcel,
    inputs=gr.Textbox(label="Topic", value="Agentic AI Workflows"),
    outputs=gr.Textbox(label="Streamed LCEL Output", lines=5),
    title="LangChain LCEL Streaming Chain"
)

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

### LangChain LCEL Streaming Chain

Click 'Stream LCEL Chain' to test token streaming.
Example 10: Enterprise LangChain & LlamaIndex Operations Hub (`gr.Blocks`)
Combines vector indexing, agentic tool execution, and memory chat into an enterprise dashboard using gr.Blocks.
Python (li_ex10.py)
import gradio as gr

with gr.Blocks() as demo:
    gr.Markdown("# 🚀 Enterprise LangChain & LlamaIndex Operations Hub")
    
    with gr.Row():
        status_panel = gr.Textbox(label="Framework Status", value="LangChain v0.3 & LlamaIndex v0.11 Active 🟢")
        db_panel = gr.Textbox(label="Vector Store Status", value="ChromaDB Connected | 1,450 Embeddings Indexed")
        
    gr.ChatInterface(
        fn=lambda msg, hist: f"Enterprise Orchestration Agent Response: Processed '{msg}' via LangChain RAG pipeline.",
        title="Enterprise AI Agent Session"
    )

if __name__ == "__main__":
    demo.launch()
🖥️ Live Interactive Web UI Simulator

# 🚀 Enterprise LangChain & LlamaIndex Operations Hub

Status: LangChain v0.3 Active 🟢
Vector Store: ChromaDB Connected
[Interactive Enterprise ChatInterface Box Ready]