29 lines
1.9 KiB
Python
29 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""Gemini 네이티브 API의 Google Search 그라운딩 시험. GEMINI_API_KEY 환경변수 필요(볼트 키는 화면에 출력하지 말 것).
|
|
사용: python3 scripts/gemini-grounding-test.py "질문1" "질문2" (질문 사이 8초 대기)
|
|
2026-10-17: 무료 등급 키는 일반 호출은 되지만 google_search 도구 호출만 429(RESOURCE_EXHAUSTED) — 결제 연결 후 재시험 필요."""
|
|
import json,os,sys,time,urllib.request,urllib.error
|
|
KEY=os.environ["GEMINI_API_KEY"]
|
|
def ground(q, model="gemini-3.5-flash-lite"):
|
|
body={"contents":[{"role":"user","parts":[{"text":q+"\n\n한국어로, 근거가 되는 사실 위주로 간결히 답하세요."}]}],
|
|
"tools":[{"google_search":{}}],"generationConfig":{"temperature":0}}
|
|
req=urllib.request.Request(f"https://generativelanguage.googleapis.com/v1beta/models/{model}:generateContent",json.dumps(body).encode(),
|
|
{"Content-Type":"application/json","x-goog-api-key":KEY})
|
|
t=time.time()
|
|
try:
|
|
d=json.loads(urllib.request.urlopen(req,timeout=90).read())
|
|
except urllib.error.HTTPError as e:
|
|
return {"err":e.code,"body":e.read()[:300].decode('utf-8','replace')}
|
|
c=d["candidates"][0]; gm=c.get("groundingMetadata",{})
|
|
text="".join(p.get("text","") for p in c["content"].get("parts",[]))
|
|
return {"sec":round(time.time()-t,1),"queries":gm.get("webSearchQueries"),
|
|
"sources":[(g["web"].get("title"),g["web"].get("uri","")[:70]) for g in gm.get("groundingChunks",[]) if "web" in g],
|
|
"supports":len(gm.get("groundingSupports",[])),"text":text}
|
|
for q in sys.argv[1:]:
|
|
r=ground(q); print("\n#####",q)
|
|
if "err" in r: print("ERR",r); continue
|
|
print("sec",r["sec"],"| 검색어:",r["queries"],"| 출처",len(r["sources"]),"| 근거연결",r["supports"])
|
|
for s in r["sources"][:6]: print(" -",s)
|
|
print(r["text"][:700])
|
|
time.sleep(8)
|