-
Notifications
You must be signed in to change notification settings - Fork 3.5k
Expand file tree
/
Copy pathbasic_usage.py
More file actions
260 lines (210 loc) · 8.32 KB
/
basic_usage.py
File metadata and controls
260 lines (210 loc) · 8.32 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/usr/bin/env python3
"""
Basic usage examples for the Sim Python SDK
"""
import os
from simstudio import SimStudioClient, SimStudioError
def basic_example():
"""Example 1: Basic workflow execution"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
try:
# Execute a workflow without input
result = client.execute_workflow("your-workflow-id")
if result.success:
print("✅ Workflow executed successfully!")
print(f"Output: {result.output}")
if result.metadata:
print(f"Duration: {result.metadata.get('duration')} ms")
else:
print(f"❌ Workflow failed: {result.error}")
except SimStudioError as error:
print(f"SDK Error: {error} (Code: {error.code})")
except Exception as error:
print(f"Unexpected error: {error}")
def with_input_example():
"""Example 2: Workflow execution with input data"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
try:
result = client.execute_workflow(
"your-workflow-id",
input_data={
"message": "Hello from Python SDK!",
"user_id": "12345",
"data": {
"type": "analysis",
"parameters": {
"include_metadata": True,
"format": "json"
}
}
},
timeout=60.0 # 60 seconds
)
if result.success:
print("✅ Workflow executed successfully!")
print(f"Output: {result.output}")
if result.metadata:
print(f"Duration: {result.metadata.get('duration')} ms")
else:
print(f"❌ Workflow failed: {result.error}")
except SimStudioError as error:
print(f"SDK Error: {error} (Code: {error.code})")
except Exception as error:
print(f"Unexpected error: {error}")
def status_example():
"""Example 3: Workflow validation and status checking"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
try:
# Check if workflow is ready
is_ready = client.validate_workflow("your-workflow-id")
print(f"Workflow ready: {is_ready}")
# Get detailed status
status = client.get_workflow_status("your-workflow-id")
print(f"Status: {{\n"
f" deployed: {status.is_deployed},\n"
f" needs_redeployment: {status.needs_redeployment},\n"
f" deployed_at: {status.deployed_at}\n"
f"}}")
if status.is_deployed:
# Execute the workflow
result = client.execute_workflow("your-workflow-id")
print(f"Result: {result}")
except Exception as error:
print(f"Error: {error}")
def context_manager_example():
"""Example 4: Using context manager"""
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
try:
result = client.execute_workflow("your-workflow-id")
print(f"Result: {result}")
except Exception as error:
print(f"Error: {error}")
# Session is automatically closed here
def batch_execution_example():
"""Example 5: Batch workflow execution"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
workflows = [
("workflow-1", {"type": "analysis", "data": "sample1"}),
("workflow-2", {"type": "processing", "data": "sample2"}),
("workflow-3", {"type": "validation", "data": "sample3"}),
]
results = []
for workflow_id, input_data in workflows:
try:
# Validate workflow before execution
if not client.validate_workflow(workflow_id):
print(f"⚠️ Skipping {workflow_id}: not deployed")
continue
result = client.execute_workflow(workflow_id, input_data)
results.append({
"workflow_id": workflow_id,
"success": result.success,
"output": result.output,
"error": result.error
})
status = "✅ Success" if result.success else "❌ Failed"
print(f"{status}: {workflow_id}")
except SimStudioError as error:
results.append({
"workflow_id": workflow_id,
"success": False,
"error": str(error)
})
print(f"❌ SDK Error in {workflow_id}: {error}")
except Exception as error:
results.append({
"workflow_id": workflow_id,
"success": False,
"error": str(error)
})
print(f"❌ Unexpected error in {workflow_id}: {error}")
# Summary
successful = sum(1 for r in results if r["success"])
total = len(results)
print(f"\n📊 Summary: {successful}/{total} workflows completed successfully")
return results
def streaming_example():
"""Example 6: Workflow execution with streaming"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
try:
result = client.execute_workflow(
"your-workflow-id",
input_data={"message": "Count to five"},
stream=True,
selected_outputs=["agent1.content"], # Use blockName.attribute format
timeout=60.0
)
if result.success:
print("✅ Workflow executed successfully!")
print(f"Output: {result.output}")
if result.metadata:
print(f"Duration: {result.metadata.get('duration')} ms")
else:
print(f"❌ Workflow failed: {result.error}")
except SimStudioError as error:
print(f"SDK Error: {error} (Code: {error.code})")
except Exception as error:
print(f"Unexpected error: {error}")
def error_handling_example():
"""Example 7: Comprehensive error handling"""
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
try:
result = client.execute_workflow("your-workflow-id")
if result.success:
print("✅ Workflow executed successfully!")
print(f"Output: {result.output}")
return result
else:
print(f"❌ Workflow failed: {result.error}")
return result
except SimStudioError as error:
if error.code == "UNAUTHORIZED":
print("❌ Invalid API key")
elif error.code == "TIMEOUT":
print("⏱️ Workflow execution timed out")
elif error.code == "USAGE_LIMIT_EXCEEDED":
print("💳 Usage limit exceeded")
elif error.code == "INVALID_JSON":
print("📝 Invalid JSON in request body")
elif error.status == 404:
print("🔍 Workflow not found")
elif error.status == 403:
print("🚫 Workflow is not deployed")
else:
print(f"⚠️ Workflow error: {error}")
raise
except Exception as error:
print(f"💥 Unexpected error: {error}")
raise
if __name__ == "__main__":
print("🚀 Running Sim Python SDK Examples\n")
# Check if API key is set
if not os.getenv("SIM_API_KEY"):
print("❌ Please set SIM_API_KEY environment variable")
exit(1)
try:
print("1️⃣ Basic Example:")
basic_example()
print("\n✅ Basic example completed\n")
print("2️⃣ Input Example:")
with_input_example()
print("\n✅ Input example completed\n")
print("3️⃣ Status Example:")
status_example()
print("\n✅ Status example completed\n")
print("4️⃣ Context Manager Example:")
context_manager_example()
print("\n✅ Context manager example completed\n")
print("5️⃣ Batch Execution Example:")
batch_execution_example()
print("\n✅ Batch execution example completed\n")
print("6️⃣ Streaming Example:")
streaming_example()
print("\n✅ Streaming example completed\n")
print("7️⃣ Error Handling Example:")
error_handling_example()
print("\n✅ Error handling example completed\n")
except Exception as e:
print(f"\n💥 Example failed: {e}")
exit(1)
print("🎉 All examples completed successfully!")