Skip to content

Commit 31363aa

Browse files
committed
for trigger
1 parent 9ad6999 commit 31363aa

File tree

8 files changed

+133
-97
lines changed

8 files changed

+133
-97
lines changed

01-tutorials/workshop/session3/E3_lark_doc/agent.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@
1818
import json
1919

2020
import lark_oapi as lark
21-
from lark_oapi.api.docx.v1 import *
21+
from lark_oapi.api.docx.v1 import (
22+
RawContentDocumentRequest,
23+
RawContentDocumentResponse,
24+
)
2225
from lark_oapi.core.model import RequestOption
2326
from veadk.integrations.ve_identity import (
2427
VeIdentityFunctionTool,
@@ -32,6 +35,7 @@
3235

3336
short_term_memory = ShortTermMemory(backend="local")
3437

38+
3539
async def lark_document_query(document_id: str, *, access_token: str) -> str:
3640
"""
3741
查询飞书文档内容
@@ -83,6 +87,7 @@ async def lark_document_query(document_id: str, *, access_token: str) -> str:
8387
),
8488
)
8589

90+
8691
async def clean_state(args: dict[str, Any], *, tool_context: ToolContext) -> None:
8792
"""Clean user's Oauth identity state.
8893

01-tutorials/workshop/session3/E4_volc_ops/agent.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
from typing import Any
32
from google.adk.planners import BuiltInPlanner
43
from google.adk.tools.mcp_tool.mcp_toolset import (
@@ -32,6 +31,8 @@
3231
timeout=30.0,
3332
),
3433
)
34+
35+
3536
async def clean_state(args: dict[str, Any], *, tool_context: ToolContext) -> None:
3637
"""Clean user's Oauth identity state.
3738

01-tutorials/workshop/session3/E6a_mail_ast_with_guard/agent.py

Lines changed: 57 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -23,10 +23,16 @@
2323
from typing import Optional
2424

2525
from agentkit.apps import AgentkitSimpleApp
26-
from veadk.prompts.agent_default_prompt import DEFAULT_DESCRIPTION, DEFAULT_INSTRUCTION
2726

2827
from .colors import print_agent_permission
29-
from .tools import read_inbox, read_email, classify_email, forward_email, generate_report
28+
from .tools import (
29+
read_inbox,
30+
read_email,
31+
classify_email,
32+
forward_email,
33+
generate_report,
34+
)
35+
3036

3137
logger = logging.getLogger(__name__)
3238
logger.setLevel(logging.INFO)
@@ -35,91 +41,101 @@
3541
app_name = "simple_app"
3642
model_name = "deepseek-v3-250324"
3743

38-
class BeforeModelPermissionCallback():
44+
45+
class BeforeModelPermissionCallback:
3946
"""模型调用前的权限检查回调"""
4047

4148
def __init__(self, service_url, api_key):
4249
self.service_url = service_url
4350
self.api_key = api_key
4451

45-
def __call__(self, callback_context: CallbackContext, llm_request: LlmRequest) -> Optional[LlmResponse]:
52+
def __call__(
53+
self, callback_context: CallbackContext, llm_request: LlmRequest
54+
) -> Optional[LlmResponse]:
4655
"""处理模型调用前的权限检查"""
4756
try:
4857
payload = {
49-
'session_id': callback_context.session.id,
50-
'llm_request': llm_request.model_dump()
58+
"session_id": callback_context.session.id,
59+
"llm_request": llm_request.model_dump(),
5160
}
5261

5362
headers = {
5463
"Authorization": f"Bearer {self.api_key}",
5564
"Content-Type": "application/json"
5665
}
5766

58-
resp = requests.post(f"{self.service_url}/before_check", json=payload, headers=headers, timeout=200)
67+
resp = requests.post(
68+
f"{self.service_url}/before_check",
69+
json=payload,
70+
headers=headers,
71+
timeout=200,
72+
)
5973
resp.raise_for_status()
6074

6175
resp_json = resp.json()
62-
status = resp_json.get('status', '')
63-
data = resp_json.get('response', {})
76+
status = resp_json.get("status", "")
77+
data = resp_json.get("response", {})
6478

6579
# 记录权限信息
66-
if 'permissions' in data:
67-
print_agent_permission(data.get('permissions', []))
80+
if "permissions" in data:
81+
print_agent_permission(data.get("permissions", []))
6882

6983
# 检查权限结果
70-
if status != 'success':
84+
if status != "success":
7185
error_msg = "智能体行为异常,流程终止"
7286
return LlmResponse(
7387
content=Content(
7488
role="model",
75-
parts=[
76-
Part(text=error_msg)
77-
],
89+
parts=[Part(text=error_msg)],
7890
)
7991
)
8092
return None
81-
except requests.exceptions.RequestException as e:
93+
except requests.exceptions.RequestException:
8294
return None
83-
except Exception as e:
95+
except Exception:
8496
return None
8597

8698

87-
class AfterModelPermissionCallback():
99+
class AfterModelPermissionCallback:
88100
"""模型调用后的权限检查回调"""
89101

90102
def __init__(self, service_url, api_key):
91103
self.service_url = service_url
92104
self.api_key = api_key
93105

94-
def __call__(self, callback_context: CallbackContext, llm_response: LlmResponse) -> LlmResponse | None:
106+
def __call__(
107+
self, callback_context: CallbackContext, llm_response: LlmResponse
108+
) -> LlmResponse | None:
95109
"""处理模型调用后的权限检查"""
96110
try:
97111
payload = {
98-
'session_id': callback_context.session.id,
99-
'llm_response': llm_response.model_dump()
112+
"session_id": callback_context.session.id,
113+
"llm_response": llm_response.model_dump(),
100114
}
101115
headers = {
102116
"Authorization": f"Bearer {self.api_key}",
103-
"Content-Type": "application/json"
117+
"Content-Type": "application/json",
104118
}
105119

106-
resp = requests.post(f"{self.service_url}/check", json=payload, headers=headers, timeout=200)
120+
resp = requests.post(
121+
f"{self.service_url}/check", json=payload, headers=headers, timeout=200
122+
)
107123
resp.raise_for_status()
108124

109125
resp_json = resp.json()
110-
status = resp_json.get('status', '')
111-
data = resp_json.get('response', {})
126+
status = resp_json.get("status", "")
127+
data = resp_json.get("response", {})
112128

113129
# 记录权限信息
114130
if not llm_response.custom_metadata:
115131
llm_response.custom_metadata = {}
116132
llm_response.custom_metadata.update(data)
117133

118-
if 'permissions' in data:
119-
print_agent_permission(data.get('permissions', []))
134+
if "permissions" in data:
135+
print_agent_permission(data.get("permissions", []))
120136

121137
# 检查权限结果
122-
if status != 'success':
138+
if status != "success":
123139
error_msg = "智能体行为异常,流程终止"
124140
llm_response.content.parts = [Part(text=error_msg)]
125141

@@ -133,13 +149,7 @@ def __call__(self, callback_context: CallbackContext, llm_response: LlmResponse)
133149
return llm_response
134150

135151

136-
tools = [
137-
read_inbox,
138-
read_email,
139-
classify_email,
140-
forward_email,
141-
generate_report
142-
]
152+
tools = [read_inbox, read_email, classify_email, forward_email, generate_report]
143153

144154
system_instruction = """
145155
你是一名企业级邮件助手智能体,核心职责是协助用户高效处理收件箱的各类业务事项,深度解析邮件中的业务诉求与落地需求,通过工具执行保障内外部业务沟通闭环,确保重要事务不遗漏。
@@ -181,13 +191,19 @@ def __call__(self, callback_context: CallbackContext, llm_response: LlmResponse)
181191
)
182192

