Implementation:24mlight A Share investment Agent workflow run
| Knowledge Sources | |
|---|---|
| Domains | Backend_Engineering |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Concrete context manager for registering and completing workflow runs in the global API state with automatic error handling, provided by the A_Share_investment_Agent repository.
Description
The workflow_run context manager wraps the execution of run_hedge_fund to ensure run lifecycle management. On entry, it calls api_state.register_run(run_id) which creates a RunInfo and sets the current_run_id. On normal exit, it calls api_state.complete_run(run_id, "completed"). On exception, it calls api_state.complete_run(run_id, "error") and re-raises.
This is a Pattern Doc — it documents a context manager interface used by both the backend API service and the CLI launcher.
Usage
Import when you need to:
- Wrap workflow execution with automatic run tracking
- Ensure runs are marked as completed or error in api_state
Code Reference
Source Location
- Repository: A_Share_investment_Agent
- File: backend/utils/context_managers.py
- Lines: L1-30
Signature
from contextlib import contextmanager
@contextmanager
def workflow_run(run_id: str):
"""
Workflow run context manager.
Usage:
with workflow_run(run_id):
# Execute workflow
"""
api_state.register_run(run_id)
try:
yield
api_state.complete_run(run_id, "completed")
except Exception as e:
api_state.complete_run(run_id, "error")
raise
Import
from backend.utils.context_managers import workflow_run
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| run_id | str | Yes | Unique run identifier |
Outputs
| Name | Type | Description |
|---|---|---|
| return | ContextManager | Yields control, manages run lifecycle |
Usage Examples
In Backend Service
from backend.utils.context_managers import workflow_run
from src.main import run_hedge_fund
with workflow_run(run_id):
result = run_hedge_fund(
run_id=run_id,
ticker="002848",
start_date=None,
end_date=None,
portfolio={"cash": 100000, "stock": 0},
show_reasoning=True,
)
# Run is automatically marked "completed" or "error" in api_state
In CLI Launcher
with workflow_run(run_id):
result = run_hedge_fund(
ticker=args.ticker,
start_date=start_date.strftime('%Y-%m-%d'),
end_date=end_date.strftime('%Y-%m-%d'),
portfolio=portfolio,
show_reasoning=args.show_reasoning,
)