1616import hashlib
1717import hmac
1818import os
19+ import platform
1920import requests
2021from urllib .parse import quote
2122from agentkit .utils .global_config_io import get_global_config_str
2930Scheme = "https"
3031
3132
33+ MAX_X_CUSTOM_SOURCE_LENGTH = 256
34+
35+
36+ def _get_os_tag () -> str :
37+ system = platform .system ().lower ()
38+ if "linux" in system :
39+ return "linux"
40+ if "windows" in system :
41+ return "windows"
42+ if "darwin" in system or "mac" in system :
43+ return "macos"
44+ return "unknown"
45+
46+
47+ def _get_entry () -> str :
48+ value = os .getenv ("AGENTKIT_CLIENT_TYPE" , "" ).strip ().lower ()
49+ if value in ("cli" , "sdk" ):
50+ return value
51+ return "sdk"
52+
53+
54+ def _get_sdk_version () -> str :
55+ try :
56+ from agentkit .version import VERSION
57+
58+ if VERSION :
59+ return VERSION
60+ except Exception :
61+ pass
62+ return "unknown"
63+
64+
65+ def build_x_custom_source_header () -> str :
66+ sdk_name = "agentkit-sdk-python"
67+ version = _get_sdk_version ()
68+ entry = _get_entry ()
69+ os_tag = _get_os_tag ()
70+ product = f"{ sdk_name } /{ version } "
71+ parts = ["schema=v1" , f"entry={ entry } " , f"os={ os_tag } " ]
72+ inner = "; " .join (parts )
73+ value = product
74+ if inner :
75+ value = f"{ product } ({ inner } )"
76+ if len (value ) <= MAX_X_CUSTOM_SOURCE_LENGTH :
77+ return value
78+ if len (product ) <= MAX_X_CUSTOM_SOURCE_LENGTH :
79+ return product
80+ return value [:MAX_X_CUSTOM_SOURCE_LENGTH ]
81+
82+
83+ def ensure_x_custom_source_header (header : dict | None ) -> dict :
84+ base = header .copy () if header is not None else {}
85+ if "X-Custom-Request-Context" not in base :
86+ base ["X-Custom-Request-Context" ] = build_x_custom_source_header ()
87+ return base
88+
89+
3290def norm_query (params ):
3391 query = ""
3492 for key in sorted (params .keys ()):
@@ -146,6 +204,7 @@ def request(method, date, query, header, ak, sk, action, body):
146204 signature ,
147205 )
148206 )
207+ header = ensure_x_custom_source_header (header )
149208 header = {** header , ** sign_result }
150209 # header = {**header, **{"X-Security-Token": SessionToken}}
151210 # 第六步:将 Signature 签名写入 HTTP Header 中,并发送 HTTP 请求。
@@ -168,7 +227,7 @@ def ve_request(
168227 version : str ,
169228 region : str ,
170229 host : str ,
171- header : dict = {} ,
230+ header : dict | None = None ,
172231 content_type : str = "application/json" ,
173232 scheme : str = "https" ,
174233):
@@ -199,7 +258,7 @@ def ve_request(
199258
200259 try :
201260 response_body = request (
202- "POST" , now , {}, header , AK , SK , action , json .dumps (request_body )
261+ "POST" , now , {}, header or {} , AK , SK , action , json .dumps (request_body )
203262 )
204263 check_error (response_body )
205264 return response_body
0 commit comments