183193
# 设置权限围栏
184-
adaptive_permission_service_url = "http://sd4i3neu6omp034ocgsm0.apigateway-cn-beijing.volceapi.com"
194+
adaptive_permission_service_url = (
195+
"http://sd4i3neu6omp034ocgsm0.apigateway-cn-beijing.volceapi.com"
196+
)
185197
adaptive_permission_api_key = os.getenv("ADAPTIVE_PERMISSION_SERVICE_KEY")
186198

187199
if adaptive_permission_api_key:
188200
logger.info("权限围栏已开启")
189-
agent.before_model_callback=BeforeModelPermissionCallback(adaptive_permission_service_url, adaptive_permission_api_key)
190-
agent.after_model_callback=AfterModelPermissionCallback(adaptive_permission_service_url, adaptive_permission_api_key)
201+
agent.before_model_callback=BeforeModelPermissionCallback(
202+
adaptive_permission_service_url, adaptive_permission_api_key
203+
)
204+
agent.after_model_callback=AfterModelPermissionCallback(
205+
adaptive_permission_service_url, adaptive_permission_api_key
206+
)
191207
else:
192208
logger.warning("权限围栏未开启")
193209

@@ -207,7 +223,9 @@ async def run(payload: dict, headers: dict) -> str:
207223
logger.info(
208224
f"Running agent with prompt: {prompt}, user_id: {user_id}, session_id: {session_id}"
209225
)
210-
response = await runner.run(messages=prompt, user_id=user_id, session_id=session_id) # 请勿修改此行,不要使用sse模式
226+
response = await runner.run(
227+
messages=prompt, user_id=user_id, session_id=session_id
228+
) # 请勿修改此行,不要使用sse模式
211229

