initial commit
This commit is contained in:
commit
aaba8753ef
36 changed files with 3682 additions and 0 deletions
1
src/examples/__init__.py
Normal file
1
src/examples/__init__.py
Normal file
|
|
@ -0,0 +1 @@
|
|||
# Examples package
|
||||
178
src/examples/example_usage.py
Normal file
178
src/examples/example_usage.py
Normal file
|
|
@ -0,0 +1,178 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example usage of the Lolly AI API
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import asyncio
|
||||
from typing import Dict, Any
|
||||
from src.config import settings
|
||||
|
||||
# Configuration
|
||||
API_BASE_URL = "http://localhost:7310"
|
||||
|
||||
async def test_session_creation():
|
||||
"""Test session creation with configured agent"""
|
||||
print("Testing Session Creation...")
|
||||
print(f"Using configured agent ID: {settings.TALESTORM_AGENT_ID}")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/sessions")
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
session_id = data.get("session_id")
|
||||
print(f"✅ Session created: {session_id}")
|
||||
return session_id
|
||||
else:
|
||||
print(f"❌ Failed to create session: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"❌ Error creating session: {e}")
|
||||
return None
|
||||
|
||||
async def test_insurance_chat():
|
||||
"""Test the insurance chat endpoint with new format"""
|
||||
print("Testing Insurance Chat...")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
# First create a session
|
||||
session_id = await test_session_creation()
|
||||
|
||||
payload = {
|
||||
"message": "What does health insurance typically cover?",
|
||||
"session_id": session_id
|
||||
}
|
||||
|
||||
try:
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/insurance_chat", json=payload)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✅ Chat successful!")
|
||||
print(f"Session ID: {data['session_id']}")
|
||||
print(f"Answer: {data['answer']}")
|
||||
|
||||
# Show sources if any
|
||||
if data['sources']:
|
||||
print(f"Sources found: {len(data['sources'])}")
|
||||
for i, source in enumerate(data['sources']):
|
||||
print(f" Source {i+1}:")
|
||||
print(f" Plan: {source['plan_name']}")
|
||||
print(f" Chunk: {source['chunk_number']}")
|
||||
print(f" Content: {source['content_chunk'][:100]}...")
|
||||
else:
|
||||
print("No sources found (RAG not implemented yet)")
|
||||
|
||||
# Show history in detail
|
||||
print(f"\nHistory entries: {len(data['history'])}")
|
||||
for i, history_item in enumerate(data['history']):
|
||||
role_emoji = "👤" if history_item['role'] == "user" else "🤖"
|
||||
print(f" {role_emoji} {history_item['role'].upper()}: {history_item['message'][:80]}...")
|
||||
|
||||
# Show full message if it's short
|
||||
if len(history_item['message']) <= 80:
|
||||
print(f" Full message: {history_item['message']}")
|
||||
else:
|
||||
print(f"❌ Chat failed with status {response.status_code}")
|
||||
print(f"Error: {response.text}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error testing chat: {e}")
|
||||
|
||||
async def test_multiple_messages():
|
||||
"""Test sending multiple messages to the same session"""
|
||||
print("\nTesting Multiple Messages...")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
# Create a session
|
||||
session_id = await test_session_creation()
|
||||
if not session_id:
|
||||
print("❌ Could not create session for multiple message test")
|
||||
return
|
||||
|
||||
# Send multiple messages
|
||||
messages = [
|
||||
"What is health insurance?",
|
||||
"What types of coverage are available?",
|
||||
"How much does insurance typically cost?"
|
||||
]
|
||||
|
||||
for i, message in enumerate(messages, 1):
|
||||
print(f"\nMessage {i}: {message}")
|
||||
payload = {
|
||||
"message": message,
|
||||
"session_id": session_id
|
||||
}
|
||||
|
||||
try:
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/insurance_chat", json=payload)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f" ✅ Response: {data['answer'][:60]}...")
|
||||
print(f" 📝 History entries: {len(data['history'])}")
|
||||
|
||||
# Show the last few history items
|
||||
recent_history = data['history'][-4:] # Show last 4 items
|
||||
for item in recent_history:
|
||||
role_emoji = "👤" if item['role'] == "user" else "🤖"
|
||||
print(f" {role_emoji} {item['role']}: {item['message'][:40]}...")
|
||||
else:
|
||||
print(f" ❌ Failed: {response.status_code}")
|
||||
except Exception as e:
|
||||
print(f" ❌ Error: {e}")
|
||||
|
||||
async def test_estimation():
|
||||
"""Test the estimation endpoint"""
|
||||
print("Testing Insurance Estimation...")
|
||||
|
||||
payload = {
|
||||
"uid": "test-application-123",
|
||||
"applicants": [
|
||||
{
|
||||
"firstName": "John",
|
||||
"dob": "15/03/1985",
|
||||
"weight": 70,
|
||||
"heightFt": 5,
|
||||
"heightIn": 10,
|
||||
"applicant": 1
|
||||
}
|
||||
],
|
||||
"plans": [{"coverage": 1}],
|
||||
"phq": {
|
||||
"effectiveDate": "01/01/2024",
|
||||
"medications": [],
|
||||
"conditions": [],
|
||||
"issues": []
|
||||
},
|
||||
"income": 50000,
|
||||
"address": {}
|
||||
}
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/estimation", json=payload)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
print(f"✅ Estimation successful!")
|
||||
print(f"Application ID: {data['uid']}")
|
||||
print(f"Status: {data['status']}")
|
||||
else:
|
||||
print(f"❌ Estimation failed with status {response.status_code}")
|
||||
print(f"Error: {response.text}")
|
||||
except Exception as e:
|
||||
print(f"❌ Error testing estimation: {e}")
|
||||
|
||||
async def main():
|
||||
"""Run all tests"""
|
||||
print("🚀 Starting Lolly AI API Tests")
|
||||
print("=" * 50)
|
||||
|
||||
await test_insurance_chat()
|
||||
print("\n" + "=" * 50)
|
||||
await test_multiple_messages()
|
||||
print("\n" + "=" * 50)
|
||||
await test_estimation()
|
||||
|
||||
print("\n✅ All tests completed!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
149
src/examples/session_example.py
Normal file
149
src/examples/session_example.py
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Example of session management with Lolly AI
|
||||
"""
|
||||
|
||||
import httpx
|
||||
import asyncio
|
||||
from typing import Dict, Any
|
||||
|
||||
# Configuration
|
||||
API_BASE_URL = "http://localhost:7310"
|
||||
|
||||
async def demonstrate_session_management():
|
||||
"""Demonstrate session management functionality"""
|
||||
print("🔄 Session Management Demo")
|
||||
print("=" * 50)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
# Step 1: List available agents
|
||||
print("1. Listing available agents...")
|
||||
response = await client.get(f"{API_BASE_URL}/api/v1/agents")
|
||||
if response.status_code == 200:
|
||||
agents = response.json()["agents"]
|
||||
print(f" ✅ Found {len(agents)} agents")
|
||||
for agent in agents:
|
||||
print(f" - {agent.get('name', 'Unknown')} ({agent.get('model_name', 'Unknown')})")
|
||||
else:
|
||||
print(f" ❌ Failed to list agents: {response.status_code}")
|
||||
|
||||
# Step 2: Create a new session
|
||||
print("\n2. Creating a new session...")
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/sessions")
|
||||
if response.status_code == 200:
|
||||
session_data = response.json()
|
||||
session_id = session_data["session_id"]
|
||||
print(f" ✅ Session created: {session_id}")
|
||||
else:
|
||||
print(f" ❌ Failed to create session: {response.status_code}")
|
||||
return
|
||||
|
||||
# Step 3: Get session details
|
||||
print(f"\n3. Getting session details for {session_id}...")
|
||||
response = await client.get(f"{API_BASE_URL}/api/v1/sessions/{session_id}")
|
||||
if response.status_code == 200:
|
||||
session_details = response.json()
|
||||
print(f" ✅ Session details retrieved")
|
||||
print(f" - Agent ID: {session_details.get('agent_id', 'Unknown')}")
|
||||
print(f" - Created: {session_details.get('created_at', 'Unknown')}")
|
||||
else:
|
||||
print(f" ❌ Failed to get session details: {response.status_code}")
|
||||
|
||||
# Step 4: Send a chat message using the session
|
||||
print(f"\n4. Sending chat message using session {session_id}...")
|
||||
chat_payload = {
|
||||
"message": "Hello! I have a question about health insurance coverage.",
|
||||
"session_id": session_id
|
||||
}
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/insurance_chat", json=chat_payload)
|
||||
if response.status_code == 200:
|
||||
chat_response = response.json()
|
||||
print(f" ✅ Chat message sent successfully")
|
||||
print(f" - Response: {chat_response['answer'][:100]}...")
|
||||
else:
|
||||
print(f" ❌ Failed to send chat message: {response.status_code}")
|
||||
|
||||
# Step 5: List all sessions
|
||||
print(f"\n5. Listing all sessions...")
|
||||
response = await client.get(f"{API_BASE_URL}/api/v1/sessions")
|
||||
if response.status_code == 200:
|
||||
sessions = response.json()["sessions"]
|
||||
print(f" ✅ Found {len(sessions)} sessions")
|
||||
for session in sessions:
|
||||
print(f" - Session {session.get('id', 'Unknown')} (Agent: {session.get('agent_id', 'Unknown')})")
|
||||
else:
|
||||
print(f" ❌ Failed to list sessions: {response.status_code}")
|
||||
|
||||
# Step 6: Send another message to the same session
|
||||
print(f"\n6. Sending follow-up message to session {session_id}...")
|
||||
follow_up_payload = {
|
||||
"message": "Can you tell me more about dental coverage?",
|
||||
"session_id": session_id
|
||||
}
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/insurance_chat", json=follow_up_payload)
|
||||
if response.status_code == 200:
|
||||
chat_response = response.json()
|
||||
print(f" ✅ Follow-up message sent successfully")
|
||||
print(f" - Response: {chat_response['answer'][:100]}...")
|
||||
print(f" - History length: {len(chat_response['history'])}")
|
||||
else:
|
||||
print(f" ❌ Failed to send follow-up message: {response.status_code}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error during session management demo: {e}")
|
||||
|
||||
async def demonstrate_session_persistence():
|
||||
"""Demonstrate session persistence across multiple requests"""
|
||||
print("\n🔄 Session Persistence Demo")
|
||||
print("=" * 50)
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
try:
|
||||
# Create a session
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/sessions")
|
||||
if response.status_code != 200:
|
||||
print("❌ Failed to create session for persistence demo")
|
||||
return
|
||||
|
||||
session_id = response.json()["session_id"]
|
||||
print(f"Created session: {session_id}")
|
||||
|
||||
# Send multiple messages to the same session
|
||||
messages = [
|
||||
"What is health insurance?",
|
||||
"What types of coverage are available?",
|
||||
"How much does insurance typically cost?",
|
||||
"What is a deductible?"
|
||||
]
|
||||
|
||||
for i, message in enumerate(messages, 1):
|
||||
print(f"\nMessage {i}: {message}")
|
||||
payload = {
|
||||
"message": message,
|
||||
"session_id": session_id
|
||||
}
|
||||
|
||||
response = await client.post(f"{API_BASE_URL}/api/v1/insurance_chat", json=payload)
|
||||
if response.status_code == 200:
|
||||
chat_response = response.json()
|
||||
print(f" Response: {chat_response['answer'][:80]}...")
|
||||
print(f" History entries: {len(chat_response['history'])}")
|
||||
else:
|
||||
print(f" ❌ Failed to send message: {response.status_code}")
|
||||
|
||||
print(f"\n✅ Session persistence demo completed for session: {session_id}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error during session persistence demo: {e}")
|
||||
|
||||
async def main():
|
||||
"""Run session management demonstrations"""
|
||||
await demonstrate_session_management()
|
||||
await demonstrate_session_persistence()
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("✅ Session management demonstrations completed!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
80
src/examples/test_agent_id.py
Normal file
80
src/examples/test_agent_id.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify TALESTORM_AGENT_ID usage
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from src.services.session_service import session_service
|
||||
from src.config import settings
|
||||
|
||||
async def test_agent_id_usage():
|
||||
"""Test that the configured agent ID is being used"""
|
||||
print("Testing TALESTORM_AGENT_ID Usage...")
|
||||
print("=" * 50)
|
||||
|
||||
print(f"Configured Agent ID: {settings.TALESTORM_AGENT_ID}")
|
||||
print(f"Session Service Agent ID: {session_service.agent_id}")
|
||||
|
||||
# Test session creation
|
||||
print("\nCreating session with configured agent...")
|
||||
session_id = await session_service.create_session()
|
||||
|
||||
if session_id:
|
||||
print(f"✅ Session created: {session_id}")
|
||||
|
||||
# Get session details to verify agent
|
||||
session_details = await session_service.get_session(session_id)
|
||||
if session_details:
|
||||
print(f"Session Agent ID: {session_details.get('agent_id')}")
|
||||
print(f"Session Organization ID: {session_details.get('organization_id')}")
|
||||
else:
|
||||
print("⚠️ Could not retrieve session details")
|
||||
else:
|
||||
print("❌ Failed to create session")
|
||||
|
||||
# Test listing agents
|
||||
print("\nListing available agents...")
|
||||
agents = await session_service.list_agents()
|
||||
if agents:
|
||||
print(f"✅ Found {len(agents)} agents:")
|
||||
for i, agent in enumerate(agents, 1):
|
||||
print(f" {i}. {agent.get('name', 'Unknown')} (ID: {agent.get('id')})")
|
||||
|
||||
# Highlight the configured agent
|
||||
if str(agent.get('id')) == settings.TALESTORM_AGENT_ID:
|
||||
print(f" ⭐ This is the configured agent!")
|
||||
else:
|
||||
print("❌ No agents found")
|
||||
|
||||
print("\n✅ Agent ID test completed!")
|
||||
|
||||
async def test_agent_validation():
|
||||
"""Test that the configured agent exists and is accessible"""
|
||||
print("\nTesting Agent Validation...")
|
||||
print("=" * 50)
|
||||
|
||||
if not settings.TALESTORM_AGENT_ID:
|
||||
print("❌ TALESTORM_AGENT_ID not configured")
|
||||
return
|
||||
|
||||
# Try to get the configured agent
|
||||
agent = await session_service.get_default_agent()
|
||||
if agent:
|
||||
print(f"✅ Configured agent found:")
|
||||
print(f" Name: {agent.get('name', 'Unknown')}")
|
||||
print(f" ID: {agent.get('id')}")
|
||||
print(f" Model: {agent.get('model_name', 'Unknown')}")
|
||||
print(f" Provider: {agent.get('model_provider', 'Unknown')}")
|
||||
print(f" RAG Enabled: {agent.get('enable_rag_search', False)}")
|
||||
else:
|
||||
print("❌ Configured agent not found or not accessible")
|
||||
|
||||
print("\n✅ Agent validation completed!")
|
||||
|
||||
async def main():
|
||||
"""Run all tests"""
|
||||
await test_agent_id_usage()
|
||||
await test_agent_validation()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(main())
|
||||
124
src/examples/test_history_parsing.py
Normal file
124
src/examples/test_history_parsing.py
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test script to verify chat history parsing with actual talestorm-ai format
|
||||
"""
|
||||
|
||||
from src.services.chat_service import ChatService
|
||||
from src.api.v1.models import HistoryItem
|
||||
|
||||
# Sample data from talestorm-ai
|
||||
sample_history = [
|
||||
{
|
||||
"id": "45d3e5f0-21cf-47b3-8c24-0d273107ab7f",
|
||||
"chat_session_id": "f250bb60-d619-4802-914f-0594d2a52bfa",
|
||||
"content": [
|
||||
{
|
||||
"parts": [
|
||||
{
|
||||
"content": "hi",
|
||||
"timestamp": "2025-07-25T09:49:29.412466Z",
|
||||
"part_kind": "user-prompt"
|
||||
}
|
||||
],
|
||||
"instructions": "You are an expert insurance assistant. You may only answer questions about insurance plans, coverage, benefits, and related terms. If asked anything outside that domain, reply: 'I'm sorry, I can only answer insurance-related questions.'",
|
||||
"kind": "request"
|
||||
},
|
||||
{
|
||||
"parts": [
|
||||
{
|
||||
"content": "Hello! How can I assist you with your insurance questions today?",
|
||||
"part_kind": "text"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"requests": 1,
|
||||
"request_tokens": 137,
|
||||
"response_tokens": 14,
|
||||
"total_tokens": 151,
|
||||
"details": {
|
||||
"accepted_prediction_tokens": 0,
|
||||
"audio_tokens": 0,
|
||||
"reasoning_tokens": 0,
|
||||
"rejected_prediction_tokens": 0,
|
||||
"cached_tokens": 0
|
||||
}
|
||||
},
|
||||
"model_name": "gpt-4.1-mini-2025-04-14",
|
||||
"timestamp": "2025-07-25T09:49:30Z",
|
||||
"kind": "response",
|
||||
"vendor_details": None,
|
||||
"vendor_id": "chatcmpl-Bx9LOZPgBbHOblSUd6LcuV3qIYEwz"
|
||||
}
|
||||
],
|
||||
"created_at": "2025-07-25T09:40:20.797430"
|
||||
}
|
||||
]
|
||||
|
||||
def parse_history_manually(messages):
|
||||
"""Manually parse the history to test our logic"""
|
||||
history = []
|
||||
|
||||
for message in messages:
|
||||
content = message.get("content", [])
|
||||
|
||||
for item in content:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
|
||||
kind = item.get("kind", "")
|
||||
|
||||
# Handle request messages (user input)
|
||||
if kind == "request":
|
||||
parts = item.get("parts", [])
|
||||
for part in parts:
|
||||
if part.get("part_kind") == "user-prompt":
|
||||
history.append(HistoryItem(
|
||||
role="user",
|
||||
message=part.get("content", "")
|
||||
))
|
||||
|
||||
# Handle response messages (assistant output)
|
||||
elif kind == "response":
|
||||
parts = item.get("parts", [])
|
||||
for part in parts:
|
||||
if part.get("part_kind") == "text":
|
||||
history.append(HistoryItem(
|
||||
role="assistant",
|
||||
message=part.get("content", "")
|
||||
))
|
||||
|
||||
return history
|
||||
|
||||
def test_history_parsing():
|
||||
"""Test the history parsing logic"""
|
||||
print("Testing History Parsing...")
|
||||
print("=" * 50)
|
||||
|
||||
# Parse the sample history
|
||||
history = parse_history_manually(sample_history)
|
||||
|
||||
print(f"Found {len(history)} history items:")
|
||||
for i, item in enumerate(history, 1):
|
||||
print(f" {i}. {item.role}: {item.message}")
|
||||
|
||||
# Verify the expected results
|
||||
expected_user_message = "hi"
|
||||
expected_assistant_message = "Hello! How can I assist you with your insurance questions today?"
|
||||
|
||||
if len(history) == 2:
|
||||
if history[0].role == "user" and history[0].message == expected_user_message:
|
||||
print("✅ User message parsed correctly")
|
||||
else:
|
||||
print("❌ User message parsing failed")
|
||||
|
||||
if history[1].role == "assistant" and history[1].message == expected_assistant_message:
|
||||
print("✅ Assistant message parsed correctly")
|
||||
else:
|
||||
print("❌ Assistant message parsing failed")
|
||||
else:
|
||||
print(f"❌ Expected 2 history items, got {len(history)}")
|
||||
|
||||
print("\n✅ History parsing test completed!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_history_parsing()
|
||||
Loading…
Add table
Add a link
Reference in a new issue