Add files via upload
This commit is contained in:
1 parent
b3f7708e0e
commit
476a9c09d6
28 files changed
+8099
-2459
No files matched your search
+15
-14
@@ -15,7 +15,10 @@ BASE_DIR = get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
DESKTOP = Path.home() / "Desktop"
|
||||
MAX_BUILD_ATTEMPTS = 3
|
||||
GEMINI_MODEL = "gemini-flash-latest"
|
||||
# Model choice lives in core/gemini.py, and so does the timeout and the
|
||||
# fallback ladder. Writing a model name here is what left this file hanging
|
||||
# forever whenever that one alias was unwell.
|
||||
from core import gemini
|
||||
|
||||
|
||||
def _get_api_key() -> str:
|
||||
@@ -23,13 +26,15 @@ def _get_api_key() -> str:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _get_gemini(model: str = GEMINI_MODEL):
|
||||
from google import genai
|
||||
_c = genai.Client(api_key=_get_api_key())
|
||||
|
||||
def _get_gemini(tier: str = gemini.SMART):
|
||||
"""Writing and fixing code is the reasoning tier; a 60s deadline because a
|
||||
whole file can come back."""
|
||||
class _W:
|
||||
def generate_content(self, contents):
|
||||
return _c.models.generate_content(model=model, contents=contents)
|
||||
resp = gemini.call(contents, tier=tier, timeout_ms=60000)
|
||||
if resp is None:
|
||||
raise RuntimeError("every Gemini model on the ladder failed")
|
||||
return resp
|
||||
|
||||
return _W()
|
||||
|
||||
@@ -456,11 +461,8 @@ def _screen_debug_action(description, file_path, player, speak=None) -> str:
|
||||
print(f"[Code] ⚠️ Could not read file: {err}")
|
||||
|
||||
try:
|
||||
from google import genai
|
||||
from google.genai import types
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
|
||||
image_bytes = screenshot_path.read_bytes()
|
||||
image_base64 = _image_to_base64(screenshot_path)
|
||||
|
||||
@@ -487,12 +489,11 @@ Be specific and actionable. If you see an error message, quote it exactly."""
|
||||
analysis_prompt,
|
||||
]
|
||||
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=contents,
|
||||
)
|
||||
response = gemini.call(contents, tier=gemini.SMART, timeout_ms=45_000)
|
||||
if response is None:
|
||||
return "Sir, I couldn't reach Gemini to analyse that screenshot."
|
||||
|
||||
analysis = response.text.strip()
|
||||
analysis = (response.text or "").strip()
|
||||
print(f"[Code] ✅ Screen analysis complete")
|
||||
|
||||
try:
|
||||
|
||||
@@ -327,7 +327,6 @@ def _screen_find(description: str) -> tuple[int, int] | None:
|
||||
img.save(buf, format="PNG")
|
||||
image_bytes = buf.getvalue()
|
||||
|
||||
client = genai.Client(api_key=api_key)
|
||||
prompt = (
|
||||
f"This is a screenshot of a {w}×{h} pixel screen. "
|
||||
f"Locate the UI element described as: '{description}'. "
|
||||
@@ -335,13 +334,13 @@ def _screen_find(description: str) -> tuple[int, int] | None:
|
||||
f"If the element is not visible, reply: NOT_FOUND"
|
||||
)
|
||||
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-lite-latest",
|
||||
contents=[
|
||||
gtypes.Part.from_bytes(data=image_bytes, mime_type="image/png"),
|
||||
prompt,
|
||||
],
|
||||
from core import gemini
|
||||
response = gemini.call(
|
||||
[gtypes.Part.from_bytes(data=image_bytes, mime_type="image/png"), prompt],
|
||||
tier=gemini.FAST, timeout_ms=20_000,
|
||||
)
|
||||
if response is None:
|
||||
return None
|
||||
|
||||
text = (response.text or "").strip()
|
||||
if "NOT_FOUND" in text.upper():
|
||||
|
||||
+5
-3
@@ -104,7 +104,6 @@ def _execute_generated_code(code: str, player=None) -> str:
|
||||
def _ask_gemini_for_desktop_action(task: str) -> str:
|
||||
|
||||
from google import genai as _genai
|
||||
_client = _genai.Client(api_key=_get_api_key())
|
||||
|
||||
desktop = str(_get_desktop())
|
||||
|
||||
@@ -142,8 +141,11 @@ Output ONLY the Python code. No explanation, no markdown, no backticks.
|
||||
Task: {task}"""
|
||||
|
||||
try:
|
||||
response = _client.models.generate_content(model="gemini-flash-latest", contents=prompt)
|
||||
code = response.text.strip()
|
||||
from core import gemini
|
||||
response = gemini.call(prompt, tier=gemini.SMART, timeout_ms=30_000)
|
||||
if response is None:
|
||||
return "ERROR: every Gemini model on the ladder failed"
|
||||
code = (response.text or "").strip()
|
||||
if code.startswith("```"):
|
||||
lines = code.split("\n")
|
||||
code = "\n".join(lines[1:-1]).strip()
|
||||
|
||||
+12
-7
@@ -16,21 +16,26 @@ BASE_DIR = get_base_dir()
|
||||
API_CONFIG_PATH = BASE_DIR / "config" / "api_keys.json"
|
||||
PROJECTS_DIR = Path.home() / "Desktop" / "JarvisProjects"
|
||||
MAX_FIX_ATTEMPTS = 5
|
||||
MODEL_PLANNER = "gemini-flash-latest"
|
||||
MODEL_WRITER = "gemini-flash-latest"
|
||||
# Model choice, timeout and fallback ladder all live in core/gemini.py.
|
||||
from core import gemini
|
||||
|
||||
MODEL_PLANNER = gemini.SMART
|
||||
MODEL_WRITER = gemini.SMART
|
||||
|
||||
def _get_api_key() -> str:
|
||||
with open(API_CONFIG_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _get_model(model_name: str):
|
||||
from google import genai
|
||||
_c = genai.Client(api_key=_get_api_key())
|
||||
|
||||
def _get_model(model_name: str = gemini.SMART):
|
||||
"""Planning and writing whole files — the reasoning tier, and a long
|
||||
deadline because the answer is a source file rather than a sentence."""
|
||||
class _W:
|
||||
def generate_content(self, contents):
|
||||
return _c.models.generate_content(model=model_name, contents=contents)
|
||||
resp = gemini.call(contents, tier=model_name, timeout_ms=60000)
|
||||
if resp is None:
|
||||
raise RuntimeError("every Gemini model on the ladder failed")
|
||||
return resp
|
||||
|
||||
return _W()
|
||||
|
||||
|
||||
@@ -158,9 +158,22 @@ def _resolve_path(raw: str) -> Path:
|
||||
"videos": _get_videos(),
|
||||
"home": Path.home(),
|
||||
}
|
||||
lower = raw.strip().lower()
|
||||
raw = raw.strip().strip('"').strip("'")
|
||||
lower = raw.lower()
|
||||
if lower in shortcuts:
|
||||
return shortcuts[lower]
|
||||
|
||||
# "desktop/notes/a.md" and "desktop\notes\a.md" — a shortcut followed by a
|
||||
# sub-path. Without this branch the whole string falls through to the
|
||||
# relative-path return below and is resolved against the process CWD instead
|
||||
# of the real Desktop: an "Access denied" when the project lives outside the
|
||||
# home directory, or — worse — a silent write into a stray "desktop" folder
|
||||
# inside the project when it lives inside it.
|
||||
head, sep, rest = raw.replace("\\", "/").partition("/")
|
||||
if sep and head.lower() in shortcuts:
|
||||
rest = rest.strip("/")
|
||||
return shortcuts[head.lower()] / rest if rest else shortcuts[head.lower()]
|
||||
|
||||
return Path(raw).expanduser()
|
||||
|
||||
def _format_size(b: int) -> str:
|
||||
|
||||
@@ -25,19 +25,24 @@ import tempfile
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
# Model choice, timeout and fallback ladder all live in core/gemini.py.
|
||||
from core import gemini
|
||||
|
||||
def _get_api_key() -> str:
|
||||
config_path = Path(__file__).resolve().parent.parent / "config" / "api_keys.json"
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
return json.load(f)["gemini_api_key"]
|
||||
|
||||
|
||||
def _gemini_client():
|
||||
from google import genai
|
||||
_c = genai.Client(api_key=_get_api_key())
|
||||
|
||||
def _gemini_client(tier: str = gemini.SMART):
|
||||
"""Summarising documents and reading images — the reasoning tier, with a
|
||||
long deadline because the input can be a whole file."""
|
||||
class _W:
|
||||
def generate_content(self, contents):
|
||||
return _c.models.generate_content(model="gemini-flash-latest", contents=contents)
|
||||
resp = gemini.call(contents, tier=tier, timeout_ms=90000)
|
||||
if resp is None:
|
||||
raise RuntimeError("every Gemini model on the ladder failed")
|
||||
return resp
|
||||
|
||||
return _W()
|
||||
|
||||
|
||||
+11
-14
@@ -60,17 +60,13 @@ def _parse_date(raw: str) -> str:
|
||||
return val.strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
from google import genai as _genai
|
||||
_client = _genai.Client(api_key=_get_api_key())
|
||||
response = _client.models.generate_content(
|
||||
model="gemini-flash-lite-latest",
|
||||
contents=(
|
||||
f"Today is {today.strftime('%Y-%m-%d')}. "
|
||||
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
|
||||
f"Return ONLY the date string, nothing else."
|
||||
)
|
||||
from core import gemini
|
||||
result = gemini.text(
|
||||
f"Today is {today.strftime('%Y-%m-%d')}. "
|
||||
f"Convert this date expression to YYYY-MM-DD: '{raw}'. "
|
||||
f"Return ONLY the date string, nothing else.",
|
||||
tier=gemini.FAST,
|
||||
)
|
||||
result = response.text.strip()
|
||||
if re.match(r"\d{4}-\d{2}-\d{2}", result):
|
||||
return result
|
||||
except Exception as e:
|
||||
@@ -155,7 +151,6 @@ def _parse_flights_with_gemini(
|
||||
from google import genai as _genai
|
||||
from google.genai import types
|
||||
|
||||
_client = _genai.Client(api_key=_get_api_key())
|
||||
prompt = (
|
||||
f"Extract flight options from {origin} to {destination} on {date} "
|
||||
f"from this Google Flights page text:\n\n{raw_text[:12000]}\n\n"
|
||||
@@ -166,9 +161,11 @@ def _parse_flights_with_gemini(
|
||||
)
|
||||
|
||||
try:
|
||||
response = _client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=prompt,
|
||||
from core import gemini
|
||||
response = gemini.call(
|
||||
prompt,
|
||||
tier=gemini.SMART,
|
||||
timeout_ms=30_000,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=(
|
||||
"You are a flight data extraction expert. "
|
||||
|
||||
+140
-67
@@ -1,8 +1,68 @@
|
||||
#web_search.py
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
# ── Gemini grounding quota circuit breaker ────────────────────────────────────
|
||||
# The google_search grounding tool has its own small quota, separate from plain
|
||||
# generation. Once it is spent every call returns 429 — so retrying it at the
|
||||
# top of every search only adds a dead round-trip before the DDG fallback runs.
|
||||
# After a quota error, skip Gemini entirely for a cooldown period.
|
||||
_QUOTA_COOLDOWN_SEC = 900 # 15 minutes
|
||||
_quota_blocked_until = 0.0
|
||||
_quota_lock = threading.Lock()
|
||||
|
||||
|
||||
def _gemini_available() -> bool:
|
||||
with _quota_lock:
|
||||
return time.monotonic() >= _quota_blocked_until
|
||||
|
||||
|
||||
def _note_gemini_error(exc: Exception) -> None:
|
||||
"""Trip the breaker when the error is a quota / rate-limit rejection."""
|
||||
global _quota_blocked_until
|
||||
msg = str(exc)
|
||||
if "429" in msg or "RESOURCE_EXHAUSTED" in msg:
|
||||
with _quota_lock:
|
||||
already = time.monotonic() < _quota_blocked_until
|
||||
_quota_blocked_until = time.monotonic() + _QUOTA_COOLDOWN_SEC
|
||||
if not already:
|
||||
print(
|
||||
"[WebSearch] Gemini grounding quota exhausted — skipping it for "
|
||||
f"{_QUOTA_COOLDOWN_SEC // 60} min and serving results from DDG."
|
||||
)
|
||||
|
||||
|
||||
class _QuotaCooldown(RuntimeError):
|
||||
"""Raised instead of calling Gemini while the quota breaker is open."""
|
||||
|
||||
|
||||
def _log_gemini_failure(context: str, exc: Exception) -> None:
|
||||
"""Log a Gemini failure — silently when it is just the expected cooldown."""
|
||||
if isinstance(exc, _QuotaCooldown):
|
||||
return # announced once when the breaker tripped; not a warning
|
||||
print(f"[WebSearch] \u26a0\ufe0f {context} failed ({exc}) — using DDG instead")
|
||||
|
||||
|
||||
def _run_bounded(fn, timeout: float, label: str = "task"):
|
||||
"""Run fn() in a daemon thread; return its result, or None if it overruns."""
|
||||
box = [None]
|
||||
|
||||
def _run():
|
||||
try:
|
||||
box[0] = fn()
|
||||
except Exception as e:
|
||||
_log_gemini_failure(label, e)
|
||||
|
||||
t = threading.Thread(target=_run, daemon=True)
|
||||
t.start()
|
||||
t.join(timeout)
|
||||
if t.is_alive():
|
||||
print(f"[WebSearch] {label} exceeded {timeout:.0f}s — moving on")
|
||||
return box[0]
|
||||
|
||||
def _get_base_dir() -> Path:
|
||||
if getattr(sys, "frozen", False):
|
||||
return Path(sys.executable).parent
|
||||
@@ -19,14 +79,22 @@ def _get_api_key() -> str:
|
||||
|
||||
|
||||
def _gemini_search(query: str) -> str:
|
||||
from google import genai
|
||||
if not _gemini_available():
|
||||
raise _QuotaCooldown("Gemini grounding is in quota cooldown")
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=query,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
)
|
||||
from core import gemini
|
||||
|
||||
# Grounded search reads a live page, so it gets a longer deadline than the
|
||||
# default — but it still HAS one, and it still walks the fallback ladder.
|
||||
try:
|
||||
response = gemini.call(query, tier=gemini.SEARCH,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
timeout_ms=30_000)
|
||||
if response is None:
|
||||
raise RuntimeError("every Gemini model on the ladder failed")
|
||||
except Exception as e:
|
||||
_note_gemini_error(e)
|
||||
raise
|
||||
|
||||
text = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
@@ -39,30 +107,45 @@ def _gemini_search(query: str) -> str:
|
||||
return text
|
||||
|
||||
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
def _get_ddgs():
|
||||
"""
|
||||
Returns the DDGS class. The package was renamed duckduckgo-search -> ddgs;
|
||||
the legacy package's endpoints are now rejected by DuckDuckGo (news() gets a
|
||||
403 Ratelimit, text() silently returns zero results), so warn loudly if we
|
||||
end up on it instead of failing in silence.
|
||||
"""
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
return DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
print(
|
||||
"[WebSearch] ⚠️ Using the deprecated 'duckduckgo-search' package — "
|
||||
"DuckDuckGo blocks its endpoints, so every search will come back "
|
||||
"empty. Fix with: pip install -U ddgs"
|
||||
)
|
||||
return DDGS
|
||||
|
||||
|
||||
def _ddg_search(query: str, max_results: int = 6) -> list[dict]:
|
||||
DDGS = _get_ddgs()
|
||||
results = []
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
try:
|
||||
with DDGS() as ddgs:
|
||||
for r in ddgs.text(query, max_results=max_results):
|
||||
results.append({
|
||||
"title": r.get("title", ""),
|
||||
"snippet": r.get("body", ""),
|
||||
"url": r.get("href", ""),
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG text() failed: {e}")
|
||||
return results
|
||||
|
||||
|
||||
def _ddg_news(query: str, max_results: int = 8) -> list[dict]:
|
||||
"""DDG news search — returns actual articles, not website homepages."""
|
||||
try:
|
||||
from ddgs import DDGS
|
||||
except ImportError:
|
||||
from duckduckgo_search import DDGS
|
||||
|
||||
DDGS = _get_ddgs()
|
||||
results = []
|
||||
try:
|
||||
with DDGS() as ddgs:
|
||||
@@ -75,6 +158,9 @@ def _ddg_news(query: str, max_results: int = 8) -> list[dict]:
|
||||
})
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news() failed ({e}) — falling back to text search")
|
||||
# Also covers the legacy-package case, where news() returns an empty list
|
||||
# instead of raising.
|
||||
if not results:
|
||||
results = _ddg_search(query, max_results=max_results)
|
||||
return results
|
||||
|
||||
@@ -120,14 +206,16 @@ def _gemini_headlines(n: int = 5) -> tuple[list[str], str]:
|
||||
Returns (headline_list, raw_text_for_display).
|
||||
"""
|
||||
import re
|
||||
from google import genai
|
||||
from core import gemini
|
||||
|
||||
client = genai.Client(api_key=_get_api_key())
|
||||
response = client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=f"Current world news: {n} headlines. Numbered list, titles only.",
|
||||
response = gemini.call(
|
||||
f"Current world news: {n} headlines. Numbered list, titles only.",
|
||||
tier=gemini.SEARCH,
|
||||
config={"tools": [{"google_search": {}}]},
|
||||
timeout_ms=30_000,
|
||||
)
|
||||
if response is None:
|
||||
return [], ""
|
||||
|
||||
raw = ""
|
||||
for part in response.candidates[0].content.parts:
|
||||
@@ -157,58 +245,43 @@ def _search(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini failed ({e}) — trying DDG...")
|
||||
_log_gemini_failure("Gemini search", e)
|
||||
results = _ddg_search(query)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
|
||||
def _news(query: str) -> str:
|
||||
"""
|
||||
Runs Gemini grounded search AND DDG news in parallel.
|
||||
Returns whichever delivers a valid result first; cancels the other.
|
||||
"""
|
||||
import threading
|
||||
DDG first, Gemini as backup.
|
||||
|
||||
The old version raced both backends in parallel and kept the first answer.
|
||||
That burned one google_search grounding call on *every* news request —
|
||||
including the startup briefing — even when DDG had already won the race.
|
||||
Grounding has a small quota, so it ran dry after a handful of launches and
|
||||
then 429'd for everything else (research/compare), which are the modes that
|
||||
actually need a synthesised answer.
|
||||
|
||||
DDG news returns in well under a second and gives raw headlines, which is
|
||||
exactly what the briefing wants, so it goes first and Gemini is only touched
|
||||
when DDG comes back empty.
|
||||
"""
|
||||
gemini_query = f"latest news today: {query}" if query else "top world news today"
|
||||
ddg_query = query if query else "world news today"
|
||||
|
||||
result_box = [None] # first valid result lands here
|
||||
lock = threading.Lock()
|
||||
done_evt = threading.Event()
|
||||
failures = [0]
|
||||
def _ddg_attempt() -> str:
|
||||
return _format_news(ddg_query, _ddg_news(ddg_query, max_results=8))
|
||||
|
||||
def _store(r: str) -> None:
|
||||
if r and len(r) > 60:
|
||||
with lock:
|
||||
if result_box[0] is None:
|
||||
result_box[0] = r
|
||||
done_evt.set()
|
||||
else:
|
||||
with lock:
|
||||
failures[0] += 1
|
||||
if failures[0] >= 2: # both failed — unblock caller
|
||||
done_evt.set()
|
||||
text = _run_bounded(_ddg_attempt, timeout=5.0, label="DDG news")
|
||||
if text and len(text) > 60 and not text.startswith("No news found"):
|
||||
return text
|
||||
|
||||
def _try_gemini():
|
||||
try:
|
||||
_store(_gemini_search(gemini_query))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini news failed ({e})")
|
||||
_store("")
|
||||
text = _run_bounded(
|
||||
lambda: _gemini_search(gemini_query), timeout=6.0, label="Gemini news"
|
||||
)
|
||||
if text and len(text) > 60:
|
||||
return text
|
||||
|
||||
def _try_ddg():
|
||||
try:
|
||||
results = _ddg_news(ddg_query, max_results=8)
|
||||
_store(_format_news(ddg_query, results))
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ DDG news failed ({e})")
|
||||
_store("")
|
||||
|
||||
threading.Thread(target=_try_gemini, daemon=True).start()
|
||||
threading.Thread(target=_try_ddg, daemon=True).start()
|
||||
|
||||
done_evt.wait(timeout=10.0)
|
||||
return result_box[0] or f"No news found for: {query}"
|
||||
return f"No news found for: {query}"
|
||||
|
||||
|
||||
def _research(query: str) -> str:
|
||||
@@ -223,7 +296,7 @@ def _research(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(research_query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Research Gemini failed ({e}) — DDG fallback...")
|
||||
_log_gemini_failure("Gemini research", e)
|
||||
results = _ddg_search(query, max_results=10)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
@@ -234,7 +307,7 @@ def _price(query: str) -> str:
|
||||
try:
|
||||
return _gemini_search(price_query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Price Gemini failed ({e}) — DDG fallback...")
|
||||
_log_gemini_failure("Gemini price", e)
|
||||
results = _ddg_search(f"{query} price buy", max_results=6)
|
||||
return _format_ddg(query, results)
|
||||
|
||||
@@ -247,7 +320,7 @@ def _compare(items: list[str], aspect: str) -> str:
|
||||
try:
|
||||
return _gemini_search(query)
|
||||
except Exception as e:
|
||||
print(f"[WebSearch] ⚠️ Gemini compare failed: {e} — falling back to DDG")
|
||||
_log_gemini_failure("Gemini compare", e)
|
||||
|
||||
all_results: dict[str, list] = {}
|
||||
for item in items:
|
||||
|
||||
@@ -167,15 +167,17 @@ def _get_transcript(video_id: str) -> str | None:
|
||||
|
||||
|
||||
def _summarize_with_gemini(transcript: str, video_url: str) -> str:
|
||||
from google import genai as _genai
|
||||
from google.genai import types
|
||||
from core import gemini
|
||||
|
||||
_client = _genai.Client(api_key=_get_api_key())
|
||||
max_chars = 80000
|
||||
truncated = transcript[:max_chars] + ("..." if len(transcript) > max_chars else "")
|
||||
response = _client.models.generate_content(
|
||||
model="gemini-flash-latest",
|
||||
contents=f"Please summarize this YouTube video transcript:\n\n{truncated}",
|
||||
# A whole transcript can be 80k characters, hence the long deadline — but a
|
||||
# deadline there is, and the ladder in core/gemini.py picks the model.
|
||||
response = gemini.call(
|
||||
f"Please summarize this YouTube video transcript:\n\n{truncated}",
|
||||
tier=gemini.SMART,
|
||||
timeout_ms=60_000,
|
||||
config=types.GenerateContentConfig(
|
||||
system_instruction=(
|
||||
"You are JARVIS, an AI assistant. "
|
||||
@@ -186,7 +188,9 @@ def _summarize_with_gemini(transcript: str, video_url: str) -> str:
|
||||
)
|
||||
)
|
||||
)
|
||||
return response.text.strip()
|
||||
if response is None:
|
||||
return "I couldn't reach Gemini to summarise that transcript, sir."
|
||||
return (response.text or "").strip()
|
||||
|
||||
|
||||
def _save_summary(content: str, video_url: str) -> str:
|
||||
|
||||
Reference in new issue
Block a user