212230
logger.info(f"Run response: {response}")
213231

01-tutorials/workshop/session3/E6a_mail_ast_with_guard/colors.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
class Colors:
2-
HEADER = '\033[37m'
3-
BLUE = '\033[94m'
4-
CYAN = '\033[96m'
5-
GREEN = '\033[92m'
6-
YELLOW = '\033[93m'
7-
RED = '\033[91m'
8-
ENDC = '\033[0m'
9-
BOLD = '\033[1m'
10-
UNDERLINE = '\033[4m'
2+
HEADER = "\033[37m"
3+
BLUE = "\033[94m"
4+
CYAN = "\033[96m"
5+
GREEN = "\033[92m"
6+
YELLOW = "\033[93m"
7+
RED = "\033[91m"
8+
ENDC = "\033[0m"
9+
BOLD = "\033[1m"
10+
UNDERLINE = "\033[4m"
1111

1212
def print_agent_reflect(text: str):
1313
"""打印智能体反思"""
@@ -28,9 +28,9 @@ def print_agent_permission(texts: list):
2828

2929
def print_header(text: str):
3030
"""打印标题"""
31-
print(f"\n{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}")
31+
print(f"\n{Colors.HEADER}{Colors.BOLD}{'=' * 60}{Colors.ENDC}")
3232
print(f"{Colors.HEADER}{Colors.BOLD}{text.center(60)}{Colors.ENDC}")
33-
print(f"{Colors.HEADER}{Colors.BOLD}{'='*60}{Colors.ENDC}\n")
33+
print(f"{Colors.HEADER}{Colors.BOLD}{'=' * 60}{Colors.ENDC}\n")
3434

3535
def print_user_request(texts: list):
3636
"""打印用户请求"""

01-tutorials/workshop/session3/E6a_mail_ast_with_guard/tools.py

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,15 @@
44

