-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.py
More file actions
110 lines (95 loc) · 3.99 KB
/
helpers.py
File metadata and controls
110 lines (95 loc) · 3.99 KB
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import yaml
import os
import sys
import subprocess
def setup_credentials():
"""
Ensures Google Application Default Credentials (ADC) are configured.
Checks for local project credentials, then environment variables,
and offers to run setup if missing.
"""
root_dir = os.path.dirname(os.path.abspath(__file__))
local_creds = os.path.join(root_dir, "application_default_credentials.json")
# 1. Check if already set in environment
if os.environ.get("GOOGLE_APPLICATION_CREDENTIALS"):
return
# 2. Prefer local credentials if they exist (portable)
if os.path.exists(local_creds):
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = local_creds
return
# 3. Check default gcloud location (standard)
default_path = os.path.expanduser("~/.config/gcloud/application_default_credentials.json")
if os.path.exists(default_path):
return # SDK will find it automatically
# 4. If missing, provide instructions or automate
print("\n" + "!" * 60)
print("⚠️ MISSING GOOGLE CLOUD CREDENTIALS")
print("Pub/Sub and BigQuery require Application Default Credentials.")
print("!" * 60 + "\n")
if sys.stdin.isatty():
choice = input("Would you like to run 'gcloud auth application-default login' now? (y/n): ")
if choice.lower() == 'y':
try:
subprocess.run(["gcloud", "auth", "application-default", "login"], check=True)
print("✅ Credentials configured.")
except Exception as e:
print(f"❌ Failed to run gcloud: {e}")
sys.exit(1)
else:
print("Please run the following command manually:")
print(" gcloud auth application-default login")
sys.exit(1)
else:
print("Non-interactive terminal detected.")
print("Please run the following command to set up credentials:")
print(" gcloud auth application-default login")
print("\nAlternatively, place your credentials JSON in the project root as:")
print(f" {local_creds}")
sys.exit(1)
def load_configs():
# Setup credentials before returning config so clients can be initialized immediately
setup_credentials()
base_dir = os.path.dirname(os.path.abspath(__file__))
config_path = os.path.join(base_dir, "config.yaml")
config = {}
if os.path.exists(config_path):
with open(config_path, "r") as f:
config = yaml.safe_load(f) or {}
# Overlay environment variables for production flexibility
# High-priority keys that often change between environments
env_keys = ["PROJECT_ID", "TOPIC_ID", "POLL_INTERVAL", "PROXY_BASE", "USE_PROXY"]
for key in env_keys:
env_val = os.environ.get(key)
if env_val is not None:
# Handle type conversion for bools and ints
if key == "POLL_INTERVAL":
try: config[key] = int(env_val)
except: pass
elif key == "USE_PROXY":
config[key] = env_val.lower() == "true"
else:
config[key] = env_val
return config
async def run_agent(agent, prompt: str):
"""
Executes an ADK agent using a Runner and returns simplified text output.
"""
from google.adk.runners import Runner
from google.adk.sessions.in_memory_session_service import InMemorySessionService
from google.genai import types
runner = Runner(
agent=agent,
app_name="NeuroTalk",
session_service=InMemorySessionService(),
auto_create_session=True
)
output = ""
async for event in runner.run_async(
user_id="streamlit_user",
session_id="chat_session",
new_message=types.Content(role="user", parts=[types.Part(text=prompt)])
):
if event.content and event.content.parts:
# Combine text parts, skipping 'thoughts'
output += "".join(p.text for p in event.content.parts if p.text and not p.thought)
return output