Spaces:
Sleeping
Sleeping
Download llm.py from Fsubhan786/AIEngineer: direct link, hf CLI and curl.
- Browser
- Download file 3.11 kB
-
https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/llm.py
- Command line
-
hf download hf://spaces/Fsubhan786/AIEngineer/llm.py
-
curl -L -o llm.py https://huggingface.co/spaces/Fsubhan786/AIEngineer/resolve/main/llm.py
3.11 kB
| """ | |
| 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 os | |
| import time | |
| from google import genai | |
| from google.genai import types | |
| from 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.")) | |