Overview
The create_event
function creates a new event within the current active step. Events represent individual actions or API calls within a step. While LLM calls are automatically tracked as events when using instrumented providers, you can also create custom events manually.
Syntax
lai.create_event(
step_id: Optional[str] = None,
description: Optional[str] = None,
result: Optional[str] = None,
cost_added: Optional[float] = None,
model: Optional[str] = None,
screenshots: Optional[List[str]] = None
) -> str
Parameters
The ID of the step to create the event in. If not provided, uses the current active step.
Description of what this event represents or what action was taken.
The result or outcome of the event.
The cost incurred by this event (e.g., API costs, compute costs).
The model or service used for this event (e.g., “gpt-4”, “custom-model”).
List of screenshots associated with this event. Each screenshot should be provided as a file path (which will be read and uploaded) or as base64-encoded image data.
Returns
Returns the event ID as a string.
Examples
Basic Manual Event
import lucidicai as lai
lai.init(session_name="Custom Processing")
# Create a step
lai.create_step(
state="Processing data",
action="Run custom analysis"
)
# Create manual events for non-LLM operations
event_id = lai.create_event(
description="Database query executed",
result="Retrieved 1,245 records",
cost_added=0.0001 # Database query cost
)
# Another event
lai.create_event(
description="Data validation completed",
result="All records passed validation",
model="custom-validator-v2"
)
lai.end_step()
Tracking Custom Model Calls
import lucidicai as lai
import requests
lai.init(session_name="Custom Model Integration")
lai.create_step(state="Using proprietary model", action="Generate predictions")
# Make custom API call
response = requests.post(
"https://api.internal.com/model/predict",
json={"data": input_data}
)
# Track it as an event
lai.create_event(
description="Called proprietary prediction model",
result=f"Predictions generated with confidence: {response.json()['confidence']}",
cost_added=0.05, # Custom model cost
model="internal-predictor-v3"
)
lai.end_step()
Multi-Event Workflow
import lucidicai as lai
from openai import OpenAI
lai.init(session_name="Multi-Stage Processing", providers=["openai"])
lai.create_step(
state="Complex document analysis",
action="Extract and analyze information"
)
# Event 1: Document parsing (manual event)
lai.create_event(
description="Parse PDF document",
result="Extracted 50 pages of text",
model="pdf-parser"
)
# Event 2: LLM call (automatically tracked)
client = OpenAI()
summary = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": f"Summarize: {document_text}"}]
)
# Event 3: Custom analysis (manual event)
lai.create_event(
description="Sentiment analysis on summary",
result="Positive sentiment (0.85 score)",
model="sentiment-analyzer"
)
# Event 4: Image processing with screenshots
screenshot_paths = save_processed_images(document_images) # Returns list of file paths
lai.create_event(
description="Extracted and analyzed document images",
result=f"Processed {len(screenshot_paths)} images",
screenshots=screenshot_paths # List of image file paths
)
lai.end_step()
Error Tracking
import lucidicai as lai
lai.init(session_name="Error Handling Demo")
lai.create_step(state="Processing user request", action="Execute workflow")
try:
# Attempt operation
result = risky_operation()
lai.create_event(
description="Operation completed successfully",
result=str(result)
)
except Exception as e:
# Track error as event
lai.create_event(
description="Operation failed",
result=f"Error: {type(e).__name__}: {str(e)}",
model="risky-operation-v1"
)
# Still end step properly
lai.end_step(
eval_score=0.0,
eval_description="Step failed due to error"
)
raise
Cost Tracking Example
import lucidicai as lai
lai.init(session_name="Cost Analysis")
lai.create_step(state="Running expensive operations", action="Process with multiple services")
total_cost = 0.0
# Track various service costs
services = [
("translation-api", 0.01),
("image-recognition", 0.02),
("data-enrichment", 0.005)
]
for service_name, cost in services:
result = call_service(service_name)
lai.create_event(
description=f"Called {service_name}",
result=result,
cost_added=cost,
model=service_name
)
total_cost += cost
lai.end_step(
eval_description=f"Total cost: ${total_cost:.3f}"
)
Notes
- Events can only be created within an active (not ended) step
- LLM calls through instrumented providers create events automatically
- Manual events are useful for tracking non-LLM operations
- Event IDs can be used with
update_event()
and end_event()
- Screenshots in events are useful for visual debugging
Error Handling
from lucidicai.errors import InvalidOperationError
try:
# This will fail if no step is active
lai.create_event(description="Some event")
except InvalidOperationError:
print("No active step - create a step first")
# Create step first
lai.create_step(state="Ready for events")
lai.create_event(description="Now this works")
Best Practices
- Descriptive Events: Provide clear descriptions of what happened
- Cost Tracking: Include costs for budget monitoring
- Model Attribution: Specify which model/service was used
- Error Events: Track failures as events for debugging
- Visual Context: Include screenshots for UI/visual operations
See Also