File size: 5,885 Bytes
3cb5f2b
ce5b5d6
3cb5f2b
 
 
 
 
ce5b5d6
3cb5f2b
 
ce5b5d6
 
 
3cb5f2b
3984583
3cb5f2b
 
ce5b5d6
 
3cb5f2b
 
 
 
 
 
 
ce5b5d6
3cb5f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce5b5d6
3cb5f2b
 
 
 
 
ce5b5d6
3cb5f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ce5b5d6
3cb5f2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
# app.py — FastAPI-only (no WebSockets/SSE)
import os
from typing import List, Optional, Tuple

from fastapi import FastAPI
from fastapi.responses import HTMLResponse, JSONResponse
from pydantic import BaseModel, Field
from openai import OpenAI

# --- Your prompts (edit these files in /prompts) ---
from prompts.initial_prompt import INITIAL_PROMPT
from prompts.main_prompt import MAIN_PROMPT

# Read key from Hugging Face Secret (Settings → Variables and secrets)
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
if not OPENAI_API_KEY:
    print("WARNING: OPENAI_API_KEY secret is not set. Set it in the Space settings.")
client = OpenAI(api_key=OPENAI_API_KEY)

# ---------- Models for API I/O ----------
class ChatIn(BaseModel):
    message: str = Field("", description="The latest user message.")
    # Optional: carry conversation history as a list of [user, assistant] turns
    history: Optional[List[Tuple[str, str]]] = Field(
        default=None,
        description="Optional history as list of (user, assistant) tuples."
    )
    model: str = Field(default="gpt-4o-mini")
    temperature: float = Field(default=0.7)
    top_p: float = Field(default=0.95)
    max_tokens: int = Field(default=600)

class ChatOut(BaseModel):
    reply: str

# ---------- Core non-streaming OpenAI call (server-side) ----------
def generate_reply(
    user_message: str,
    history: Optional[List[Tuple[str, str]]] = None,
    model: str = "gpt-4o-mini",
    temperature: float = 0.7,
    top_p: float = 0.95,
    max_tokens: int = 600,
) -> str:
    """
    Builds messages as:
      system: MAIN_PROMPT
      assistant: INITIAL_PROMPT (so users see your intro)
      ... then optional history [(user, assistant), ...]
      user: latest message
    """
    messages = [
        {"role": "system", "content": MAIN_PROMPT},
        {"role": "assistant", "content": INITIAL_PROMPT},
    ]

    if history:
        for u, a in history:
            if u:
                messages.append({"role": "user", "content": u})
            if a:
                messages.append({"role": "assistant", "content": a})

    messages.append({"role": "user", "content": user_message or ""})

    try:
        resp = client.chat.completions.create(
            model=model,
            messages=messages,
            temperature=temperature,
            top_p=top_p,
            max_tokens=max_tokens,
        )
        return resp.choices[0].message.content
    except Exception as e:
        # Return the error to the UI
        return f"Error: {e}"

# ---------- FastAPI app + routes ----------
app = FastAPI(title="Module Chat — Basic Mode")

@app.get("/health")
async def health():
    return {"status": "ok"}

@app.post("/api/chat", response_model=ChatOut)
async def api_chat(payload: ChatIn):
    reply = generate_reply(
        user_message=payload.message,
        history=payload.history,
        model=payload.model,
        temperature=payload.temperature,
        top_p=payload.top_p,
        max_tokens=payload.max_tokens,
    )
    return ChatOut(reply=reply)

# Single-page minimal UI that uses ONLY plain HTTPS (no WebSockets)
INDEX_HTML = f"""
<!doctype html>
<html>
<head>
  <meta charset="utf-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <title>Module Chat — Basic Mode</title>
  <style>
    :root {{ color-scheme: light dark; }}
    body {{ font-family: system-ui, Arial, sans-serif; max-width: 820px; margin: 24px auto; padding: 0 12px; }}
    textarea {{ width: 100%; height: 140px; }}
    #reply {{ white-space: pre-wrap; border: 1px solid #ddd; padding: 12px; border-radius: 10px; min-height: 120px; }}
    button {{ padding: 10px 16px; border-radius: 10px; cursor: pointer; }}
    .tip {{ color: #555; font-size: 0.95rem; }}
    .row {{ display: flex; gap: 8px; align-items: center; }}
    .row > * {{ flex: 1; }}
    .small {{ font-size: 12px; color: #666; }}
  </style>
</head>
<body>
  <h1>Module Chat — Basic Mode</h1>
  <p class="tip">
    This version uses only normal HTTPS requests (works even on strict campus Wi-Fi).<br/>
    <b>Assistant:</b> {INITIAL_PROMPT}
  </p>

  <textarea id="msg" placeholder="Type your message..."></textarea>
  <div class="row">
    <button id="send">Send</button>
    <label style="flex:0 0 auto">
      <input type="checkbox" id="keepHistory" checked /> keep history
    </label>
  </div>

  <h3>Reply</h3>
  <div id="reply"></div>

  <p class="small">Tip: Press Ctrl/Cmd+Enter to send.</p>

  <script>
    const btn = document.getElementById("send");
    const msg = document.getElementById("msg");
    const out = document.getElementById("reply");
    const keep = document.getElementById("keepHistory");
    let history = [];

    async function sendOnce() {{
      out.textContent = "Thinking...";
      const payload = {{
        message: msg.value || "",
        history: keep.checked ? history : null
      }};
      try {{
        const res = await fetch("/api/chat", {{
          method: "POST",
          headers: {{ "Content-Type": "application/json" }},
          body: JSON.stringify(payload)
        }});
        if (!res.ok) {{
          const txt = await res.text();
          out.textContent = "Server error: " + res.status + " " + txt;
          return;
        }}
        const data = await res.json();
        const reply = data.reply || "(no reply)";
        out.textContent = reply;
        if (keep.checked) {{
          history.push([msg.value || "", reply]);
        }}
      }} catch (e) {{
        out.textContent = "Network error: " + e;
      }}
    }}

    btn.onclick = sendOnce;
    msg.addEventListener("keydown", (ev) => {{
      if (ev.key === "Enter" && (ev.ctrlKey || ev.metaKey)) {{
        ev.preventDefault();
        sendOnce();
      }}
    }});
  </script>
</body>
</html>
"""

@app.get("/", response_class=HTMLResponse)
async def root():
    return INDEX_HTML