Spaces:
Sleeping
Sleeping
Upload 3 files
Browse filesFiles changed (3)
- app.pyAdded+59
- llm.pyAdded+94
- requirements.txtAdded+6
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859"""app.py — a streaming chatbot UI with Gradio. Deploys free to Hugging Face Spaces.Run locally: python app.py → open the printed local URL."""import gradio as grfrom llm import stream_chat, trim_history, DEFAULT_SYSTEM
def respond(user_message, chat_history, system_prompt, temperature): # Convert Gradio's [{"role": ..., "content": ...}, ...] history to Gemini. chat_history = chat_history or [] gemini_history = [] for message in chat_history: role = message.get("role") content = message.get("content") if not content: continue if role == "user": gemini_history.append({"role": "user", "parts": [content]}) elif role == "assistant": gemini_history.append({"role": "model", "parts": [content]}) gemini_history = trim_history(gemini_history)
chat_history = chat_history + [ {"role": "user", "content": user_message}, {"role": "assistant", "content": ""}, ] partial = "" try: for piece in stream_chat(gemini_history, user_message, system_prompt=system_prompt or DEFAULT_SYSTEM, temperature=temperature): partial += piece chat_history[-1]["content"] = partial yield chat_history, "" except Exception as e: chat_history[-1]["content"] = f"(error: {e}). Please try again." yield chat_history, ""
with gr.Blocks(title="AI Engineer — Project 1 Chatbot") as demo: gr.Markdown("# Streaming Chatbot\nBuilt on Google Gemini (free API). Project 1 of 4.") with gr.Row(): with gr.Column(scale=3): chatbot = gr.Chatbot(height=420, label="Conversation") msg = gr.Textbox(placeholder="Ask anything…", label="Your message") with gr.Row(): send = gr.Button("Send", variant="primary") clear = gr.Button("Clear") with gr.Column(scale=1): system = gr.Textbox(value=DEFAULT_SYSTEM, lines=4, label="System prompt") temp = gr.Slider(0.0, 1.0, value=0.3, step=0.1, label="Temperature")
send.click(respond, [msg, chatbot, system, temp], [chatbot, msg]) msg.submit(respond, [msg, chatbot, system, temp], [chatbot, msg]) clear.click(lambda: ([], ""), None, [chatbot, msg])
if __name__ == "__main__": demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394"""llm.py - a tiny, provider-agnostic LLM client for the chatbot.Uses Google Gemini's FREE API (get a key at https://aistudio.google.com/apikey)."""import osimport timefrom google import genaifrom google.genai import typesfrom dotenv import find_dotenv, load_dotenv
load_dotenv(find_dotenv())
MODEL_NAME = os.environ.get("GEMINI_MODEL", "gemini-2.5-flash")DEFAULT_SYSTEM = "You are a concise, helpful assistant. Answer clearly and briefly."
def _client(): """Create a Gemini API client using GEMINI_API_KEY from .env.""" api_key = os.environ.get("GEMINI_API_KEY") if not api_key or api_key == "your_gemini_api_key_here": raise RuntimeError("Set GEMINI_API_KEY in the repository .env file first.") return genai.Client(api_key=api_key)
def _content_history(history): """Convert simple role/parts dicts into google-genai Content objects.""" contents = [] for item in history: parts = [] for part in item.get("parts", []): if isinstance(part, str): parts.append(types.Part.from_text(text=part)) elif isinstance(part, dict) and "text" in part: parts.append(types.Part.from_text(text=part["text"])) if parts: contents.append(types.Content(role=item["role"], parts=parts)) return contents
def _config(system_prompt: str, temperature: float): return types.GenerateContentConfig( system_instruction=system_prompt, temperature=temperature, )
def chat(history, user_message, system_prompt=DEFAULT_SYSTEM, temperature=0.3, max_retries=4): """ Send one turn and return the full reply text. `history` is a list of {"role": "user"|"model", "parts": [text]} dicts. Includes exponential-backoff retry on transient errors. """ client = _client() convo = client.chats.create( model=MODEL_NAME, history=_content_history(history), config=_config(system_prompt, temperature), ) delay = 1.0 for attempt in range(max_retries): try: resp = convo.send_message(user_message) return resp.text except Exception: if attempt == max_retries - 1: raise time.sleep(delay) delay *= 2 return ""
def stream_chat(history, user_message, system_prompt=DEFAULT_SYSTEM, temperature=0.3): """Yield reply chunks as they arrive, for a responsive UI.""" client = _client() convo = client.chats.create( model=MODEL_NAME, history=_content_history(history), config=_config(system_prompt, temperature), ) for chunk in convo.send_message_stream(user_message): if chunk.text: yield chunk.text
def trim_history(history, max_turns=20): """Keep the most recent `max_turns` turns to stay within the context window.""" return history[-max_turns * 2:] if len(history) > max_turns * 2 else history
if __name__ == "__main__": # Smoke test: one question, printed. print(chat([], "Explain what an API key is in two sentences."))123456google-genaigradiopython-dotenv
# optional Anthropic path:anthropicapp.pyAdded+59
llm.pyAdded+94
requirements.txtAdded+6