-
Notifications
You must be signed in to change notification settings - Fork 65
Expand file tree
/
Copy pathcontext_optimizer_gemini_loop.py
More file actions
87 lines (74 loc) · 2.64 KB
/
Copy pathcontext_optimizer_gemini_loop.py
File metadata and controls
87 lines (74 loc) · 2.64 KB
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
"""Optional live Gemini loop: context_optimizer → answer from optimized_context.
Requires GOOGLE_API_KEY and pip install "skillware[gemini]".
Set CONTEXT_OPTIMIZER_GEMINI_LIVE=1 to run the model call.
"""
from __future__ import annotations
import os
from pathlib import Path
from skillware.core.env import load_env_file
from skillware.core.loader import SkillLoader
SAMPLE = (
Path(__file__).resolve().parent.parent
/ "skills"
/ "optimization"
/ "context_optimizer"
/ "data"
/ "sample_policy.txt"
)
def main() -> None:
load_env_file()
if os.environ.get("CONTEXT_OPTIMIZER_GEMINI_LIVE", "").strip().lower() not in {
"1",
"true",
"yes",
}:
print(
"Set CONTEXT_OPTIMIZER_GEMINI_LIVE=1 and GOOGLE_API_KEY to run live phase."
)
return
import google.genai as genai
from google.genai import types
bundle = SkillLoader.load_skill("optimization/context_optimizer")
skill = bundle["class"]()
document = SAMPLE.read_text(encoding="utf-8")
agent_goal = "Summarize jurisdiction and data handling obligations only."
max_tokens = int(os.environ.get("CONTEXT_OPTIMIZER_MAX_TOKENS", "250"))
min_score = float(os.environ.get("CONTEXT_OPTIMIZER_MIN_SCORE", "0.45"))
selected = skill.execute(
{
"document_text": document,
"agent_goal": agent_goal,
"max_tokens_return": max_tokens,
"min_score": min_score,
}
)
print(
"Optimizer:",
selected.get("status"),
selected.get("reduction_percentage"),
f"chunks={selected.get('chunks_selected_count')}/{selected.get('chunks_total')}",
f"out~{selected.get('estimated_output_tokens')}tok",
)
excerpt = selected.get("optimized_context", "")
if not excerpt.strip():
print("No excerpt selected — cannot run Gemini phase.")
print("agent_hint:", selected.get("agent_hint"))
return
print("Excerpt preview:", excerpt[:240].replace("\n", " "), "...")
client = genai.Client()
model = os.environ.get("GEMINI_MODEL", "gemini-3.5-flash-lite")
prompt = (
f"Task: {agent_goal}\n\n"
"Answer using ONLY the excerpt below. If the excerpt lacks enough detail, say so.\n\n"
f"--- EXCERPT ---\n{excerpt}\n--- END EXCERPT ---"
)
response = client.models.generate_content(
model=model,
contents=prompt,
config=types.GenerateContentConfig(
system_instruction="You are a compliance assistant. Cite only the provided excerpt.",
),
)
print("\nGemini answer:\n", response.text)
if __name__ == "__main__":
main()