Spaces:
Sleeping
Sleeping
Download app.py from keefereuther/CI_tab2: direct link, hf CLI and curl.
- Browser
- Download file 4.5 kB
-
https://huggingface.co/spaces/keefereuther/CI_tab2/resolve/main/app.py
- Command line
-
hf download hf://spaces/keefereuther/CI_tab2/app.py
-
curl -L -o app.py https://huggingface.co/spaces/keefereuther/CI_tab2/resolve/main/app.py
4.5 kB
| import os | |
| import gradio as gr | |
| import litellm | |
| from dotenv import load_dotenv | |
| import config | |
| load_dotenv() | |
| def _resolve_openai_base() -> str: | |
| raw = (os.environ.get("OPENAI_API_BASE") or os.environ.get("OPENAI_BASE_URL") or "").strip() | |
| if not raw: | |
| return "" | |
| base = raw.rstrip("/") | |
| if not base.endswith("/v1"): | |
| base += "/v1" | |
| return base | |
| OPENAI_BASE = _resolve_openai_base() | |
| if OPENAI_BASE: | |
| os.environ["OPENAI_API_BASE"] = OPENAI_BASE | |
| MODEL_NAME = config.ai_model | |
| try: | |
| _supported = set(litellm.get_supported_openai_params(model=MODEL_NAME) or []) | |
| except Exception: | |
| _supported = {"max_tokens", "temperature", "frequency_penalty", "presence_penalty"} | |
| _wanted = { | |
| "temperature": config.temperature, | |
| "max_tokens": config.max_tokens, | |
| "frequency_penalty": config.frequency_penalty, | |
| "presence_penalty": config.presence_penalty, | |
| } | |
| GEN_PARAMS = {k: v for k, v in _wanted.items() if v is not None and k in _supported} | |
| _skipped = [k for k, v in _wanted.items() if v is not None and k not in _supported] | |
| print( | |
| f"[config] MODEL_NAME={MODEL_NAME} | OPENAI_API_BASE={OPENAI_BASE or '(unset)'} | " | |
| f"OPENAI_API_KEY set={bool(os.environ.get('OPENAI_API_KEY'))} | " | |
| f"gen_params={GEN_PARAMS} | skipped_unsupported={_skipped}" | |
| ) | |
| if MODEL_NAME.startswith("openai/") and not OPENAI_BASE: | |
| print( | |
| "[config] WARNING: no OPENAI_API_BASE is set, but the model is " | |
| f"'{MODEL_NAME}'. Requests will go to api.openai.com unless the endpoint is configured." | |
| ) | |
| def _build_completion_kwargs() -> dict: | |
| completion_kwargs = {} | |
| if MODEL_NAME.startswith("openai/") and OPENAI_BASE: | |
| completion_kwargs["api_base"] = OPENAI_BASE | |
| completion_kwargs["api_key"] = os.environ.get("OPENAI_API_KEY") | |
| completion_kwargs.update(GEN_PARAMS) | |
| return completion_kwargs | |
| def _opening_history(): | |
| return [{"role": "assistant", "content": config.opening_message}] | |
| def predict(message, history): | |
| messages = [{"role": "system", "content": config.prompt}] | |
| for msg in history: | |
| if isinstance(msg.get("content"), str): | |
| messages.append({"role": msg["role"], "content": msg["content"]}) | |
| messages.append({"role": "user", "content": message}) | |
| partial_message = "" | |
| completion_kwargs = _build_completion_kwargs() | |
| try: | |
| response = litellm.completion( | |
| model=MODEL_NAME, | |
| messages=messages, | |
| stream=True, | |
| **completion_kwargs, | |
| ) | |
| for chunk in response: | |
| if not chunk.choices: | |
| continue | |
| delta = chunk.choices[0].delta.content | |
| if delta: | |
| partial_message += delta | |
| yield partial_message | |
| except Exception as e: | |
| yield ( | |
| f"**An error occurred:** {e}\n\n" | |
| "*Check your API keys, OPENAI_API_BASE, and model name in config.py.*" | |
| ) | |
| def verify_login(username, password): | |
| users_env = os.environ.get("ALLOWED_USERS", "") | |
| if not users_env: | |
| return False | |
| try: | |
| valid_users = dict(pair.split(":", 1) for pair in users_env.split(",")) | |
| except ValueError: | |
| return False | |
| return valid_users.get(username) == password | |
| with gr.Blocks(fill_height=True) as demo: | |
| with gr.Sidebar(open=False): | |
| gr.Markdown(config.warning_message) | |
| gr.Markdown("---") | |
| gr.Markdown( | |
| "<small>Licensed under " | |
| '<a href="https://www.gnu.org/licenses/gpl-3.0.en.html">GNU GPL v3.0</a></small>' | |
| ) | |
| chatbot = gr.Chatbot( | |
| value=_opening_history(), | |
| height="100%", | |
| ) | |
| chatbot.clear(fn=lambda: _opening_history(), outputs=chatbot) | |
| gr.ChatInterface( | |
| fn=predict, | |
| chatbot=chatbot, | |
| textbox=gr.Textbox( | |
| placeholder="Type your message here...", | |
| lines=1, | |
| scale=7, | |
| ), | |
| fill_height=True, | |
| ) | |
| if __name__ == "__main__": | |
| _i18n = gr.I18n( | |
| en={ | |
| "login": { | |
| "login": "Log in", | |
| "username": "Username", | |
| "password": "Password", | |
| "incorrect_credentials": "Incorrect username or password.", | |
| "enable_cookies": ( | |
| "If you are visiting a HuggingFace Space in Incognito mode, " | |
| "you must enable third party cookies." | |
| ), | |
| }, | |
| }, | |
| ) | |
| demo.launch(auth=verify_login, i18n=_i18n) | |