Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| from google import genai | |
| st.title("Chat con Gemini") | |
| # API key desde la interfaz | |
| api_key = st.text_input("Gemini API Key", type="password") | |
| if "history" not in st.session_state: | |
| st.session_state.history = [] | |
| # Mostrar historial | |
| for message in st.session_state.history: | |
| role = "assistant" if message["role"] == "model" else "user" | |
| st.chat_message(role).write(message["parts"][0]["text"]) | |
| prompt = st.chat_input("Escribe tu mensaje") | |
| if prompt: | |
| if not api_key: | |
| st.warning("Debes ingresar tu API key.") | |
| st.stop() | |
| # Crear cliente en cada ejecución | |
| client = genai.Client(api_key=api_key) | |
| # Agregar mensaje del usuario en formato correcto | |
| st.session_state.history.append({ | |
| "role": "user", | |
| "parts": [{"text": prompt}] | |
| }) | |
| # Crear chat con historial válido | |
| chat = client.chats.create( | |
| model="gemini-1.5-flash", | |
| history=st.session_state.history | |
| ) | |
| response = chat.send_message(prompt) | |
| # Guardar respuesta del modelo correctamente | |
| st.session_state.history.append({ | |
| "role": "model", | |
| "parts": [{"text": response.text}] | |
| }) | |
| st.chat_message("assistant").write(response.text) | |