Observed since 20 Oct, 22:48 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
AI Reliability Engineering for LLM Agents - Monitor hallucinations, latency, and throughput
A flexible hallucination detection system for LLM responses that works both with and without RAG (Retrieval Augmented Generation). Monitor truth quality, latency, and throughput for production LLM systems.
User Prompt + Response
↓
[ ⏱️ Latency Timer Start ]
↓
[ Embedding Drift Check ] → always active
[ Uncertainty Analysis ] → always active
[ Evidence Entailment ] → only if retrieved_docs
[ Factual Self-Check LLM ] → fallback when no evidence
↓
Weighted Fusion (0.4 factual + 0.4 drift + 0.2 uncertainty)
↓
[ ⏱️ Latency Timer End ]
[ 📊 Throughput Calculation ]
↓
→ truth metrics + reliability metrics
pip install agentops-client
That's it! You're ready to start monitoring your LLM agents.
Create a .env file or set environment variable:
export OPENAI_API_KEY=your_openai_api_key_here
Or in Python:
import os
os.environ['OPENAI_API_KEY'] = 'your_openai_api_key_here'
If you want to contribute or modify the code:
git clone https://github.com/ezazahamad2003/agentops.git
cd agentops
pip install -e .
from agentops import AgentOps
# Initialize the SDK
ops = AgentOps()
# Evaluate a single response
result = ops.evaluate(
prompt="Who discovered penicillin?",
response="Penicillin was discovered by Alexander Fleming in 1928."
)
print(f"Hallucinated: {result['hallucinated']}")
print(f"Latency: {result['latency_sec']}s")
Connect to our production backend for automatic metrics storage and analytics:
from agentops import AgentOps
# Initialize with production backend
ops = AgentOps(
api_key="your_api_key", # Get from /register endpoint
api_url="https://agentops-api-1081133763032.us-central1.run.app"
)
# Evaluations are automatically uploaded to backend
result = ops.evaluate(
prompt="What is AI?",
response="AI is artificial intelligence...",
model_name="gpt-4o-mini"
)
# Data is stored in Supabase for analytics! ✅
Get Your API Key:
curl -X POST https://agentops-api-1081133763032.us-central1.run.app/register \
-H "Content-Type: application/json" \
-d '{"name":"my_agent"}'
from agentops import AgentOps
ops = AgentOps()
# RAG Mode evaluation
result = ops.evaluate(
prompt="What are the side effects of aspirin?",
response="Aspirin causes stomach upset, nausea, and heartburn.",
retrieved_docs=[
"Common side effects include stomach upset and nausea.",
"Some people may experience allergic reactions."
]
)
print(result)
from agentops import AgentOps
ops = AgentOps()
# Start a monitoring session
ops.start_session()
# Run multiple evaluations
for prompt, response in your_test_cases:
result = ops.evaluate(prompt, response)
print(f"Latency: {result['latency_sec']}s")
# Get session statistics
stats = ops.end_session()
print(f"Total evaluations: {stats['total_evaluations']}")
print(f"Average throughput: {stats['throughput_qps']} req/sec")
from agentops import AgentOps
with AgentOps() as ops:
result = ops.evaluate(prompt, response)
# Session automatically closed after block
from agentops import detect_hallucination
# Direct function call (lower-level API)
result = detect_hallucination(prompt, response, retrieved_docs)
print(result)
{
# Truth Metrics
"semantic_drift": 0.22, # 0-1: semantic distance from prompt
"uncertainty": 0.0, # 0-1: uncertainty language score
"factual_support": 0.52, # 0-1: factual grounding score
"mode": "retrieved-doc entailment", # or "self-check"
"hallucination_probability": 0.57, # 0-1: overall score
"hallucinated": True, # True if probability > 0.45
# Reliability Metrics 🆕
"latency_sec": 2.34, # End-to-end evaluation time in seconds
"throughput_qps": 0.427 # Requests per second (queries per second)
}
| Mode | retrieved_docs | Truth Checks | Reliability Metrics |
|---|---|---|---|
| RAG mode | List of chunks | Semantic drift + entailment (evidence-based factuality) | Latency + Throughput (tracked) |
| No-RAG mode | None | Semantic drift + uncertainty + factual self-check (LLM) | Latency + Throughput (tracked) |
track_throughput=False): throughput = 1 / latencytrack_throughput=True): throughput = total_evaluations / total_timeRun the test suite:
pytest test_detector.py -v
Run example scenarios:
python examples.py
Semantic Drift (weight: 0.4)
Uncertainty (weight: 0.2)
Factual Support (weight: 0.4)
Edit the fusion weights in detector_flexible.py:
halluc_prob = round(0.4 * (1 - factual) + 0.4 * drift + 0.2 * uncert, 3)
# ^^^ ^^^ ^^^
# factual weight drift uncertainty
Change the threshold in the return statement:
"hallucinated": halluc_prob > 0.45 # Change 0.45 to desired threshold
# Single-run mode (throughput = 1/latency)
result = detect_hallucination(prompt, response, track_throughput=False)
# Batch mode (cumulative tracking)
result = detect_hallucination(prompt, response, track_throughput=True)
# Reset cumulative tracker
from detector_flexible import reset_throughput_tracker
reset_throughput_tracker()
# Get current stats
from detector_flexible import get_throughput_stats
stats = get_throughput_stats()
# Returns: {'total_evaluations': int, 'total_time_sec': float, 'throughput_qps': float}
prompt = "What are Ozempic side effects?"
docs = ["Common: nausea, vomiting", "Rare: pancreatitis"]
response = "Causes nausea and heart palpitations" # ⚠️ heart palpitations not in docs
result = detect_hallucination(prompt, response, docs)
# High hallucination probability due to unsupported claim
prompt = "Who invented the telephone?"
response = "Alexander Graham Bell invented the telephone."
result = detect_hallucination(prompt, response)
# Low hallucination probability - factually correct
prompt = "What's the weather like?"
response = "Maybe it's probably sunny, I'm not sure."
result = detect_hallucination(prompt, response)
# High uncertainty score detected
AgentOps(api_key=None, track_throughput=True)Initialize the AgentOps SDK client.
Parameters:
api_key (str, optional): API key for future cloud featurestrack_throughput (bool, default=True): Enable cumulative throughput trackingMethods:
evaluate(prompt, response, retrieved_docs=None)Evaluate an agent's response for hallucinations and reliability.
Returns: dict with truth and reliability metrics
metrics()Get current cumulative statistics.
Returns: {'total_evaluations': int, 'total_time_sec': float, 'throughput_qps': float}
reset_metrics()Reset throughput tracker for new session.
start_session()Start a new monitoring session with fresh metrics.
end_session()End current session and return final statistics.
Context Manager Support:
with AgentOps() as ops:
result = ops.evaluate(prompt, response)
detect_hallucination(prompt, response, retrieved_docs=None, track_throughput=True)Low-level detection function with reliability metrics.
Parameters:
prompt (str): Original user question/promptresponse (str): LLM's generated responseretrieved_docs (list[str], optional): Retrieved evidence chunks for RAG modetrack_throughput (bool, default=True): Enable cumulative throughput trackingReturns:
dict: Detection results with truth metrics and reliability metricsreset_throughput_tracker(): Reset cumulative throughput countersget_throughput_stats(): Get current throughput statisticsuncertainty_score(text): Calculate uncertainty language scoreMIT License - feel free to use in your projects!
Contributions welcome! Please test your changes with the test suite before submitting.
Built with ❤️ using OpenAI APIs
Download counts and popularity will appear here as the collector receives them.
| Version | Published | Direct dependencies | Open version |
|---|---|---|---|
| 0.2.2 | 2 Nov 2025 | 8 |
This describes our collected data; it is not a security assessment.
Observed since 20 Oct, 22:48 UTC
No superseded metadata states collected. Unchanged observations do not create new revisions.
package:cc45d6d21ed3b084682afb3e0ee996b7a21d69bbcf8eae55e07791299c813f03