Skip to main content

Chat Metrics

Chat automatically tracks costs, tokens, and session metrics for monitoring and analytics.

Cost Tracking

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)

    await chat.invoke("Hello")
    await chat.invoke("How are you?")

    # Access cost metrics
    print(f"Total cost: ${chat.total_cost:.4f}")
    print(f"Input tokens: {chat.input_tokens}")
    print(f"Output tokens: {chat.output_tokens}")


if __name__ == "__main__":
    asyncio.run(main())

Detailed Cost History

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)

    await chat.invoke("Hello")

    # Get detailed cost history
    cost_history = chat.get_cost_history()
    for entry in cost_history:
        print(f"Time: {entry['timestamp']}")
        print(f"Cost: ${entry['estimated_cost']:.4f}")
        print(f"Model: {entry['model_name']}")


if __name__ == "__main__":
    asyncio.run(main())

Session Metrics

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)

    await chat.invoke("Hello")

    # Get comprehensive session metrics
    metrics = chat.get_session_metrics()
    print(f"Duration: {metrics.duration:.1f}s")
    print(f"Messages: {metrics.message_count}")
    print(f"Avg response time: {metrics.average_response_time:.2f}s")
    print(f"Messages/min: {metrics.messages_per_minute:.1f}")


if __name__ == "__main__":
    asyncio.run(main())

Session Summary

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)

    await chat.invoke("Hello")
    await chat.invoke("How are you?")

    # Get human-readable summary
    summary = chat.get_session_summary()
    print(summary)


if __name__ == "__main__":
    asyncio.run(main())

Session Duration and Activity

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)

    await chat.invoke("Hello")

    # Session timing
    print(f"Session duration: {chat.session_duration:.1f}s")
    print(f"Last activity: {chat.last_activity:.1f}s ago")


if __name__ == "__main__":
    asyncio.run(main())