import base64 import json import re from pathlib import Path import gradio as gr from chat import ( HY_CHAT_INITIAL_HTML, api_chat, init_state, new_chat, send_message, submit_tool_result, ) from i18n import LANG, t from tools import validate_functions_json from styles import CSS _STATIC_DIR = Path(__file__).parent / "static" _VENDOR_DIR = _STATIC_DIR / "vendor" _FN_PLACEHOLDER = json.dumps([{ "type": "function", "function": { "name": "get_weather", "description": "Get weather info for a city", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City name"} }, "required": ["location"] } } }], indent=2, ensure_ascii=False) _EXTRACT_NAMES_PROMPT = """You are a text information extraction expert with exceptional abilities in information filtering and structured processing. Your core task is to accurately capture key information from the raw text provided by the user and output the result according to the required format, ensuring informational purity and logical consistency. Initial settings: 1. All extracted information must strictly come from the text provided by the user. 2. If the user's request requires extracting uncertainty-related words such as "possible" or "speculative," you must extract them as requested. Otherwise, you must not output uncertainty-related words such as "possible" or "speculative." 3. You must strictly follow the output format below and must not include any content outside the required format. The output format is: "Extracted content: xxx". Here, "xxx" is a placeholder. Please help me extract all personal names from the text in order. Note that you do not need to remove duplicates. Text: In a warm and harmonious extended family, four elders—father, mother, grandfather, and grandmother—have always quietly watched over the family, supporting the whole household with love and tolerance. Meanwhile, six younger family members—Emily Carter, Olivia Brooks, Ethan Miller, Sophie Taylor, Grace Wilson, and Daniel Harris—are each growing along their own paths in life. The family supports one another and keeps each other company, making ordinary days feel warm and fulfilling. Father is hardworking and steady, carrying the family's responsibilities with strength. Mother is gentle and attentive, taking care of every detail of daily life. Grandfather is experienced and often tells the children stories from the past. Grandmother is kind and loving, warming everyone who returns home with hot meals. Emily Carter is sensible and motivated, setting a good example for her younger siblings. Olivia Brooks is lively and cheerful, always bringing laughter to the home. Ethan Miller is dependable and practical, taking every task seriously without being careless. Sophie Taylor is gentle and considerate, skilled at caring for the people around her. Grace Wilson loves life and is attentive to the beauty around her. Daniel Harris is energetic and full of expectations for the future. These ten family members each have their own traits and strengths, yet they share the same care and affection for one another. Together, they share joy, ease worries, pass through spring, summer, autumn, and winter, and move through the years side by side. Through family love, they gather the strongest support, making home the safest and warmest harbor, and making ordinary life full of happiness and light because of each other's companionship.""" _CHONGQING_TRIP_PROMPT = """You are an experienced local tour guide in Chongqing. Based on the attraction information and the users' situation, you need to generate a travel summary arranged by travel date. You must not output anything else. The travel summary format is as follows: Date/Location/Ticket MM-dd/Travel location/Ticket price MM-dd/Travel location/Ticket price ...... For the Travel location field, choose exactly one from the following six options: Hongya Cave, Chaotianmen, Jiefangbei, Qiansimen, Shapingba, Jiangbeizui. Opening hours: Hongya Cave: 9:00–11:00 Chaotianmen: 9:00–11:00 Jiefangbei: 15:00–17:00 Qiansimen: 11:00–13:00 Shapingba: 12:00–14:00 Jiangbeizui: 16:00–18:00 Ticket prices: Hongya Cave: CNY 20 per person Chaotianmen: CNY 60 per person Jiefangbei: CNY 30 per person Qiansimen: CNY 50 per person Shapingba: CNY 60 per person Jiangbeizui: CNY 50 per person Alex: My friend Ben and I came to Chongqing on March 15 for a trip. For every attraction we visit, we must stay from opening time until closing time. We brought a total of CNY 300. On the first day, we visited two attractions. Ben: Although we had a great time on the first day, after the day's trip ended, I realized that I had lost CNY 200. So we did not plan to visit any attractions on the second day. Alex: Losing the money was really stressful for us. However, after 12:00 on the second day, our parents sent us another CNY 200, so we went to visit one attraction that afternoon. Ben: We were too tired from the first two days, so on the final day we visited only one attraction. None of the attractions we visited were repeated.""" _RATIONAL_VARIETY_PROMPT = r"""Let \(K\) be an algebraically closed field and \(X\) the hypersurface in \(\mathbf{P}_{K}^{3}\) defined by the homogeneous equation \[ x^{2} w-y^{2} z=0 \] where \((x, y, z, w)\) are homogeneous coordinates on \(\mathbf{P}_{K}^{3}\). Prove that \(X\) is a rational variety, i.e., its function field is \(K\left(t_{1}, t_{2}\right)\), where \(t_{1}, t_{2}\) are algebraically independent over \(K\).""" _FISH_PUZZLE_PROMPT = """Three houses stand side by side, numbered 1–3 from left to right. Each house has: A different color: red, green, blue A resident of a different nationality: British, French, Japanese A different pet: dog, cat, fish Clues: The British resident lives in the red house. The French resident owns the dog. The green house is immediately to the left of the red house. The Japanese resident lives in House 1. The cat is kept in the blue house. Question: Who owns the fish? 🐟""" # The 4 showcase prompts are shared across languages — the full text is # kept verbatim (that's what we send to the model) while the frontend # truncates the button label for display; see ``createOverlay`` in # static/app.js for the label-truncation side. _SHOWCASE_PROMPTS = [ _EXTRACT_NAMES_PROMPT, _CHONGQING_TRIP_PROMPT, _RATIONAL_VARIETY_PROMPT, _FISH_PUZZLE_PROMPT, ] _EXAMPLES_BY_LANG = { "en": _SHOWCASE_PROMPTS, "zh": _SHOWCASE_PROMPTS, } EXAMPLES = _EXAMPLES_BY_LANG.get(LANG, _EXAMPLES_BY_LANG["en"]) # ─── Vendored asset inlining ────────────────────────────────────────── # Every vendored library is INLINED into the ``js`` / ``css`` parameters # that ``gr.Blocks`` already serves on the page, so the app runs fully # self-contained without any external CDN or extra static-route plumbing. # # Order matters for JS: marked / katex / auto-render / hljs must be # defined as globals BEFORE static/chat.js runs; static/chat.js must # define ``window.HY_CHAT`` BEFORE static/app.js's ``bootstrap()`` # polls for ``#hy-chat``. Concatenation order below preserves this. def _read(p: Path) -> str: return p.read_text(encoding="utf-8") _VENDOR_JS = "\n;\n".join([ _read(_VENDOR_DIR / "marked" / "marked.min.js"), _read(_VENDOR_DIR / "katex" / "katex.min.js"), _read(_VENDOR_DIR / "katex" / "auto-render.min.js"), _read(_VENDOR_DIR / "highlight" / "highlight.min.js"), ]) _CHAT_JS = _read(_STATIC_DIR / "chat.js") _APP_JS = _read(_STATIC_DIR / "app.js") # KaTeX's stylesheet references font files via ``url(fonts/KaTeX_*.woff2)`` # — a path that only resolves if the CSS itself is served from the same # directory as the fonts. Since we inline the CSS into a