Implementation:24mlight A Share investment Agent log llm interaction
| Knowledge Sources | |
|---|---|
| Domains | Observability, LLM_Infrastructure |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Concrete tool for recording LLM request/response pairs with caller info and timestamps via a decorator factory pattern, provided by the A_Share_investment_Agent repository.
Description
The log_llm_interaction function serves as a decorator factory that wraps LLM calls to record request/response pairs. It operates in two modes:
- Decorator factory mode:
log_llm_interaction(state)(get_chat_completion)(messages)— extracts agent_name and run_id from state, records formatted request/response to api_state and BaseLogStorage.
- Direct call mode:
log_llm_interaction("agent_name")(request_data, response_data)— backward-compatible direct logging.
In decorator factory mode, it captures caller frame info (function name, file, line), extracts messages and model from arguments, formats request/response with both structured and raw representations, and optionally writes file-level trace logs when trace_dir is set.
Usage
Import when you need to:
- Log LLM interactions for debugging and compliance
- Record request/response pairs with agent context
Code Reference
Source Location
- Repository: A_Share_investment_Agent
- File: src/utils/api_utils.py
- Lines: L102-270
Signature
def log_llm_interaction(state):
"""
Record LLM interactions decorator factory.
Usage modes:
1. Decorator factory: log_llm_interaction(state)(get_chat_completion)(messages)
2. Direct call: log_llm_interaction("agent_name")(request_data, response_data)
"""
Import
from src.utils.api_utils import log_llm_interaction
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| state | str | Yes | Agent state dict (decorator mode) or agent name string (direct mode) |
Outputs
| Name | Type | Description |
|---|---|---|
| return | Callable | Decorator or direct logger function |
Usage Examples
Wrapping LLM Calls (used by all agents)
from src.utils.api_utils import log_llm_interaction
from src.tools.openrouter_config import get_chat_completion
# In an agent function with state available:
messages = [
{"role": "system", "content": "You are a financial analyst."},
{"role": "user", "content": "Analyze stock 002848."},
]
# Wrap with logging
result = log_llm_interaction(state)(get_chat_completion)(messages)
# Records: caller info, messages, model, response, timestamp
# Stores in: api_state, BaseLogStorage, optional trace file