Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435362 unmodified linesfrom getpass import getpassfrom openai import OpenAIimport gradio as gr# βββ Configure your OpenRouter key βββif "OPENROUTER_API_KEY" not in os.environ or not os.environ["OPENROUTER_API_KEY"]:os.environ["OPENROUTER_API_KEY"] = getpass("π Enter your OpenRouter API key: ")client = OpenAI(base_url="https://openrouter.ai/api/v1",api_key=os.environ["OPENROUTER_API_KEY"],)#mistralai/Devstral-Small-2505def openrouter_chat(user_message, history):"""Send user_message to mistralai/devstral-small:free and append to history."""# build the messages listmsgs = [{"role": "user", "content": user_message}]# call the modelresp = client.chat.completions.create(model="mistralai/devstral-small:free",messages=msgs,# you can tweak max_tokens, temperature, etc. here)bot_reply = resp.choices[0].message.contenthistory = history or []history.append((user_message, bot_reply))return history, ""with gr.Blocks() as demo:gr.Markdown("## π¦π Gradio + OpenRouter Chat with Devstral-Small")chatbot = gr.Chatbot(label="Chat")msg_in = gr.Textbox(placeholder="Type your question hereβ¦", label="You")msg_in.submit(openrouter_chat, inputs=[msg_in, chatbot], outputs=[chatbot, msg_in])demo.launch()2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162632 unmodified linesfrom getpass import getpassfrom openai import OpenAIimport gradio as grfrom google.colab import userdata# βββ Configure your OpenRouter key βββ# Assuming OPENROUTER_API_KEY is already set in the environment or Colab secrets# Retrieve the API key from Colab secretsapi_key=OPENROUTER_API_KEY# Check if the API key was retrievedif not OPENROUTER_API_KEY:print("Error: OPENROUTER_API_KEY not found in Colab secrets.")print("Please add your API key to Colab secrets by clicking on the key icon in the left panel and naming it OPENROUTER_API_KEY.")else:client = OpenAI(base_url="https://openrouter.ai/api/v1",api_key=OPENROUTER_API_KEY,)def openrouter_chat(user_message, history):"""Send user_message and history to mistralai/devstral-small:free and append to history."""history = history or []# Build the messages list from the history and the current user message# Gradio history is a list of tuples [(user_msg, bot_msg), ...]# We need to convert it to the OpenAI API format: list of dicts [{"role": "user", "content": ...}, {"role": "assistant", "content": ...}, ...]messages_for_api = []for human_message, ai_message in history:messages_for_api.append({"role": "user", "content": human_message})if ai_message is not None: # Only add assistant message if it existsmessages_for_api.append({"role": "assistant", "content": ai_message})# Add the current user messagemessages_for_api.append({"role": "user", "content": user_message})try:# Call the model with the full conversation historyresp = client.chat.completions.create(model="mistralai/devstral-small:free",messages=messages_for_api,# you can tweak max_tokens, temperature, etc. here)bot_reply = resp.choices[0].message.content# Append the user message and bot reply to the history for Gradio displayhistory.append((user_message, bot_reply))except Exception as e:# Handle potential errors and append an error message to the historyhistory.append((user_message, f"Error: {e}"))return history, ""with gr.Blocks() as demo:gr.Markdown("## π¦π Gradio + OpenRouter Chat with Devstral-Small (with History)")chatbot = gr.Chatbot(label="Chat")msg_in = gr.Textbox(placeholder="Type your question hereβ¦", label="You")msg_in.submit(openrouter_chat, inputs=[msg_in, chatbot], outputs=[chatbot, msg_in])demo.launch()
app.py+55-28