byteplussdk-llmshield 3.0.64__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ Metadata-Version: 2.4
2
+ Name: byteplussdk-llmshield
3
+ Version: 3.0.64
4
+ Summary: Byteplus llmshield SDK for Python
5
+ Home-page: https://github.com/byteplus-sdk/byteplus-python-sdk-v2
6
+ Author: byteplus-sdk
7
+ Author-email: sdk@byteplus.com
8
+ License: Apache License 2.0
9
+ Platform: any
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE.txt
13
+ Requires-Dist: pydantic<3,>=2
14
+ Requires-Dist: requests<3,>=2
15
+ Dynamic: author
16
+ Dynamic: author-email
17
+ Dynamic: description
18
+ Dynamic: description-content-type
19
+ Dynamic: home-page
20
+ Dynamic: license
21
+ Dynamic: license-file
22
+ Dynamic: platform
23
+ Dynamic: requires-dist
24
+ Dynamic: requires-python
25
+ Dynamic: summary
26
+
27
+ # byteplussdk-llmshield
28
+
29
+ This distribution contains the `byteplussdkllmshield` import package from the Byteplus
30
+ Python SDK. Install `byteplus-python-sdk-v2` to install every service package.
@@ -0,0 +1,10 @@
1
+ byteplussdk_llmshield-3.0.64.dist-info/licenses/LICENSE.txt,sha256=jG2zQEdRNt88EgHUWPpXVWmOrOduUQRx7MnYV9YIPaw,11359
2
+ byteplussdkllmshield/__init__.py,sha256=0U-ymvDhNVlpOT_o360kViXUIT_LW2nq20iy9GhtxUo,2162
3
+ byteplussdkllmshield/api/__init__.py,sha256=di_9IIKQ0HCuzkGrTyZ6h38iP7y1xelH8_IJbKi4aWA,71
4
+ byteplussdkllmshield/api/llm_shield_sdk_v2.py,sha256=1hIXCkchAVaitEgavJC8bMmz4dWCAmLrOMKMrqNwE2o,21266
5
+ byteplussdkllmshield/models/__init__.py,sha256=OpEdwHNrJ0rcWEdVt0Km58pboIBWP4WYA8zv2LhzzWc,259
6
+ byteplussdkllmshield/models/llm_shield_sign.py,sha256=8SQqQsI3KUghfVEfGHqSMAEAZ4V2f6brpj3cEKtT4hI,5956
7
+ byteplussdk_llmshield-3.0.64.dist-info/METADATA,sha256=GAtbWpJ_hP2uI8oxO8CE7DmWOgPVw73_kFRsVlHbCPY,844
8
+ byteplussdk_llmshield-3.0.64.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
9
+ byteplussdk_llmshield-3.0.64.dist-info/top_level.txt,sha256=6yDy2pFQ9vsuoL6-pwx9fSOyvHRG2t7fyaTw-hezy28,21
10
+ byteplussdk_llmshield-3.0.64.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,203 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
203
+
@@ -0,0 +1 @@
1
+ byteplussdkllmshield
@@ -0,0 +1,102 @@
1
+ # coding: utf-8
2
+
3
+ # flake8: noqa
4
+
5
+ """
6
+ llmshield
7
+
8
+ No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
9
+
10
+ OpenAPI spec version: common-version
11
+
12
+ Generated by: https://github.com/swagger-api/swagger-codegen.git
13
+ """
14
+
15
+ from __future__ import absolute_import
16
+
17
+ # 导入API模块
18
+ from byteplussdkllmshield.api.llm_shield_sdk_v2 import ClientV2, SetServiceDev, GetServiceCode
19
+ from byteplussdkllmshield.api.llm_shield_sdk_v2 import (
20
+ OPTION_REWRITE_URL,
21
+ ContentTypeV2,
22
+ DecisionTypeV2,
23
+ UserAction,
24
+ MatchSource,
25
+ ExtensionsKey,
26
+ MultiPart,
27
+ FunctionCall,
28
+ ToolCall,
29
+ MessageV2,
30
+ ModerateV2Request,
31
+ ImagePositionInfo,
32
+ PositionInfo,
33
+ RiskMatchV2,
34
+ PermitMatchV2,
35
+ RiskV2,
36
+ SourceInfoV2,
37
+ RiskInfoV2,
38
+ PermitV2,
39
+ PermitInfoV2,
40
+ BlockDetailV2,
41
+ ReplaceDetailV2,
42
+ DecisionDetailV2,
43
+ DecisionV2,
44
+ ModerateV2Result,
45
+ ErrorInfo,
46
+ ResponseMetadata,
47
+ ModerateV2Response,
48
+ ModerateV2StreamSession,
49
+ GenerateStreamV2Request,
50
+ GenerateStreamV2Response,
51
+ GenerateSummarizeV2,
52
+ GenerateStreamResult,
53
+ GenerateStreamV2ResponseData,
54
+ CustomJSONEncoder,
55
+ SetServiceDev,
56
+ GetServiceCode
57
+ )
58
+
59
+
60
+ __all__ = [
61
+ # API客户端
62
+ 'ClientV2',
63
+ 'OPTION_REWRITE_URL',
64
+ # 常量类
65
+ 'ContentTypeV2',
66
+ 'DecisionTypeV2',
67
+ 'UserAction',
68
+ 'MatchSource',
69
+ 'ExtensionsKey',
70
+ # 数据模型
71
+ 'MultiPart',
72
+ 'FunctionCall',
73
+ 'ToolCall',
74
+ 'MessageV2',
75
+ 'ModerateV2Request',
76
+ 'ImagePositionInfo',
77
+ 'PositionInfo',
78
+ 'RiskMatchV2',
79
+ 'PermitMatchV2',
80
+ 'RiskV2',
81
+ 'SourceInfoV2',
82
+ 'RiskInfoV2',
83
+ 'PermitV2',
84
+ 'PermitInfoV2',
85
+ 'BlockDetailV2',
86
+ 'ReplaceDetailV2',
87
+ 'DecisionDetailV2',
88
+ 'DecisionV2',
89
+ 'ModerateV2Result',
90
+ 'ErrorInfo',
91
+ 'ResponseMetadata',
92
+ 'ModerateV2Response',
93
+ 'ModerateV2StreamSession',
94
+ 'GenerateStreamV2Request',
95
+ 'GenerateStreamV2Response',
96
+ 'GenerateSummarizeV2',
97
+ 'GenerateStreamResult',
98
+ 'GenerateStreamV2ResponseData',
99
+ 'CustomJSONEncoder',
100
+ 'SetServiceDev',
101
+ 'GetServiceCode',
102
+ ]
@@ -0,0 +1,4 @@
1
+ # coding: utf-8
2
+ # flake8: noqa
3
+
4
+ from __future__ import absolute_import
@@ -0,0 +1,597 @@
1
+ from pydantic import BaseModel, field_validator, Field
2
+ from typing import Dict, List, Optional, Any, Union
3
+ from datetime import datetime, date
4
+ from uuid import UUID
5
+ import requests
6
+ from requests.adapters import HTTPAdapter
7
+ import json
8
+ import os
9
+
10
+ from ..models.llm_shield_sign import request_sign, Version, SetServiceDev, GetServiceCode
11
+
12
+ LLM_STREAM_SEND_BASE_WINDOW_V2 = 10
13
+ LLM_STREAM_SEND_EXPONENT_V2 = 2
14
+
15
+ OPTION_REWRITE_URL = "RewriteUrl"
16
+
17
+
18
+ # 定义内容类型常量
19
+ class ContentTypeV2:
20
+ TEXT = 1
21
+ AUDIO = 2
22
+ IMAGE = 3
23
+ VIDEO = 4
24
+ FILE = 5
25
+
26
+ # 定义决策类型常量
27
+ class DecisionTypeV2:
28
+ PASS = 1
29
+ BLOCK = 2
30
+ MARK = 3
31
+ REPLACE = 4
32
+ OPTIMIZE = 5
33
+
34
+
35
+ # 定义用户操作常量
36
+ class UserAction:
37
+ PASS = 1
38
+ BLOCK = 2
39
+ MARK = 3
40
+ REPLACE = 4
41
+
42
+
43
+ # 定义匹配来源常量
44
+ class MatchSource:
45
+ UNKNOWN = 0
46
+ GLOBAL_CONTENTLIB = 1
47
+ ADMIN_CONTENTLIB = 2
48
+ USER_CONTENTLIB = 3
49
+
50
+
51
+ # 定义扩展字段Key常量
52
+ class ExtensionsKey:
53
+ USER_ID = "user_id"
54
+ RUN_ID = "run_id"
55
+ SESSION_ID = "session_id"
56
+ CONTEXT_ID = "context_id"
57
+ HOOK_NAME = "hook_name"
58
+
59
+
60
+ # 定义消息结构体
61
+ class MultiPart(BaseModel):
62
+ content: str = Field("", alias="Content")
63
+ content_type: int = Field(ContentTypeV2.TEXT, alias="ContentType")
64
+
65
+ class Config:
66
+ populate_by_name = True
67
+
68
+
69
+ # 定义函数调用结构体
70
+ class FunctionCall(BaseModel):
71
+ name: str = Field("", alias="Name")
72
+ arguments: str = Field("", alias="Arguments")
73
+
74
+ class Config:
75
+ populate_by_name = True
76
+
77
+
78
+ # 定义工具调用结构体
79
+ class ToolCall(BaseModel):
80
+ id: str = Field("", alias="ID")
81
+ type: str = Field("", alias="Type")
82
+ function: Optional[FunctionCall] = Field(None, alias="Function")
83
+
84
+ class Config:
85
+ populate_by_name = True
86
+
87
+
88
+ # 定义消息结构体
89
+ class MessageV2(BaseModel):
90
+ role: str = Field("", alias="Role")
91
+ content: str = Field("", alias="Content")
92
+ content_type: int = Field(ContentTypeV2.TEXT, alias="ContentType")
93
+ multi_part: Optional[List[MultiPart]] = Field(None, alias="MultiPart")
94
+ tool_call_id: Optional[str] = Field(None, alias="ToolCallID")
95
+ tool_call: Optional[List[ToolCall]] = Field(None, alias="ToolCall")
96
+
97
+ class Config:
98
+ populate_by_name = True
99
+
100
+ # 定义审核请求结构体
101
+ class ModerateV2Request(BaseModel):
102
+ message: MessageV2 = Field(None, alias="Message")
103
+ msg_id: str = Field("", alias="MsgID")
104
+ use_stream: int = Field(0, alias="UseStream")
105
+ scene: str = Field("", alias="Scene")
106
+ history: List[MessageV2] = Field([], alias="History")
107
+ extensions: Dict[str, str] = Field(default_factory=dict, alias="Extensions")
108
+ call_generate_on_optimize: Optional[bool] = Field(None, alias="CallGenerateOnOptimize")
109
+
110
+ class Config:
111
+ populate_by_name = True
112
+
113
+ # 深拷贝构造方法:通过 Pydantic 序列化/反序列化实现
114
+ def __init__(self, other=None, **data):
115
+ # 如果传入了其他 ModerateV2Request 实例,则进行深拷贝
116
+ if other is not None and isinstance(other, ModerateV2Request):
117
+ # 1. 将其他实例序列化为字典(包含嵌套对象)
118
+ other_dict = other.model_dump(by_alias=True) # 使用 alias 键名
119
+ # 2. 用序列化后的字典初始化当前实例(实现深拷贝)
120
+ super().__init__(**other_dict)
121
+ else:
122
+ # 正常初始化逻辑
123
+ super().__init__(**data)
124
+
125
+
126
+ # 定义风险匹配结构体
127
+ class RiskMatchV2(BaseModel):
128
+ word: str = Field("", alias="Word")
129
+ action: Optional[int] = Field(None, alias="Action")
130
+ source: Optional[int] = Field(None, alias="Source")
131
+ rule_id: Optional[Any] = Field(None, alias="RuleID")
132
+ position: Optional["PositionInfo"] = Field(None, alias="Position")
133
+
134
+ class Config:
135
+ populate_by_name = True
136
+
137
+
138
+ class ImagePositionInfo(BaseModel):
139
+ x_start: str = Field("", alias="xStart")
140
+ y_start: str = Field("", alias="yStart")
141
+ x_end: str = Field("", alias="xEnd")
142
+ y_end: str = Field("", alias="yEnd")
143
+
144
+ class Config:
145
+ populate_by_name = True
146
+
147
+
148
+ class PositionInfo(BaseModel):
149
+ image_position: Optional[ImagePositionInfo] = Field(None, alias="ImagePosition")
150
+
151
+ class Config:
152
+ populate_by_name = True
153
+
154
+
155
+ # 定义放行匹配结构体
156
+ class PermitMatchV2(BaseModel):
157
+ word: str = Field("", alias="Word")
158
+ action: Optional[int] = Field(None, alias="Action")
159
+ source: Optional[int] = Field(None, alias="Source")
160
+ rule_id: Optional[Any] = Field(None, alias="RuleID")
161
+
162
+ class Config:
163
+ populate_by_name = True
164
+
165
+
166
+ # 定义风险结构体
167
+ class RiskV2(BaseModel):
168
+ category: str = Field("", alias="Category")
169
+ label: str = Field("", alias="Label")
170
+ prob: Optional[float] = Field(None, alias="Prob")
171
+ matches: List[RiskMatchV2] = Field([], alias="Matches")
172
+ source_infos: List["SourceInfoV2"] = Field([], alias="SourceInfos")
173
+
174
+ @field_validator('matches', mode="before")
175
+ def convert_risk_matches_none_to_list(cls, value):
176
+ return [] if value is None else value
177
+
178
+ @field_validator('source_infos', mode="before")
179
+ def convert_source_infos_none_to_list(cls, value):
180
+ return [] if value is None else value
181
+
182
+ class Config:
183
+ populate_by_name = True
184
+
185
+
186
+ class SourceInfoV2(BaseModel):
187
+ source: str = Field("", alias="Source")
188
+ source_detail: Dict[str, str] = Field(default_factory=dict, alias="SourceDetail")
189
+
190
+ class Config:
191
+ populate_by_name = True
192
+
193
+
194
+ # 定义风险信息结构体 - 添加 None 转换
195
+ class RiskInfoV2(BaseModel):
196
+ risks: List[RiskV2] = Field([], alias="Risks")
197
+
198
+ @field_validator('risks', mode="before")
199
+ def convert_none_to_list(cls, value):
200
+ return [] if value is None else value
201
+
202
+ class Config:
203
+ populate_by_name = True
204
+
205
+
206
+ # 定义放行结构体
207
+ class PermitV2(BaseModel):
208
+ category: str = Field("", alias="Category")
209
+ label: str = Field("", alias="Label")
210
+ prob: Optional[float] = Field(None, alias="Prob")
211
+ matches: List[PermitMatchV2] = Field([], alias="Matches")
212
+
213
+ @field_validator('matches', mode="before")
214
+ def convert_permit_matches_none_to_list(cls, value):
215
+ return [] if value is None else value
216
+
217
+ class Config:
218
+ populate_by_name = True
219
+
220
+
221
+ # 定义放行信息结构体 - 添加 None 转换
222
+ class PermitInfoV2(BaseModel):
223
+ permits: List[PermitV2] = Field([], alias="Permits")
224
+
225
+ @field_validator('permits', mode="before")
226
+ def convert_none_to_list(cls, value):
227
+ return [] if value is None else value
228
+
229
+ class Config:
230
+ populate_by_name = True
231
+
232
+
233
+ # 定义拦截详情结构体
234
+ class BlockDetailV2(BaseModel):
235
+ class Config:
236
+ extra = "forbid"
237
+
238
+
239
+ # 定义替换详情结构体
240
+ class ReplaceDetailV2(BaseModel):
241
+ replacement: Optional[MessageV2] = Field(None, alias="Replacement")
242
+
243
+ class Config:
244
+ populate_by_name = True
245
+
246
+
247
+ # 定义决策详情结构体
248
+ class DecisionDetailV2(BaseModel):
249
+ block_detail: Optional[BlockDetailV2] = Field(None, alias="BlockDetail")
250
+ replace_detail: Optional[ReplaceDetailV2] = Field(None, alias="ReplaceDetail")
251
+
252
+ class Config:
253
+ populate_by_name = True
254
+
255
+
256
+ # 定义决策结构体
257
+ class DecisionV2(BaseModel):
258
+ decision_type: int = Field(0, alias="DecisionType")
259
+ decision_detail: DecisionDetailV2 = Field(default_factory=DecisionDetailV2, alias="DecisionDetail")
260
+ decision_strategy_id: Optional[str] = Field(None, alias="DecisionStrategyID")
261
+ hit_strategy_ids: List[str] = Field([], alias="HitStrategyIDs")
262
+
263
+ @field_validator('hit_strategy_ids', mode="before")
264
+ def convert_hit_strategies_none_to_list(cls, value):
265
+ return [] if value is None else value
266
+
267
+ class Config:
268
+ populate_by_name = True
269
+
270
+
271
+ # 定义审核结果结构体
272
+ class ModerateV2Result(BaseModel):
273
+ msg_id: str = Field("", alias="MsgID")
274
+ risk_info: RiskInfoV2 = Field(default_factory=RiskInfoV2, alias="RiskInfo")
275
+ decision: DecisionV2 = Field(default_factory=DecisionV2, alias="Decision")
276
+ permit_info: PermitInfoV2 = Field(default_factory=PermitInfoV2, alias="PermitInfo")
277
+ content_info: str = Field("", alias="ContentInfo")
278
+ degraded: bool = Field(False, alias="Degraded")
279
+ degrade_reason: str = Field("", alias="DegradeReason")
280
+
281
+ class Config:
282
+ populate_by_name = True
283
+
284
+
285
+ # 定义错误信息结构体
286
+ class ErrorInfo(BaseModel):
287
+ code: str = Field("", alias="Code")
288
+ codeN: Union[int, str] = Field("", alias="CodeN")
289
+ message: str = Field("", alias="Message")
290
+
291
+ class Config:
292
+ populate_by_name = True
293
+
294
+
295
+ # 定义响应元数据结构体
296
+ class ResponseMetadata(BaseModel):
297
+ error: Union[ErrorInfo, None] = Field(default_factory=ErrorInfo, alias="Error")
298
+ requestId: str = Field(..., alias="RequestId") # 添加requestId字段,映射自RequestId
299
+ service: Union[str, None] = Field(None, alias="Service")
300
+ action: Union[str, None] = Field(None, alias="Action")
301
+ version: Union[str, None] = Field(None, alias="Version")
302
+ region: Union[str, None] = Field(None, alias="Region")
303
+
304
+ class Config:
305
+ populate_by_name = True
306
+ validate_by_name = True
307
+
308
+
309
+ # 定义审核响应结构体
310
+ class ModerateV2Response(BaseModel):
311
+ response_metadata: ResponseMetadata = Field(default_factory=ResponseMetadata, alias="ResponseMetadata")
312
+ result: Union[ModerateV2Result, None] = Field(default_factory=ModerateV2Result, alias="Result")
313
+
314
+ class Config:
315
+ populate_by_name = True
316
+
317
+
318
+ class ModerateV2StreamSession:
319
+ """流式会话结构体,用于积累流式请求、存储未发送长度和默认响应体"""
320
+
321
+ def __init__(self):
322
+ # 用于积累流式的请求(初始为 None,对应 Go 中的指针)
323
+ self.request: Optional[ModerateV2Request] = None
324
+ # 未发送的长度(对应 Go 中的 StreamSendLen)
325
+ self.stream_send_len: int = 0
326
+ self.CurrentSendWindow = LLM_STREAM_SEND_BASE_WINDOW_V2
327
+ # 存储默认响应体(初始为 None,对应 Go 中的指针)
328
+ self.default_body: Optional[ModerateV2Response] = None
329
+
330
+
331
+ class GenerateStreamV2Request(BaseModel):
332
+ """生成流V2版本的请求模型"""
333
+ msg_id: str = Field(..., alias="MsgID", description="消息ID,表示请求的唯一标识")
334
+
335
+ class Config:
336
+ populate_by_name = True
337
+ json_schema_extra = {
338
+ "validate": {"required": True} # 对应Go中的validate:"required"
339
+ }
340
+
341
+
342
+ class GenerateStreamV2Response(BaseModel):
343
+ def __init__(self, reader=None):
344
+ self.Reader = reader
345
+
346
+
347
+ class GenerateSummarizeV2(BaseModel):
348
+ """生成过程的总结信息模型"""
349
+ token_cost: int = Field(0, alias="TokenCost", description="消耗的token数量")
350
+ time_cost_ms: int = Field(0, alias="TimeCostMS", description="消耗的时长(毫秒)")
351
+
352
+ class Config:
353
+ populate_by_name = True
354
+
355
+
356
+ class GenerateStreamResult(BaseModel):
357
+ """生成流V2版本的结果模型"""
358
+ message: Optional[MessageV2] = Field(None, alias="Message", description="优化内容,isFinished为true时为空")
359
+ is_finished: bool = Field(False, alias="IsFinished", description="标识是否结束")
360
+
361
+ # summarize: Optional[GenerateSummarizeV2] = Field(None, alias="Summarize", description="总结信息,isFinished为true时有值")
362
+
363
+ class Config:
364
+ populate_by_name = True
365
+
366
+
367
+ class GenerateStreamV2ResponseData(BaseModel):
368
+ """生成流V2版本的响应数据模型"""
369
+ response_metadata: ResponseMetadata = Field(..., alias="ResponseMetadata", description="响应元数据")
370
+ result: GenerateStreamResult = Field(..., alias="Result", description="生成流结果")
371
+
372
+ class Config:
373
+ populate_by_name = True
374
+
375
+
376
+ # 自定义带默认超时的Session子类
377
+ class SessionTimeout(requests.Session):
378
+ def __init__(self, default_timeout=None, *args, **kwargs):
379
+ super().__init__(*args, **kwargs)
380
+ # 保存默认超时时间
381
+ self.default_timeout = default_timeout
382
+
383
+ def request(self, method, url, **kwargs):
384
+ # 核心逻辑:如果没手动传timeout,就用默认值
385
+ if "timeout" not in kwargs and self.default_timeout is not None:
386
+ # 流式请求避免 read timeout 打断连接:只设置 connect timeout
387
+ if kwargs.get("stream") and isinstance(self.default_timeout, (int, float)):
388
+ kwargs["timeout"] = (self.default_timeout, None)
389
+ else:
390
+ kwargs["timeout"] = self.default_timeout
391
+ # 调用父类的request方法,保持原有逻辑不变
392
+ return super().request(method, url, **kwargs)
393
+
394
+
395
+ # 定义客户端类
396
+ class ClientV2:
397
+ def __init__(self, url: str, ak: str, sk: str, region: str, timeout: float,
398
+ options: Optional[Dict[str, Any]] = None):
399
+ self.url = url
400
+ self.rewrite_url = options.get(OPTION_REWRITE_URL) if options else None
401
+ self.ak = ak
402
+ self.sk = sk
403
+ self.region = region
404
+ self.http_client = SessionTimeout(default_timeout=timeout)
405
+ self.http_client.timeout = timeout
406
+
407
+ def SetProxy(self, proxy: dict):
408
+ if proxy:
409
+ self.http_client.proxies = proxy
410
+ else:
411
+ self.http_client.proxies.clear()
412
+
413
+ def SetConnMax(self, connMax):
414
+ if connMax > 0:
415
+ adapter = HTTPAdapter(
416
+ pool_connections=connMax, # 全局连接池数量:最多维护多少个 Host 的连接池
417
+ pool_maxsize=connMax, # 单 Host 最大连接数:控制并发的核心(= 目标并发数)
418
+ pool_block=False # 连接池满时是否阻塞:False=非阻塞(超时抛异常),True=阻塞等待
419
+ )
420
+ # 将适配器挂载到 Session:所有 HTTP/HTTPS 请求都使用该连接池
421
+ self.http_client.mount("http://", adapter)
422
+ self.http_client.mount("https://", adapter)
423
+
424
+ def Moderate(self, request: Optional[ModerateV2Request] = None) -> ModerateV2Response:
425
+ path = "/v2/moderate"
426
+ action = "Moderate"
427
+
428
+ if request is None:
429
+ request = ModerateV2Request()
430
+
431
+ request_body = request.model_dump_json(by_alias=True).encode("utf-8")
432
+
433
+ header = {
434
+ }
435
+
436
+ sign_header = request_sign(
437
+ header, self.ak, self.sk, self.region, self.url, path, action, request_body, self.rewrite_url
438
+ )
439
+
440
+ try:
441
+ resp = self.http_client.post(
442
+ url=self.url + path + "?Action=" + action + "&Version=" + Version,
443
+ data=request_body,
444
+ headers=sign_header
445
+ )
446
+
447
+ response = ModerateV2Response.model_validate(resp.json())
448
+ return response
449
+
450
+ except requests.RequestException as e:
451
+ raise Exception(f"请求失败: {e}")
452
+ except Exception as e:
453
+ raise Exception(f"处理响应失败: {e}")
454
+
455
+ def ModerateStream(
456
+ self, request: ModerateV2Request, session: ModerateV2StreamSession
457
+ ) -> Optional[ModerateV2Response]:
458
+ """
459
+ 处理流式审核请求
460
+ :param request: 当前流式请求片段(ModerateV2Request 类型)
461
+ :param session: 流式会话对象(ModerateV2StreamSession 类型)
462
+ :return: 审核响应(ModerateV2Response 类型)
463
+ """
464
+ # 1. 校验参数合法性
465
+ path = "/v2/moderate"
466
+ action = "Moderate"
467
+ if request is None:
468
+ request = ModerateV2Request() # 初始化空请求
469
+
470
+ # 本接口仅支持流式调用(use_stream 不能为 0,且 session 不能为空)
471
+ if request.use_stream == 0 or session is None:
472
+ raise ValueError("use_stream cannot be 0, and session cannot be None")
473
+
474
+ is_first_request = (session.request is None) # 判断是否为首次请求
475
+ is_last_request = (request.use_stream == 2) # 判断是否为最后一次请求
476
+
477
+ # 2. 初始化或追加会话请求(深拷贝确保隔离)
478
+ if session.request is None:
479
+ # 首次请求:深拷贝初始请求到 session
480
+ session.request = ModerateV2Request(request)
481
+ else:
482
+ # 后续请求:追加当前请求内容到 session 积累的请求中
483
+ # 示例:追加 message.content(根据实际业务调整)
484
+ if request.message and request.message.content:
485
+ if session.request.message is None:
486
+ session.request.message = MessageV2()
487
+ session.request.message.content += request.message.content
488
+ session.request.use_stream = request.use_stream
489
+ if request.call_generate_on_optimize is not None:
490
+ session.request.call_generate_on_optimize = request.call_generate_on_optimize
491
+ session.stream_send_len += len(request.message.content)
492
+
493
+ # 3. 判断是否需要发送请求到后端
494
+ # 只有当未检测长度 >= 10 或者是第一次或者是最后一次请求时,才发送请求
495
+ need_send_request = is_last_request or is_first_request or (
496
+ session.stream_send_len >= session.CurrentSendWindow)
497
+
498
+ # 如果不需要发送请求,直接返回上次的默认响应(如果有)
499
+ if not need_send_request:
500
+ return session.default_body
501
+ else:
502
+ session.CurrentSendWindow = session.CurrentSendWindow * LLM_STREAM_SEND_EXPONENT_V2
503
+
504
+ # 3. 序列化请求(使用 Pydantic 的 model_dump 方法)
505
+ try:
506
+ request_body = session.request.model_dump_json(by_alias=True).encode("utf-8")
507
+ # request_str = session.request.model_dump_json(by_alias=True)
508
+ except Exception as e:
509
+ raise IOError(f"Failed to serialize request: {str(e)}")
510
+ headers = {
511
+ # "Content-Type": "application/json",
512
+ }
513
+ sign_header = request_sign(
514
+ headers, self.ak, self.sk, self.region, self.url, path, action, request_body, self.rewrite_url
515
+ )
516
+ try:
517
+ response = self.http_client.post(
518
+ url=self.url + path + "?Action=" + action + "&Version=" + Version,
519
+ data=request_body,
520
+ headers=sign_header
521
+ )
522
+ except requests.exceptions.RequestException as e:
523
+ raise IOError(f"HTTP request failed: {str(e)}")
524
+
525
+ # 5. 解析响应
526
+ try:
527
+ response_data = json.loads(response.text)
528
+ moderate_response = ModerateV2Response(**response_data)
529
+ except Exception as e:
530
+ raise IOError(f"Failed to parse response: {str(e)}")
531
+
532
+ # 6. 更新会话状态
533
+ session.default_body = moderate_response # 存储响应体
534
+ session.stream_send_len = 0 # 重置未发送长度(根据实际业务调整)
535
+ session.request.msg_id = moderate_response.result.msg_id
536
+
537
+ # 7. 若为最后一次流式请求(use_stream == 2),打印最终内容
538
+ if session.request.use_stream == 2:
539
+ final_content = session.request.message.content if (
540
+ session.request.message and session.request.message.content) else ""
541
+ print(f"最终检测内容: {final_content}")
542
+
543
+ return moderate_response
544
+
545
+ def GenerateV2Stream(self, request):
546
+ path = "/v2/generate"
547
+ action = "Generate"
548
+ if request is None:
549
+ request = GenerateStreamV2Request()
550
+
551
+ # 将请求结构体序列化为 JSON
552
+ requestBody = request.model_dump_json(by_alias=True).encode("utf-8")
553
+
554
+ headers = {
555
+ # "Content-Type": "application/json",
556
+ }
557
+ try:
558
+ sign_header = request_sign(
559
+ headers, self.ak, self.sk, self.region, self.url, path, action, requestBody, self.rewrite_url
560
+ )
561
+ # 发送 HTTP 请求
562
+ resp = self.http_client.post(url=self.url + path + "?Action=" + action + "&Version=" + Version,
563
+ data=requestBody, headers=sign_header, stream=True)
564
+ if resp.status_code != 200:
565
+ raise Exception("bad response code: %d" % resp.status_code)
566
+
567
+ for line in resp.iter_lines():
568
+ if line:
569
+ line = line.decode('utf-8')
570
+ if line.lstrip().startswith('data:'):
571
+ sse_data = line[line.index(':') + 1:].strip()
572
+ yield sse_data
573
+ except Exception as e:
574
+ return None, Exception("failed to send request: %s" % str(e))
575
+
576
+
577
+ # 自定义 JSON 编码器
578
+ class CustomJSONEncoder(json.JSONEncoder):
579
+ def default(self, obj):
580
+ # 处理datetime类型(如2023-10-01T12:00:00)
581
+ if isinstance(obj, datetime):
582
+ return obj.isoformat()
583
+ # 处理date类型(如2023-10-01)
584
+ elif isinstance(obj, date):
585
+ return obj.isoformat()
586
+ # 处理UUID类型
587
+ elif isinstance(obj, UUID):
588
+ return str(obj)
589
+ # 处理其他未知的自定义类型(返回类型信息便于调试)
590
+ elif hasattr(obj, '__dict__'):
591
+ return obj.__dict__ # 返回对象的属性字典
592
+ # 调用默认处理(会抛出TypeError)
593
+ return super().default(obj)
594
+
595
+
596
+ RiskMatchV2.model_rebuild()
597
+ RiskV2.model_rebuild()
@@ -0,0 +1,20 @@
1
+ # coding:utf-8
2
+
3
+ from __future__ import absolute_import
4
+
5
+ from .llm_shield_sign import (
6
+ request_sign,
7
+ Service,
8
+ Version,
9
+ ContentType,
10
+ Method
11
+ )
12
+
13
+ __all__ = [
14
+ 'request_sign',
15
+ 'Service',
16
+ 'Version',
17
+ 'ContentType',
18
+ 'Method'
19
+ ]
20
+
@@ -0,0 +1,172 @@
1
+ # coding:utf-8
2
+ """
3
+ Copyright (year) BytePlus Technology Ltd.
4
+
5
+ Licensed under the Apache License, Version 2.0 (the "License");
6
+ you may not use this file except in compliance with the License.
7
+ You may obtain a copy of the License at
8
+
9
+ http://www.apache.org/licenses/LICENSE-2.0
10
+
11
+ Unless required by applicable law or agreed to in writing, software
12
+ distributed under the License is distributed on an "AS IS" BASIS,
13
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ See the License for the specific language governing permissions and
15
+ limitations under the License.
16
+ """
17
+
18
+ import datetime
19
+ import hashlib
20
+ import hmac
21
+ from urllib.parse import quote, urlparse
22
+ import requests
23
+
24
+ # 以下参数视服务不同而不同,一个服务内通常是一致的
25
+ Version = "2025-08-31"
26
+ ContentType = "application/json"
27
+ Method = "POST"
28
+
29
+ ServiceCodeDev = "llmshield_dev"
30
+ ServiceCodeOnline = "llmshield"
31
+ Service = ServiceCodeOnline
32
+
33
+ def SetServiceDev(IsDev :bool):
34
+ global Service, ServiceCodeDev, ServiceCodeOnline
35
+ if IsDev:
36
+ Service = ServiceCodeDev
37
+ else:
38
+ Service = ServiceCodeOnline
39
+
40
+ def GetServiceCode():
41
+ global Service
42
+ return Service
43
+
44
+ def norm_query(params):
45
+ query = ""
46
+ for key in sorted(params.keys()):
47
+ if type(params[key]) == list:
48
+ for k in params[key]:
49
+ query = (
50
+ query + quote(key, safe="-_.~") + "=" + quote(k, safe="-_.~") + "&"
51
+ )
52
+ else:
53
+ query = (query + quote(key, safe="-_.~") + "=" + quote(params[key], safe="-_.~") + "&")
54
+ query = query[:-1]
55
+ return query.replace("+", "%20")
56
+
57
+
58
+ # 第一步:准备辅助函数。
59
+ # sha256 非对称加密
60
+ def hmac_sha256(key: bytes, content: str):
61
+ return hmac.new(key, content.encode("utf-8"), hashlib.sha256).digest()
62
+
63
+
64
+ # sha256 hash算法
65
+ def hash_sha256(content: bytes):
66
+ return hashlib.sha256(content).hexdigest()
67
+
68
+
69
+ # 第二步:签名请求函数
70
+ def request_sign(header, ak, sk, region, url, path, action, body, rewrite_url=None):
71
+ sign_url = rewrite_url or url
72
+ host = urlparse(sign_url).netloc
73
+ date = utc_now()
74
+ # 第三步:创建身份证明。其中的 Service 和 Region 字段是固定的。ak 和 sk 分别代表
75
+ # AccessKeyID 和 SecretAccessKey。同时需要初始化签名结构体。一些签名计算时需要的属性也在这里处理。
76
+ # 初始化身份证明结构体
77
+ credential = {
78
+ "access_key_id": ak,
79
+ "secret_access_key": sk,
80
+ "service": Service,
81
+ "region": region,
82
+ }
83
+ # 初始化签名结构体
84
+ request_param = {
85
+ "body": body,
86
+ "host": host,
87
+ "path": path,
88
+ "method": Method,
89
+ "content_type": ContentType,
90
+ "date": date,
91
+ "query": {"Action": action, "Version": Version},
92
+ }
93
+ if body is None:
94
+ request_param["body"] = ""
95
+ # 第四步:接下来开始计算签名。在计算签名前,先准备好用于接收签算结果的 signResult 变量,并设置一些参数。
96
+ # 初始化签名结果的结构体
97
+ x_date = request_param["date"].strftime("%Y%m%dT%H%M%SZ")
98
+ short_x_date = x_date[:8]
99
+ x_content_sha256 = hash_sha256(request_param["body"])
100
+ sign_result = {
101
+ "X-Content-Sha256": x_content_sha256,
102
+ "X-Date": x_date,
103
+ "Content-Type": request_param["content_type"],
104
+ }
105
+ # 第五步:计算 Signature 签名。
106
+ signed_headers_str = ";".join(
107
+ ["content-type", "host", "x-content-sha256", "x-date"]
108
+ )
109
+ # signed_headers_str = signed_headers_str + ";x-security-token"
110
+ canonical_request_str = "\n".join(
111
+ [request_param["method"].upper(),
112
+ request_param["path"],
113
+ norm_query(request_param["query"]),
114
+ "\n".join(
115
+ [
116
+ "content-type:" + request_param["content_type"],
117
+ "host:" + request_param["host"],
118
+ "x-content-sha256:" + x_content_sha256,
119
+ "x-date:" + x_date,
120
+ ]
121
+ ),
122
+ "",
123
+ signed_headers_str,
124
+ x_content_sha256,
125
+ ]
126
+ )
127
+
128
+ # 打印正规化的请求用于调试比对
129
+ # print(canonical_request_str)
130
+ hashed_canonical_request = hash_sha256(canonical_request_str.encode("utf-8"))
131
+
132
+ # 打印hash值用于调试比对
133
+ # print(hashed_canonical_request)
134
+ credential_scope = "/".join([short_x_date, credential["region"], credential["service"], "request"])
135
+ string_to_sign = "\n".join(["HMAC-SHA256", x_date, credential_scope, hashed_canonical_request])
136
+
137
+ # 打印最终计算的签名字符串用于调试比对
138
+ # print(string_to_sign)
139
+ k_date = hmac_sha256(credential["secret_access_key"].encode("utf-8"), short_x_date)
140
+ k_region = hmac_sha256(k_date, credential["region"])
141
+ k_service = hmac_sha256(k_region, credential["service"])
142
+ k_signing = hmac_sha256(k_service, "request")
143
+ signature = hmac_sha256(k_signing, string_to_sign).hex()
144
+
145
+ sign_result["Authorization"] = "HMAC-SHA256 Credential={}, SignedHeaders={}, Signature={}".format(
146
+ credential["access_key_id"] + "/" + credential_scope,
147
+ signed_headers_str,
148
+ signature,
149
+ )
150
+ header = {**header, **sign_result, "X-Top-Service": Service, "X-Top-Region": region}
151
+ # header = {**header, **{"X-Security-Token": SessionToken}}
152
+ # 第六步:将 Signature 签名写入 HTTP Header 中,并发送 HTTP 请求。
153
+ return header
154
+
155
+
156
+ # datetime.utcnow() 在 3.12+ 已经过期,使用如下方法兼容
157
+ def utc_now():
158
+ try:
159
+ from datetime import timezone
160
+ return datetime.datetime.now(timezone.utc)
161
+ except ImportError:
162
+ class UTC(datetime.tzinfo):
163
+ def utcoffset(self, dt):
164
+ return datetime.timedelta(0)
165
+
166
+ def tzname(self, dt):
167
+ return "UTC"
168
+
169
+ def dst(self, dt):
170
+ return datetime.timedelta(0)
171
+
172
+ return datetime.datetime.now(UTC())