File size: 2,396 Bytes
28fad98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
from google.genai import types

async def display_state(
    session_service, app_name, user_id, session_id, label="Current State"
):
    """Display the current session state in a formatted way."""
    try:
        session = await session_service.get_session(
            app_name=app_name, user_id=user_id, session_id=session_id
        )

        # Format the output with clear sections
        print(f"\n{'-' * 10} {label} {'-' * 10}")

        # Handle the user name
        user_name = session.state.get("user:name", "Unknown")
        print(f"User: {user_name}")

        balance = session.state.get("user:balance", 0)
        print(f"Balance: {balance}")

        language = session.state.get("user:language", 0)
        print(f"Language: {language}")

        currency = session.state.get("user:currency", 0)
        print(f"Currency: {currency}")

        # Handle reminders
        goals = session.state.get("user:financial_goals", [])
        if goals:
            print("Goals :")
            for idx, goal in enumerate(goals, 1):
                print(f"  {idx}. {goal}")
        else:
            print("Goals: None")

        print("-" * (22 + len(label)))
    except Exception as e:
        print(f"Error displaying state: {e}")

async def process_agent_response(event):
    
    print(f"Event ID: {event.id}, Author: {event.author}")

    final_response = None
    if event.is_final_response():
        if (
            event.content and event.content.parts
        ):
            final_response = event.content.parts[0].text

    return final_response

async def call_agent_async(query: str, runner, user_id, session_id):

    content = types.Content(role="user", parts=[types.Part(text=query)])

    final_response_text = None

    # Display state before processing
    await display_state(
        runner.session_service,
        runner.app_name,
        user_id,
        session_id,
        "State BEFORE processing",
    )

    async for event in runner.run_async(user_id=user_id, session_id=session_id, new_message=content):

        response = await process_agent_response(event)
        if response:
            final_response_text = response

    # Display state after processing
    await display_state(
        runner.session_service,
        runner.app_name,
        user_id,
        session_id,
        "State AFTER processing",
    )

    return final_response_text