Skip to content

Commit eed2943

Browse files
committed
feat: add wait_for_completion method to IndexingJobs resource with sync/async support
1 parent 1af16f3 commit eed2943

File tree

2 files changed

+392
-0
lines changed

2 files changed

+392
-0
lines changed
Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Example: Waiting for Knowledge Base Indexing Job Completion
4+
5+
This example demonstrates how to use the wait_for_completion() method
6+
to automatically wait for a knowledge base indexing job to finish,
7+
without needing to write manual polling loops.
8+
"""
9+
10+
import os
11+
from gradient import Gradient
12+
13+
14+
def main():
15+
# Initialize the Gradient client
16+
client = Gradient()
17+
18+
# Example 1: Basic usage - wait for indexing job to complete
19+
print("Example 1: Basic usage")
20+
print("-" * 50)
21+
22+
# Create an indexing job (replace with your actual knowledge base UUID)
23+
knowledge_base_uuid = os.getenv("KNOWLEDGE_BASE_UUID", "your-kb-uuid-here")
24+
25+
print(f"Creating indexing job for knowledge base: {knowledge_base_uuid}")
26+
indexing_job = client.knowledge_bases.indexing_jobs.create(
27+
knowledge_base_uuid=knowledge_base_uuid,
28+
)
29+
30+
job_uuid = indexing_job.job.uuid if indexing_job.job else None
31+
if not job_uuid:
32+
print("Error: Could not create indexing job")
33+
return
34+
35+
print(f"Indexing job created with UUID: {job_uuid}")
36+
print("Waiting for indexing job to complete...")
37+
38+
try:
39+
# Wait for the job to complete (polls every 5 seconds by default)
40+
completed_job = client.knowledge_bases.indexing_jobs.wait_for_completion(
41+
job_uuid
42+
)
43+
44+
print("\n✅ Indexing job completed successfully!")
45+
if completed_job.job:
46+
print(f"Phase: {completed_job.job.phase}")
47+
print(f"Total items indexed: {completed_job.job.total_items_indexed}")
48+
print(f"Total items failed: {completed_job.job.total_items_failed}")
49+
print(f"Total datasources: {completed_job.job.total_datasources}")
50+
print(f"Completed datasources: {completed_job.job.completed_datasources}")
51+
52+
except TimeoutError as e:
53+
print(f"\n⏱️ Timeout: {e}")
54+
except RuntimeError as e:
55+
print(f"\n❌ Error: {e}")
56+
except Exception as e:
57+
print(f"\n❌ Unexpected error: {e}")
58+
59+
60+
def example_with_custom_polling():
61+
"""Example with custom polling interval and timeout"""
62+
print("\n\nExample 2: Custom polling interval and timeout")
63+
print("-" * 50)
64+
65+
client = Gradient()
66+
knowledge_base_uuid = os.getenv("KNOWLEDGE_BASE_UUID", "your-kb-uuid-here")
67+
68+
print(f"Creating indexing job for knowledge base: {knowledge_base_uuid}")
69+
indexing_job = client.knowledge_bases.indexing_jobs.create(
70+
knowledge_base_uuid=knowledge_base_uuid,
71+
)
72+
73+
job_uuid = indexing_job.job.uuid if indexing_job.job else None
74+
if not job_uuid:
75+
print("Error: Could not create indexing job")
76+
return
77+
78+
print(f"Indexing job created with UUID: {job_uuid}")
79+
print("Waiting for indexing job to complete (polling every 10 seconds, 5 minute timeout)...")
80+
81+
try:
82+
# Wait with custom poll interval (10 seconds) and timeout (5 minutes = 300 seconds)
83+
completed_job = client.knowledge_bases.indexing_jobs.wait_for_completion(
84+
job_uuid,
85+
poll_interval=10, # Poll every 10 seconds
86+
timeout=300, # Timeout after 5 minutes
87+
)
88+
89+
print("\n✅ Indexing job completed successfully!")
90+
if completed_job.job:
91+
print(f"Phase: {completed_job.job.phase}")
92+
93+
except TimeoutError:
94+
print("\n⏱️ Job did not complete within 5 minutes")
95+
# You can still check the current status
96+
current_status = client.knowledge_bases.indexing_jobs.retrieve(job_uuid)
97+
if current_status.job:
98+
print(f"Current phase: {current_status.job.phase}")
99+
print(f"Completed datasources: {current_status.job.completed_datasources}/{current_status.job.total_datasources}")
100+
except RuntimeError as e:
101+
print(f"\n❌ Job failed: {e}")
102+
103+
104+
def example_manual_polling():
105+
"""Example of the old manual polling approach (for comparison)"""
106+
print("\n\nExample 3: Manual polling (old approach)")
107+
print("-" * 50)
108+
109+
client = Gradient()
110+
knowledge_base_uuid = os.getenv("KNOWLEDGE_BASE_UUID", "your-kb-uuid-here")
111+
112+
indexing_job = client.knowledge_bases.indexing_jobs.create(
113+
knowledge_base_uuid=knowledge_base_uuid,
114+
)
115+
116+
job_uuid = indexing_job.job.uuid if indexing_job.job else None
117+
if not job_uuid:
118+
print("Error: Could not create indexing job")
119+
return
120+
121+
print(f"Indexing job created with UUID: {job_uuid}")
122+
print("Manual polling (old approach)...")
123+
124+
import time
125+
126+
while True:
127+
indexing_job = client.knowledge_bases.indexing_jobs.retrieve(job_uuid)
128+
129+
if indexing_job.job and indexing_job.job.phase:
130+
phase = indexing_job.job.phase
131+
print(f"Current phase: {phase}")
132+
133+
if phase in ["BATCH_JOB_PHASE_UNKNOWN", "BATCH_JOB_PHASE_PENDING", "BATCH_JOB_PHASE_RUNNING"]:
134+
time.sleep(5)
135+
continue
136+
elif phase == "BATCH_JOB_PHASE_SUCCEEDED":
137+
print("✅ Job completed successfully!")
138+
break
139+
else:
140+
print(f"❌ Job ended with phase: {phase}")
141+
break
142+
143+
144+
async def example_async():
145+
"""Example using async/await"""
146+
print("\n\nExample 4: Async usage")
147+
print("-" * 50)
148+
149+
from gradient import AsyncGradient
150+
151+
client = AsyncGradient()
152+
knowledge_base_uuid = os.getenv("KNOWLEDGE_BASE_UUID", "your-kb-uuid-here")
153+
154+
print(f"Creating indexing job for knowledge base: {knowledge_base_uuid}")
155+
indexing_job = await client.knowledge_bases.indexing_jobs.create(
156+
knowledge_base_uuid=knowledge_base_uuid,
157+
)
158+
159+
job_uuid = indexing_job.job.uuid if indexing_job.job else None
160+
if not job_uuid:
161+
print("Error: Could not create indexing job")
162+
return
163+
164+
print(f"Indexing job created with UUID: {job_uuid}")
165+
print("Waiting for indexing job to complete (async)...")
166+
167+
try:
168+
completed_job = await client.knowledge_bases.indexing_jobs.wait_for_completion(
169+
job_uuid,
170+
poll_interval=5,
171+
timeout=600, # 10 minute timeout
172+
)
173+
174+
print("\n✅ Indexing job completed successfully!")
175+
if completed_job.job:
176+
print(f"Phase: {completed_job.job.phase}")
177+
178+
except TimeoutError as e:
179+
print(f"\n⏱️ Timeout: {e}")
180+
except RuntimeError as e:
181+
print(f"\n❌ Error: {e}")
182+
finally:
183+
await client.close()
184+
185+
186+
if __name__ == "__main__":
187+
# Run the basic example
188+
main()
189+
190+
# Uncomment to run other examples:
191+
# example_with_custom_polling()
192+
# example_manual_polling()
193+
194+
# For async example, you would need to run:
195+
# import asyncio
196+
# asyncio.run(example_async())

0 commit comments

Comments
 (0)