HiAgent SDK
A Python SDK for interacting with HiAgent Workflow API. Execute and monitor AI workflows with ease.
Features
- Simple API: Easy-to-use client interface for workflow execution
- HTTP Client: Built on httpx for efficient HTTP requests with retry logic
- Robust Error Handling: Comprehensive error handling with custom exceptions
- Type Safety: Full type hints and Pydantic models
- Configurable: Flexible configuration via environment variables or parameters
- Proxy Server: Built-in FastAPI proxy server with API key authentication
- Logging: Built-in logging with loguru
Installation
# Install from source
pip install -e .
# Or using uv (recommended for development)
uv pip install -e .
Quick Start
Basic Usage
from hiagent_sdk import HiAgentClient, RunWorkflowRequest, QueryWorkflowRequest, WorkflowStatus
# Initialize client with direct parameters (Recommended)
client = HiAgentClient(
api_key="your-api-key",
base_url="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1"
)
# Create workflow request
request = RunWorkflowRequest(
InputData={"prompt": "Your input data"},
UserID="your_user_id",
NoDebug=True
)
# Run workflow
response = client.run_workflow(request)
print(f"Workflow started: {response.runId}")
# Query workflow status
query_request = QueryWorkflowRequest(
RunID=response.runId,
UserID="your_user_id"
)
status_response = client.query_workflow(query_request)
print(f"Status: {status_response.status}")
Environment Variables Configuration
# Set environment variables
# HIAGENT_API_KEY="your-api-key"
# HIAGENT_BASE_URL="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1"
# HIAGENT_TIMEOUT=30
# HIAGENT_MAX_RETRIES=3
# Initialize client (will load from environment)
client = HiAgentClient()
Advanced Usage with Polling
from hiagent_sdk import HiAgentClient, RunWorkflowRequest, WorkflowStatus
import time
client = HiAgentClient(
api_key="your-api-key",
base_url="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1"
)
# Start workflow
request = RunWorkflowRequest(
InputData={"prompt": "Create a video about space exploration"},
UserID="user123",
NoDebug=True
)
response = client.run_workflow(request)
print(f"Workflow started: {response.runId}")
# Wait for completion with built-in polling
final_response = client.wait_for_completion(
execution_id=response.runId,
user_id="user123",
timeout=600.0, # 10 minutes
poll_interval=2.0 # Poll every 2 seconds
)
if final_response.status == WorkflowStatus.SUCCESS:
print("Workflow completed successfully!")
print(f"Output: {final_response.output}")
else:
print(f"Workflow failed: {final_response.message}")
Configuration
The SDK can be configured via environment variables or programmatically:
Environment Variables
export HIAGENT_API_KEY="your-api-key"
export HIAGENT_BASE_URL="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1"
export HIAGENT_TIMEOUT=30
export HIAGENT_MAX_RETRIES=3
export HIAGENT_LOG_LEVEL=INFO
Programmatic Configuration
from hiagent_sdk import HiAgentClient
client = HiAgentClient(
api_key="your-api-key",
base_url="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1",
timeout=30.0,
max_retries=3
)
Proxy Server
The SDK includes a FastAPI-based proxy server that provides API key authentication and forwards requests to the HiAgent service.
Running the Proxy Server
# Using the run script
python run_proxy.py
# Or directly
python -m src.proxy
# With custom configuration
PROXY_HOST=0.0.0.0 PROXY_PORT=8080 python run_proxy.py
Proxy Server Endpoints
GET /health- Health check endpointPOST /api/v1/workflow/run- Run workflow asynchronouslyPOST /api/v1/workflow/query- Query workflow statusPOST /api/v1/workflow/run-sync- Run workflow synchronously with polling
Using the Proxy Server
import requests
# Run workflow via proxy
response = requests.post(
"http://localhost:8000/api/v1/workflow/run",
headers={"Apikey": "your-api-key"},
json={
"InputData": {"prompt": "Your input"},
"UserID": "user123",
"NoDebug": True
}
)
run_id = response.json()["runId"]
# Query status via proxy
status_response = requests.post(
"http://localhost:8000/api/v1/workflow/query",
headers={"Apikey": "your-api-key"},
json={
"RunID": run_id,
"UserID": "user123"
}
)
Error Handling
The SDK provides comprehensive error handling:
from hiagent_sdk import (
HiAgentClient,
HiAgentClientError,
WorkflowExecutionError,
WorkflowTimeoutError
)
from hiagent_sdk.utils import HTTPRequestError
client = HiAgentClient(
api_key="your-api-key",
base_url="https://hiagent-byteplus.volcenginepaas.com/api/proxy/api/v1"
)
try:
request = RunWorkflowRequest(
InputData={"prompt": "Create a video"},
UserID="user123",
NoDebug=True
)
response = client.run_workflow(request)
# Wait for completion with custom timeout
final_response = client.wait_for_completion(
execution_id=response.runId,
user_id="user123",
timeout=60 # Custom timeout
)
except WorkflowTimeoutError:
print("Workflow execution timed out")
except WorkflowExecutionError as e:
print(f"Workflow execution failed: {e}")
except HTTPRequestError as e:
print(f"HTTP request failed: {e.status_code} - {e}")
except HiAgentClientError as e:
print(f"Client error: {e}")
Workflow Results
The SDK provides structured access to workflow results:
from hiagent_sdk import HiAgentClient, QueryWorkflowRequest, WorkflowStatus
client = HiAgentClient()
# Query workflow result
query_request = QueryWorkflowRequest(RunID="your_run_id", UserID="user123")
result = client.query_workflow(query_request)
# Check workflow status
if result.status == WorkflowStatus.SUCCESS:
print("Workflow completed successfully!")
# Access workflow nodes
if result.nodes:
for node_id, node_data in result.nodes.items():
print(f"Node {node_id}: {node_data}")
# Access final output
if result.output:
print(f"Final output: {result.output}")
# Access execution steps
if result.steps:
print(f"Execution steps: {result.steps}")
# Access cost information
print(f"Total cost: {result.costMs}ms, {result.costToken} tokens")
elif result.status == WorkflowStatus.FAILED:
print(f"Workflow failed: {result.message}")
elif result.status == WorkflowStatus.PROCESSING:
print("Workflow is still processing...")
Development
Setup Development Environment
# Clone the repository
git clone https://github.com/hiagent/hiagent-sdk.git
cd hiagent-sdk
# Create virtual environment using uv (recommended)
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
# Install development dependencies
uv pip install -e ".[dev]"
Running Tests
# Run all tests
pytest
# Run with coverage
pytest --cov=src --cov-report=html
# Run specific test file
pytest tests/test_client.py
# Run integration tests
pytest -m integration
Code Quality
# Format code
black src tests
isort src tests
# Lint code
flake8 src tests
mypy src
# Run all quality checks
pre-commit run --all-files
API Reference
HiAgentClient
Main client class for interacting with HiAgent API.
Constructor
HiAgentClient(
api_key: Optional[str] = None,
base_url: Optional[str] = None,
timeout: Optional[float] = None,
max_retries: Optional[int] = None,
user_id: Optional[str] = None
)
Methods
run_workflow(request: RunWorkflowRequest) -> RunWorkflowResponse: Start workflow executionquery_workflow(request: QueryWorkflowRequest) -> QueryWorkflowResponse: Query workflow statuswait_for_completion(execution_id: str, user_id: str = "", timeout: Optional[float] = None, poll_interval: Optional[float] = None) -> QueryWorkflowResponse: Wait for workflow completion with polling
Models
WorkflowStatus
PENDING: Workflow is pending executionPROCESSING: Workflow is currently runningSUCCESS: Workflow completed successfullyFAILED: Workflow execution failed
NodeStatus
TO_START: Node is waiting to startPROCESSING: Node is currently processingSUCCESS: Node completed successfullyFAILED: Node execution failedSTOPPED: Node execution was stopped
NodeType
REMOTE_TOOL: Remote tool execution nodePY: Python code execution nodeLOOP: Loop control nodeSTART: Workflow start nodeLLM: Large Language Model nodeEND: Workflow end nodeBATCH: Batch processing nodeCONDITION: Conditional logic nodeVARIABLES_MERGE: Variable merging nodeHTTP_REQUEST: HTTP request node
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Make your changes
- Add tests for your changes
- Run the test suite (
pytest) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
- Documentation: https://hiagent-sdk.readthedocs.io
- Issues: https://github.com/hiagent/hiagent-sdk/issues
- Discussions: https://github.com/hiagent/hiagent-sdk/discussions
Metadata
Release files for hiagent-sdk 0.1.3
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| hiagent_sdk-0.1.3.tar.gz | 12.0 kB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| hiagent_sdk-0.1.3-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 26.8 kB
Release files / hiagent_sdk-0.1.3.tar.gz
| Download URL | hiagent_sdk-0.1.3.tar.gz |
|---|---|
| Size | 12.0 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
953a9faf24539ebb29b8566e63d475043dbd9fcc05879a1b167a09b9f283bf84
|
|
BLAKE2b-256 checksum How to use checksums |
10063be8b47d93e1a0758399f004d657f6d12c29b74ea5a2f3b574cc675f4308
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.14
|
Release files / hiagent_sdk-0.1.3-py3-none-any.whl
| Download URL | hiagent_sdk-0.1.3-py3-none-any.whl |
|---|---|
| Size | 14.8 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
3c48ce6f211c45f85ffb1e2f7a75bd52ff22be0cb1bc668135c6a24105488e52
|
|
BLAKE2b-256 checksum How to use checksums |
e65444c8d97b59a863f1e9327357e72b4915c6d1d56b6ae772a8514651b2a7d3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.8.14
|