Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738import subprocessimport osimport timeimport gradio as grimport ollama# --- 1. Setup Ollama ---def setup_ollama():# Install zstd (required for extraction)subprocess.run("apt-get update && apt-get install -y zstd", shell=True, check=True)# Download and install Ollamasubprocess.run("curl -fsSL https://ollama.com/install.sh | sh", shell=True, check=True)# Start Ollama server in the backgroundsubprocess.Popen(["ollama", "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)# Wait for server to starttime.sleep(5)# Pull the modelsubprocess.run(["ollama", "pull", "llama3"], check=True)setup_ollama()# --- 2. Define Chat Function ---def chat_with_llm(message, history):response = ollama.chat(model='llama3', messages=[{'role': 'user', 'content': message}])return response['message']['content']# --- 3. Launch Gradio Interface ---demo = gr.ChatInterface(fn=chat_with_llm,title="My Ollama Chatbot",description="Chat with a local LLM powered by Ollama!",)demo.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import subprocessimport timeimport gradio as grimport anthropic# --- 1. Setup Ollama ---def setup_ollama():# Install zstd (required)subprocess.run("apt-get update && apt-get install -y zstd", shell=True, check=True)# Install Ollamasubprocess.run("curl -fsSL https://ollama.com/install.sh | sh", shell=True, check=True)# Start Ollama serversubprocess.Popen(["ollama", "serve"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)# Wait for servertime.sleep(5)# Pull your model (change if needed)subprocess.run(["ollama", "pull", "qwen3:0.6b"], check=True)# Run setupsetup_ollama()# --- 2. Connect via Anthropic-compatible API ---client = anthropic.Anthropic(base_url="http://localhost:11434", # π Ollama endpointapi_key="ollama" # π dummy key required)# --- 3. Streaming Chat Function ---def chat_with_llm(message, history):messages = []# Preserve conversation historyfor user_msg, bot_msg in history:messages.append({"role": "user", "content": user_msg})messages.append({"role": "assistant", "content": bot_msg})messages.append({"role": "user", "content": message})# Start streaming from Ollama via Anthropic SDKstream = client.messages.stream(model="qwen3:0.6b", # π must match Ollama model namemessages=messages)partial_response = ""for event in stream:if event.type == "content_block_delta":delta = event.delta.textpartial_response += deltayield partial_response # π₯ streaming output# --- 4. Gradio Interface ---demo = gr.ChatInterface(fn=chat_with_llm,title="Ollama + Anthropic Streaming Chatbot",description="Local LLM with streaming via Anthropic-compatible API",)demo.launch()
app.py+40-15