sdk_submit_poll_result.py
1 #!/usr/bin/env python3 2 """ 3 SDK Example: Submit, Poll, and Get Result for Async Jobs 4 5 This example demonstrates how to use the PraisonAI Jobs SDK to: 6 1. Submit an async job 7 2. Poll for status 8 3. Get the result 9 10 Requirements: 11 - OPENAI_API_KEY environment variable set 12 - Jobs server running on http://127.0.0.1:8005 13 14 Usage: 15 python sdk_submit_poll_result.py 16 """ 17 18 import os 19 import time 20 import httpx 21 22 # Configuration 23 API_URL = os.getenv("PRAISONAI_BASE_URL", "http://127.0.0.1:8005") 24 POLL_INTERVAL = 2 # seconds 25 26 27 def submit_job(prompt: str, idempotency_key: str = None) -> dict: 28 """Submit a job and return the response.""" 29 headers = {} 30 if idempotency_key: 31 headers["Idempotency-Key"] = idempotency_key 32 33 with httpx.Client(timeout=30.0) as client: 34 response = client.post( 35 f"{API_URL}/api/v1/runs", 36 json={"prompt": prompt}, 37 headers=headers if headers else None 38 ) 39 response.raise_for_status() 40 return response.json() 41 42 43 def get_status(job_id: str) -> dict: 44 """Get job status.""" 45 with httpx.Client(timeout=30.0) as client: 46 response = client.get(f"{API_URL}/api/v1/runs/{job_id}") 47 response.raise_for_status() 48 return response.json() 49 50 51 def get_result(job_id: str) -> dict: 52 """Get job result.""" 53 with httpx.Client(timeout=30.0) as client: 54 response = client.get(f"{API_URL}/api/v1/runs/{job_id}/result") 55 response.raise_for_status() 56 return response.json() 57 58 59 def wait_for_completion(job_id: str, max_wait: int = 120) -> dict: 60 """Poll until job completes.""" 61 start = time.time() 62 while time.time() - start < max_wait: 63 status = get_status(job_id) 64 print(f" Status: {status['status']} | Progress: {status['progress']['percentage']:.0f}%") 65 66 if status["status"] in ("succeeded", "failed", "cancelled"): 67 return status 68 69 # Honor retry_after if present 70 wait_time = status.get("retry_after") or POLL_INTERVAL 71 time.sleep(wait_time) 72 73 raise TimeoutError(f"Job {job_id} did not complete within {max_wait}s") 74 75 76 def main(): 77 print("=" * 60) 78 print("PraisonAI Async Jobs SDK Example") 79 print("=" * 60) 80 81 # Check if server is running 82 try: 83 with httpx.Client(timeout=5.0) as client: 84 health = client.get(f"{API_URL}/health") 85 health.raise_for_status() 86 print(f"✓ Server healthy: {health.json()['status']}") 87 except Exception as e: 88 print(f"✗ Server not available at {API_URL}: {e}") 89 print(" Start the server with: python -m uvicorn praisonai.jobs.server:create_app --port 8005 --factory") 90 return 91 92 # 1. Submit a job 93 print("\n1. Submitting job...") 94 prompt = "What is the capital of France? Answer in one word." 95 result = submit_job(prompt) 96 job_id = result["job_id"] 97 print(f" Job ID: {job_id}") 98 print(f" Status: {result['status']}") 99 print(f" Poll URL: {result['poll_url']}") 100 101 # 2. Wait for completion 102 print("\n2. Waiting for completion...") 103 final_status = wait_for_completion(job_id) 104 print(f" Final status: {final_status['status']}") 105 106 # 3. Get result 107 if final_status["status"] == "succeeded": 108 print("\n3. Getting result...") 109 result = get_result(job_id) 110 print(f" Result: {result['result']}") 111 print(f" Duration: {result['duration_seconds']:.2f}s") 112 else: 113 print(f"\n3. Job did not succeed: {final_status.get('error', 'Unknown error')}") 114 115 print("\n" + "=" * 60) 116 print("Example completed successfully!") 117 print("=" * 60) 118 119 120 if __name__ == "__main__": 121 main()