Files
opro_demo/examples/client_demo.py
2025-12-05 07:11:25 +00:00

56 lines
1.5 KiB
Python

import requests
BASE = "http://127.0.0.1:8010"
def _post(path, payload):
r = requests.post(BASE + path, json=payload, timeout=30)
r.raise_for_status()
j = r.json()
if "success" in j:
if not j.get("success"):
raise RuntimeError(f"api error: {j}")
return j.get("data")
return j
def _get(path):
r = requests.get(BASE + path, timeout=15)
r.raise_for_status()
j = r.json()
if "success" in j:
if not j.get("success"):
raise RuntimeError(f"api error: {j}")
return j.get("data")
return j
def main():
print("health:", _get("/health"))
try:
print("version:", _get("/version"))
except Exception:
pass
data = _post("/query", {"query": "我想买苹果"})
sid = data["session_id"]
print("created session:", sid)
print("candidates:", data["candidates"])
# choose first candidate
if data["candidates"]:
choice = data["candidates"][0]
ans = _post("/select", {"session_id": sid, "choice": choice})
print("answer:", ans["answer"][:200])
# continue optimization
more = _post("/query_from_message", {"session_id": sid})
print("next candidates:", more["candidates"])
# chat
chat = _post("/message", {"session_id": sid, "message": "还有更甜的苹果吗?"})
print("chat answer:", chat["answer"][:200])
# list sessions
print("sessions:", _get("/sessions"))
if __name__ == "__main__":
main()