Spaces:
Sleeping

File size: 3,113 Bytes
73fe831
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""
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."))