Python / Python Modern Generative AI and Agents Interview Questions
How do you build a demo web interface for an LLM application using Gradio?
Gradio is Hugging Face's rapid UI library for building interactive machine learning demos with a few lines of Python. It runs locally or deploys instantly to Hugging Face Spaces. For LLM applications, gr.ChatInterface provides a fully featured chat UI out of the box, while gr.Interface handles simpler input-output demos.
# pip install gradio
import gradio as gr
from openai import OpenAI
client = OpenAI()
# ── ChatInterface: streaming chat with history
def predict(message: str, history: list) -> str:
# Convert Gradio history format to OpenAI messages
messages = [{'role': 'system', 'content': 'You are a helpful assistant.'}]
for user_msg, ai_msg in history:
messages.append({'role': 'user', 'content': user_msg})
messages.append({'role': 'assistant', 'content': ai_msg})
messages.append({'role': 'user', 'content': message})
# Stream response
stream = client.chat.completions.create(
model='gpt-4o-mini', messages=messages, stream=True
)
partial = ''
for chunk in stream:
if chunk.choices[0].delta.content:
partial += chunk.choices[0].delta.content
yield partial # Gradio supports generator streaming!
demo = gr.ChatInterface(
fn=predict,
title='My AI Assistant',
description='Ask me anything!',
examples=['What is RAG?', 'Explain transformers in one sentence.'],
)
demo.launch(server_name='0.0.0.0', server_port=7860)
# ── Interface: simple input-output for non-chat tasks
from transformers import pipeline
classifier = pipeline('text-classification')
def classify(text):
result = classifier(text)[0]
return f"{result['label']} ({result['score']:.2%})"
gr.Interface(
fn=classify,
inputs=gr.Textbox(label='Enter text'),
outputs=gr.Text(label='Sentiment'),
title='Sentiment Classifier',
).launch()
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
