Spaces:
Sleeping
Sleeping
Download elyon_protocol.py from Soushell/Elyon-Lyra: direct link, hf CLI and curl.
- Browser
- Download file 5.23 kB
-
https://huggingface.co/spaces/Soushell/Elyon-Lyra/resolve/main/elyon_protocol.py
- Command line
-
hf download hf://spaces/Soushell/Elyon-Lyra/elyon_protocol.py
-
curl -L -o elyon_protocol.py https://huggingface.co/spaces/Soushell/Elyon-Lyra/resolve/main/elyon_protocol.py
5.23 kB
| #!/usr/bin/env python | |
| # -*- coding: utf-8 -*- | |
| """Общий протокол Elyon Lyra / Elyon Vega: один формат для обучения, тестов и серверной части (Space). | |
| Без внешних зависимостей (только stdlib), чтобы файл можно было положить в Space как есть. | |
| Цикл одного запроса (до MAX_TOOL_ROUNDS раз): | |
| 1. messages = [system(SYSTEM_PROMPT), ...история..., user(вопрос)] | |
| 2. ответ модели. Если parse_tool_call(ответ) вернул query -> вызвать поиск, иначе ответ финальный. | |
| 3. к messages добавляются: assistant(JSON-вызов как есть) и user(format_results(...)); шаг 2 повторяется. | |
| Результаты поиска передаются обычной user-репликой (а не специальной ролью), потому что шаблоны Gemma и Qwen | |
| по-разному обрабатывают роль tool, а так формат одинаков для обеих моделей и для обучения (обучается последняя реплика ассистента). | |
| """ | |
| import json | |
| import re | |
| MAX_TOOL_ROUNDS = 2 | |
| # Тот же текст, что TOOL_SYSTEM в model_probe.py: навык вызова поиска, обученный раньше, не должен сломаться. | |
| SYSTEM_PROMPT = ( | |
| "You are an assistant with one tool: web_search(query). " | |
| "If the question needs current or recent information that you cannot know reliably, " | |
| 'reply with ONLY this JSON and nothing else: {"tool": "web_search", "query": "<search query>"}. ' | |
| "If you can answer from stable knowledge or by reasoning, answer directly and do NOT call the tool. " | |
| "Answer in the user's language." | |
| ) | |
| RESULTS_HEADER = "Search results for: " | |
| RESULTS_FOOTER = ( | |
| "Answer the user's question using these results. Reply in the user's language. " | |
| "If the results do not contain the answer, say that you could not find it; do not guess." | |
| ) | |
| MAX_RESULTS = 5 | |
| MAX_SNIPPET_CHARS = 400 | |
| def make_call(query): | |
| """Текст вызова поиска, каким модель должна его выдать (и каким он кладётся в историю).""" | |
| return json.dumps({"tool": "web_search", "query": query}, ensure_ascii=False) | |
| def parse_tool_call(text): | |
| """query, если ответ содержит валидный вызов web_search, иначе None.""" | |
| for m in re.finditer(r"\{.*?\}", text, flags=re.S): | |
| try: | |
| d = json.loads(m.group(0)) | |
| except Exception: | |
| continue | |
| if isinstance(d, dict) and d.get("tool") == "web_search" and str(d.get("query", "")).strip(): | |
| return str(d["query"]).strip() | |
| return None | |
| def _host(url): | |
| m = re.match(r"https?://([^/]+)", url or "") | |
| return m.group(1).removeprefix("www.") if m else "" | |
| def format_results(query, results): | |
| """results: список {"title","snippet","url"}. Возвращает текст user-реплики с результатами поиска.""" | |
| lines = [RESULTS_HEADER + query, ""] | |
| shown = 0 | |
| for r in results[:MAX_RESULTS]: | |
| title = " ".join(str(r.get("title", "")).split()) | |
| snip = " ".join(str(r.get("snippet", "")).split())[:MAX_SNIPPET_CHARS] | |
| if not (title or snip): | |
| continue | |
| shown += 1 | |
| host = _host(r.get("url", "")) | |
| lines.append("[%d] %s%s" % (shown, title, " (%s)" % host if host else "")) | |
| if snip: | |
| lines.append(snip) | |
| lines.append("") | |
| if shown == 0: | |
| lines += ["(no results)", ""] | |
| lines.append(RESULTS_FOOTER) | |
| return "\n".join(lines) | |
| def run_chat(generate, search, history, user_text, max_rounds=MAX_TOOL_ROUNDS): | |
| """Полный цикл для сервера и тестов. | |
| generate(messages) -> str (вызов модели) | |
| search(query) -> list[dict] (вызов поиска; исключения превращаются в «нет результатов») | |
| Возвращает (финальный_ответ, journal), journal = список вызовов поиска [{"query","n_results"}]. | |
| """ | |
| messages = [{"role": "system", "content": SYSTEM_PROMPT}] + list(history) + [{"role": "user", "content": user_text}] | |
| journal = [] | |
| for _ in range(max_rounds + 1): | |
| answer = generate(messages) | |
| q = parse_tool_call(answer) | |
| if q is None or len(journal) >= max_rounds: | |
| # после лимита раундов вызов JSON не отдаём пользователю как ответ | |
| return (answer if q is None else ""), journal | |
| try: | |
| res = search(q) or [] | |
| except Exception: | |
| res = [] | |
| journal.append({"query": q, "n_results": len(res)}) | |
| messages.append({"role": "assistant", "content": make_call(q)}) | |
| messages.append({"role": "user", "content": format_results(q, res)}) | |
| return "", journal | |