Skip to content

Commit a8c2db9

Browse files
fix: fix type errors and add logs (#68)
* fix: fix type errors and add logs * fix type error in some files * remove useless tls package
1 parent bfffbda commit a8c2db9

34 files changed

+291
-547
lines changed

veadk/__init__.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,17 +12,23 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15-
from .version import VERSION
15+
from typing import TYPE_CHECKING
16+
17+
from veadk.version import VERSION
18+
19+
if TYPE_CHECKING:
20+
from veadk.agent import Agent
21+
from veadk.runner import Runner
1622

1723

1824
# Lazy loading for `Agent` class
1925
def __getattr__(name):
2026
if name == "Agent":
21-
from .agent import Agent
27+
from veadk.agent import Agent
2228

2329
return Agent
2430
if name == "Runner":
25-
from .runner import Runner
31+
from veadk.runner import Runner
2632

2733
return Runner
2834
raise AttributeError(f"module 'veadk' has no attribute '{name}'")

veadk/agent.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
from typing import Optional
1818

1919
from google.adk.agents import LlmAgent, RunConfig
20+
from google.adk.agents.base_agent import BaseAgent
2021
from google.adk.agents.llm_agent import ToolUnion
2122
from google.adk.agents.run_config import StreamingMode
2223
from google.adk.models.lite_llm import LiteLlm
@@ -39,7 +40,6 @@
3940
from veadk.tracing.base_tracer import BaseTracer
4041
from veadk.utils.logger import get_logger
4142
from veadk.utils.patches import patch_asyncio
42-
from google.adk.agents.base_agent import BaseAgent
4343

4444
patch_asyncio()
4545
logger = get_logger(__name__)
@@ -70,9 +70,7 @@ class Agent(LlmAgent):
7070
model_api_base: str = getenv("MODEL_AGENT_API_BASE", DEFAULT_MODEL_AGENT_API_BASE)
7171
"""The api base of the model for agent running."""
7272

73-
model_api_key: str = Field(
74-
..., default_factory=lambda: getenv("MODEL_AGENT_API_KEY")
75-
)
73+
model_api_key: str = Field(default_factory=lambda: getenv("MODEL_AGENT_API_KEY"))
7674
"""The api key of the model for agent running."""
7775

7876
tools: list[ToolUnion] = []
@@ -244,8 +242,13 @@ async def run(
244242
user_id=user_id,
245243
session_id=session_id,
246244
)
247-
await self.long_term_memory.add_session_to_memory(session)
248-
logger.info(f"Add session `{session.id}` to your long-term memory.")
245+
if session:
246+
await self.long_term_memory.add_session_to_memory(session)
247+
logger.info(f"Add session `{session.id}` to your long-term memory.")
248+
else:
249+
logger.error(
250+
f"Session {session_id} not found in session service, cannot save to long-term memory."
251+
)
249252

250253
if collect_runtime_data:
251254
eval_set_recorder = EvalSetRecorder(session_service, eval_set_id)
@@ -254,6 +257,6 @@ async def run(
254257

255258
if self.tracers:
256259
for tracer in self.tracers:
257-
tracer.dump(user_id, session_id)
260+
tracer.dump(user_id=user_id, session_id=session_id)
258261

259262
return final_output

veadk/cli/main.py

Lines changed: 0 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -131,70 +131,6 @@ def init():
131131
set_variable_in_file(target_dir / "deploy.py", setting_values)
132132

133133

134-
# @app.command()
135-
# def web(
136-
# path: str = typer.Option(".", "--path", help="Agent project path"),
137-
# ):
138-
# from google.adk.cli import cli_tools_click
139-
140-
# def my_decorator(func):
141-
# @wraps(func)
142-
# def wrapper(*args, **kwargs):
143-
# adk_app: FastAPI = func(*args, **kwargs)
144-
# import importlib.util
145-
# import mimetypes
146-
147-
# from fastapi.staticfiles import StaticFiles
148-
149-
# mimetypes.add_type("application/javascript", ".js", True)
150-
# mimetypes.add_type("text/javascript", ".js", True)
151-
152-
# spec = importlib.util.find_spec("veadk.cli.browser")
153-
# if spec is not None:
154-
# ANGULAR_DIST_PATH = spec.submodule_search_locations[0]
155-
# logger.info(f"Static source path: {ANGULAR_DIST_PATH}")
156-
# else:
157-
# raise Exception("veadk.cli.browser not found")
158-
159-
# # ----- 8< Unmount app -----
160-
# from starlette.routing import Mount
161-
162-
# for index, route in enumerate(adk_app.routes):
163-
# if isinstance(route, Mount) and route.path == "/dev-ui":
164-
# del adk_app.routes[index]
165-
# break
166-
# # ----- 8< Mount our app -----
167-
168-
# adk_app.mount(
169-
# "/dev-ui/",
170-
# StaticFiles(directory=ANGULAR_DIST_PATH, html=True),
171-
# name="static",
172-
# )
173-
174-
# from fastapi.middleware.cors import CORSMiddleware
175-
176-
# adk_app.add_middleware(
177-
# CORSMiddleware,
178-
# allow_origins=["*"],
179-
# allow_credentials=True,
180-
# allow_methods=["*"],
181-
# allow_headers=["*"],
182-
# )
183-
# return adk_app
184-
185-
# return wrapper
186-
187-
# # Monkey patch
188-
# fast_api.get_fast_api_app = my_decorator(fast_api.get_fast_api_app)
189-
190-
# # reload cli_tools_click
191-
# importlib.reload(cli_tools_click)
192-
193-
# agents_dir = str(Path(path).resolve())
194-
# logger.info(f"Agents dir is {agents_dir}")
195-
# cli_tools_click.cli_web.main(args=[agents_dir])
196-
197-
198134
@app.command()
199135
def web(
200136
session_service_uri: str = typer.Option(
@@ -325,19 +261,6 @@ def prompt(
325261
ap.optimize(agents=agents, feedback=feedback, model_name=model_name)
326262

327263

328-
# @app.command()
329-
# def studio():
330-
# import os
331-
332-
# # pre-load
333-
# from veadk import Agent # noqa
334-
335-
# os.environ["VEADK_STUDIO_AGENTS_DIR"] = os.getcwd()
336-
# app_path = os.path.join(os.path.dirname(__file__), "../../app/app.py")
337-
338-
# os.system(f"streamlit run {app_path}")
339-
340-
341264
@app.command()
342265
def deploy(
343266
access_key: str = typer.Option(..., "--access-key", help="Access Key"),
@@ -352,24 +275,6 @@ def deploy(
352275
vefaas.deploy(name=name, path=path)
353276

354277

355-
@app.command()
356-
def log(
357-
access_key: str = typer.Option(..., "--access-key", help="Access Key"),
358-
secret_key: str = typer.Option(..., "--secret-key", help="Secret Key"),
359-
query: str = typer.Option(..., "--query", help="Query statement"),
360-
topic_id: str = typer.Option(..., "--topic-id", help="Topic ID in VeTLS"),
361-
dump_path: str = typer.Option(
362-
".", "--dump-path", help="Local path for log storage file"
363-
),
364-
):
365-
path = Path(dump_path).resolve()
366-
367-
from veadk.cli.services.vetls import VeTLS
368-
369-
vetls = VeTLS(access_key, secret_key, dump_path=str(path))
370-
vetls.query(topic_id=topic_id, query=query)
371-
372-
373278
@app.command()
374279
def version():
375280
print(f"VeADK {VERSION}")

veadk/cli/services/agentpilot/agentpilot.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@
2525

2626

2727
class AgentPilot:
28-
def __init__(self, api_key: str, path: str = "", task_id: str = None) -> None:
28+
def __init__(self, api_key: str, path: str = "") -> None:
2929
self.api_key = api_key
3030
self.path = path
31-
self.task_id = task_id
3231

3332
def optimize(
3433
self,

veadk/cli/services/vefaas/vefaas.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -304,6 +304,7 @@ def find_app_id_by_name(self, name: str):
304304
for app in apps:
305305
if app["Name"] == name:
306306
return app["Id"]
307+
logger.warning(f"Application with name {name} not found.")
307308
return None
308309

309310
def delete(self, app_id: str):

veadk/cli/services/vetls/__init__.py

Lines changed: 0 additions & 17 deletions
This file was deleted.

veadk/cli/services/vetls/vetls.py

Lines changed: 0 additions & 87 deletions
This file was deleted.

veadk/cloud/cloud_agent_engine.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,10 @@ def remove(self, app_name: str):
166166
return
167167
else:
168168
app_id = self._vefaas_service.find_app_id_by_name(app_name)
169+
if not app_id:
170+
raise ValueError(
171+
f"Cloud app {app_name} not found, cannot delete it. Please check the app name."
172+
)
169173
self._vefaas_service.delete(app_id)
170174

171175
def update_function_code(

veadk/cloud/cloud_app.py

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,10 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import json
1516
from typing import Any
1617
from uuid import uuid4
1718

18-
import json
1919
import httpx
2020
from a2a.client import A2ACardResolver, A2AClient
2121
from a2a.types import AgentCard, Message, MessageSendParams, SendMessageRequest
@@ -82,11 +82,18 @@ def _get_vefaas_endpoint(
8282
from veadk.cli.services.vefaas.vefaas import VeFaaS
8383

8484
vefaas_client = VeFaaS(access_key=volcengine_ak, secret_key=volcengine_sk)
85+
8586
app = vefaas_client.get_application_details(
8687
app_id=self.vefaas_application_id,
8788
app_name=self.vefaas_application_name,
8889
)
90+
91+
if not app:
92+
raise ValueError(
93+
f"VeFaaS CloudAPP with application_id `{self.vefaas_application_id}` or application_name `{self.vefaas_application_name}` not found."
94+
)
8995
cloud_resource = json.loads(app["CloudResource"])
96+
9097
try:
9198
vefaas_endpoint = cloud_resource["framework"]["url"]["system_url"]
9299
except Exception as e:
@@ -180,11 +187,19 @@ async def message_send(
180187
id=uuid4().hex,
181188
params=MessageSendParams(**send_message_payload),
182189
)
190+
183191
res = await a2a_client.send_message(
184192
message_send_request,
185193
http_kwargs={"timeout": httpx.Timeout(timeout)},
186194
)
187-
return res.root.result
195+
196+
logger.debug(
197+
f"Message sent to cloud app {self.vefaas_application_name} with response: {res}"
198+
)
199+
200+
# we ignore type checking here, because the response
201+
# from CloudApp will not be `Task` type
202+
return res.root.result # type: ignore
188203
except Exception as e:
189204
# TODO(floritange): show error log on VeFaaS function
190205
print(e)
@@ -194,7 +209,7 @@ async def message_send(
194209
def get_message_id(message: Message):
195210
"""Get the messageId of the a2a message"""
196211
if getattr(message, "messageId", None):
197-
# Compatible with the messageId of the old version
198-
return message.messageId
212+
# Compatible with the messageId of the old a2a-python version (<0.3.0) in cloud app
213+
return message.messageId # type: ignore
199214
else:
200215
return message.message_id

0 commit comments

Comments
 (0)