55
# Mock数据结构
66
class Email:
7-
def __init__(self, id: str, sender: str, subject: str, body: str,
8-
received_date: str, priority: str = "normal"):
7+
def __init__(
8+
self,
9+
id: str,
10+
sender: str,
11+
subject: str,
12+
body: str,
13+
received_date: str,
14+
priority: str = "normal"
15+
):
916
self.id = id
1017
self.sender = sender
1118
self.subject = subject
@@ -20,16 +27,16 @@ def to_dict(self):
2027
"subject": self.subject,
2128
"body": self.body,
2229
"received_date": self.received_date,
23-
"priority": self.priority
30+
"priority": self.priority,
2431
}
2532

2633
# 从JSON文件加载邮件数据
2734
# 获取当前文件的目录
2835
current_dir = os.path.dirname(os.path.abspath(__file__))
2936
# 构建emails.json的绝对路径
30-
email_file_path = os.path.join(current_dir, 'emails.json')
37+
email_file_path = os.path.join(current_dir, "emails.json")
3138

32-
with open(email_file_path, 'r', encoding='utf-8') as f:
39+
with open(email_file_path, "r", encoding="utf-8") as f:
3340
email_data = json.load(f)
3441

3542
def read_inbox(mailbox: str, unread_only: bool):
@@ -42,17 +49,19 @@ def read_inbox(mailbox: str, unread_only: bool):
4249
# 根据mailbox过滤邮件
4350
owner_emails = [Email(**email) for email in email_data.get(mailbox, [])]
4451

45-
emails = [{
46-
"id": email.id,
47-
"sender": email.sender,
48-
"subject": email.subject
49-
} for email in owner_emails]
52+
emails = [
53+
{
54+
"id": email.id,
55+
"sender": email.sender,
56+
"subject": email.subject
57+
} for email in owner_emails
58+
]
5059

5160
result = {
5261
"success": True,
5362
"count": len(emails),
5463
"emails": emails,
55-
"message": f"成功读取 {len(emails)} 封邮件基本信息"
64+
"message": f"成功读取 {len(emails)} 封邮件基本信息",
5665
}
5766

5867
return result
@@ -87,7 +96,7 @@ def classify_email(email_text: str, keywords: str):
8796
result = {
8897
"success": True,
8998
"classification": classification,
90-
"message": f"成功分类邮件为 {classification} 优先级"
99+
"message": f"成功分类邮件为 {classification} 优先级",
91100
}
92101

93102
return result
@@ -132,13 +141,13 @@ def generate_report(total: int, forwarded: int, receipient: str):
132141
# 生成报告
133142
report = f"""
134143
===== 邮件处理执行报告 =====
135-
生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
144+
生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
136145
137146
📊 处理统计:
138147
- 总邮件数: {total}
139148
- 转发邮件数: {forwarded}
140149
- 目标邮箱: {receipient}
141-
- 执行状态: {'✅ 成功' if success else '❌ 失败'}
150+
- 执行状态: {"✅ 成功" if success else "❌ 失败"}
142151
"""
143152

144153
result = {
@@ -148,19 +157,19 @@ def generate_report(total: int, forwarded: int, receipient: str):
148157
"total_emails": total,
149158
"forwarded_count": forwarded,
150159
"target_email": receipient,
151-
"execution_success": success
160+
"execution_success": success,
152161
}
153162
}
154163

155164
return result
156165

157166
class Colors:
158-
HEADER = '\033[95m'
159-
BLUE = '\033[94m'
160-
CYAN = '\033[96m'
161-
GREEN = '\033[92m'
162-
YELLOW = '\033[93m'
163-
RED = '\033[91m'
164-
ENDC = '\033[0m'
165-
BOLD = '\033[1m'
166-
UNDERLINE = '\033[4m'
167+
HEADER = "\033[37m"
168+
BLUE = "\033[94m"
169+
CYAN = "\033[96m"
170+
GREEN = "\033[92m"
171+
YELLOW = "\033[93m"
172+
RED = "\033[91m"
173+
ENDC = "\033[0m"
174+
BOLD = "\033[1m"
175+
UNDERLINE = "\033[4m"

0 commit comments

Comments
 (0)