koreshield 0.1.3__tar.gz → 0.2.0__tar.gz

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.
Files changed (37) hide show
  1. koreshield-0.2.0/PKG-INFO +681 -0
  2. koreshield-0.2.0/README.md +625 -0
  3. koreshield-0.2.0/examples/batch_processing.py +78 -0
  4. koreshield-0.2.0/examples/framework_integrations.py +171 -0
  5. koreshield-0.2.0/examples/streaming_scan.py +137 -0
  6. {koreshield-0.1.3 → koreshield-0.2.0}/pyproject.toml +13 -4
  7. koreshield-0.2.0/src/koreshield.egg-info/PKG-INFO +681 -0
  8. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield.egg-info/SOURCES.txt +7 -1
  9. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield.egg-info/requires.txt +8 -1
  10. koreshield-0.2.0/src/koreshield_sdk/async_client.py +544 -0
  11. koreshield-0.2.0/src/koreshield_sdk/integrations/__init__.py +39 -0
  12. koreshield-0.2.0/src/koreshield_sdk/integrations/frameworks.py +361 -0
  13. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/types.py +53 -1
  14. koreshield-0.2.0/tests/test_async_client.py +115 -0
  15. {koreshield-0.1.3 → koreshield-0.2.0}/tests/test_client.py +2 -1
  16. koreshield-0.2.0/tests/test_integrations.py +273 -0
  17. koreshield-0.1.3/PKG-INFO +0 -455
  18. koreshield-0.1.3/README.md +0 -387
  19. koreshield-0.1.3/src/koreshield.egg-info/PKG-INFO +0 -455
  20. koreshield-0.1.3/src/koreshield_sdk/async_client.py +0 -263
  21. koreshield-0.1.3/src/koreshield_sdk/integrations/__init__.py +0 -15
  22. {koreshield-0.1.3 → koreshield-0.2.0}/CHANGELOG.md +0 -0
  23. {koreshield-0.1.3 → koreshield-0.2.0}/LICENSE +0 -0
  24. {koreshield-0.1.3 → koreshield-0.2.0}/MANIFEST.in +0 -0
  25. {koreshield-0.1.3 → koreshield-0.2.0}/examples/async_usage.py +0 -0
  26. {koreshield-0.1.3 → koreshield-0.2.0}/examples/basic_usage.py +0 -0
  27. {koreshield-0.1.3 → koreshield-0.2.0}/examples/deepseek_integration.py +0 -0
  28. {koreshield-0.1.3 → koreshield-0.2.0}/examples/fastapi_integration.py +0 -0
  29. {koreshield-0.1.3 → koreshield-0.2.0}/examples/langchain_integration.py +0 -0
  30. {koreshield-0.1.3 → koreshield-0.2.0}/setup.cfg +0 -0
  31. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield.egg-info/dependency_links.txt +0 -0
  32. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield.egg-info/top_level.txt +0 -0
  33. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/__init__.py +0 -0
  34. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/client.py +0 -0
  35. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/exceptions.py +0 -0
  36. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/integrations/langchain.py +0 -0
  37. {koreshield-0.1.3 → koreshield-0.2.0}/src/koreshield_sdk/py.typed +0 -0
@@ -0,0 +1,681 @@
1
+ Metadata-Version: 2.4
2
+ Name: koreshield
3
+ Version: 0.2.0
4
+ Summary: Python SDK for KoreShield LLM Security Platform
5
+ Author-email: KoreShield Team <team@koreshield.com>
6
+ Maintainer-email: KoreShield Team <team@koreshield.com>
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://koreshield.com
9
+ Project-URL: Documentation, https://docs.koreshield.com
10
+ Project-URL: Repository, https://github.com/koreshield/koreshield.git
11
+ Project-URL: Issues, https://github.com/koreshield/koreshield/issues
12
+ Project-URL: Changelog, https://github.com/koreshield/koreshield/blob/main/koreshield-python-sdk/CHANGELOG.md
13
+ Project-URL: PyPI, https://pypi.org/project/koreshield/
14
+ Keywords: llm,security,ai,safety,prompt-injection,koreshield
15
+ Classifier: Development Status :: 3 - Alpha
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.8
20
+ Classifier: Programming Language :: Python :: 3.9
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Security
26
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
27
+ Requires-Python: >=3.8
28
+ Description-Content-Type: text/markdown
29
+ License-File: LICENSE
30
+ Requires-Dist: httpx>=0.24.0
31
+ Requires-Dist: pydantic>=2.0.0
32
+ Requires-Dist: typing-extensions>=4.5.0
33
+ Requires-Dist: aiofiles>=0.23.0
34
+ Provides-Extra: langchain
35
+ Requires-Dist: langchain>=0.0.350; extra == "langchain"
36
+ Requires-Dist: langchain-core>=0.1.0; extra == "langchain"
37
+ Provides-Extra: fastapi
38
+ Requires-Dist: fastapi>=0.100.0; extra == "fastapi"
39
+ Requires-Dist: uvicorn>=0.23.0; extra == "fastapi"
40
+ Provides-Extra: flask
41
+ Requires-Dist: flask>=2.3.0; extra == "flask"
42
+ Requires-Dist: werkzeug>=2.3.0; extra == "flask"
43
+ Provides-Extra: django
44
+ Requires-Dist: django>=4.2.0; extra == "django"
45
+ Requires-Dist: djangorestframework>=3.14.0; extra == "django"
46
+ Provides-Extra: all
47
+ Requires-Dist: langchain>=0.0.350; extra == "all"
48
+ Requires-Dist: langchain-core>=0.1.0; extra == "all"
49
+ Requires-Dist: fastapi>=0.100.0; extra == "all"
50
+ Requires-Dist: uvicorn>=0.23.0; extra == "all"
51
+ Requires-Dist: flask>=2.3.0; extra == "all"
52
+ Requires-Dist: werkzeug>=2.3.0; extra == "all"
53
+ Requires-Dist: django>=4.2.0; extra == "all"
54
+ Requires-Dist: djangorestframework>=3.14.0; extra == "all"
55
+ Dynamic: license-file
56
+
57
+ # KoreShield Python SDK
58
+
59
+ [![PyPI version](https://badge.fury.io/py/koreshield-python-sdk.svg)](https://pypi.org/project/koreshield-python-sdk/)
60
+ [![Python versions](https://img.shields.io/pypi/pyversions/koreshield-python-sdk)](https://pypi.org/project/koreshield-python-sdk/)
61
+ [![License](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)
62
+
63
+ A comprehensive Python SDK for integrating KoreShield's LLM security features into your applications with ease.
64
+
65
+ ## New in v0.2.0
66
+
67
+ - **Enhanced Async Support**: Improved async/await patterns with context managers and performance monitoring
68
+ - **Advanced Batch Processing**: Optimized batch scanning with progress callbacks, concurrency control, and batching
69
+ - **Streaming Content Scanning**: Real-time scanning of long content with overlapping chunks
70
+ - **Security Policies**: Configurable allowlist/blocklist patterns and custom threat rules
71
+ - **Framework Integrations**: Built-in middleware for FastAPI, Flask, and Django
72
+ - **Performance Monitoring**: Comprehensive metrics collection and analytics
73
+ - **Type Safety**: Full Pydantic models for all data structures
74
+
75
+ ## Supported LLM Providers
76
+
77
+ KoreShield supports multiple LLM providers through its proxy architecture. Configure your preferred provider in the KoreShield API:
78
+
79
+ - **DeepSeek** (OpenAI-compatible API)
80
+ - **OpenAI** (GPT models)
81
+ - **Anthropic** (Claude models)
82
+ - **Google Gemini** (coming soon)
83
+ - **Azure OpenAI** (coming soon)
84
+
85
+ ### Provider Configuration
86
+
87
+ Configure providers in your KoreShield `config.yaml`:
88
+
89
+ ```yaml
90
+ providers:
91
+ deepseek:
92
+ enabled: true
93
+ base_url: "https://api.deepseek.com/v1"
94
+
95
+ openai:
96
+ enabled: false
97
+ base_url: "https://api.openai.com/v1"
98
+
99
+ anthropic:
100
+ enabled: false
101
+ base_url: "https://api.anthropic.com/v1"
102
+ ```
103
+
104
+ Set the corresponding API key as an environment variable:
105
+ ```bash
106
+ export DEEPSEEK_API_KEY="your-deepseek-key"
107
+ # or
108
+ export OPENAI_API_KEY="your-openai-key"
109
+ # or
110
+ export ANTHROPIC_API_KEY="your-anthropic-key"
111
+ ```
112
+
113
+ ```bash
114
+ pip install koreshield
115
+ ```
116
+
117
+ ### Optional Dependencies
118
+
119
+ For LangChain integration:
120
+ ```bash
121
+ pip install koreshield-python-sdk[langchain]
122
+ ```
123
+
124
+ For framework integrations:
125
+ ```bash
126
+ pip install koreshield-python-sdk[fastapi,flask,django]
127
+ ```
128
+
129
+ ## Quick Start
130
+
131
+ ### Basic Usage
132
+
133
+ ```python
134
+ from koreshield import KoreShieldClient
135
+
136
+ # Initialize client
137
+ client = KoreShieldClient(api_key="your-api-key")
138
+
139
+ # Scan a prompt
140
+ result = client.scan_prompt("Hello, how are you?")
141
+ print(f"Safe: {result.is_safe}, Threat Level: {result.threat_level}")
142
+ ```
143
+
144
+ ### Enhanced Async Usage
145
+
146
+ ```python
147
+ import asyncio
148
+ from koreshield_sdk import AsyncKoreShieldClient
149
+
150
+ async def main():
151
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
152
+ result = await client.scan_prompt("Tell me a joke")
153
+ print(f"Confidence: {result.confidence}")
154
+
155
+ # Get performance metrics
156
+ metrics = await client.get_performance_metrics()
157
+ print(f"Total requests: {metrics.total_requests}")
158
+
159
+ asyncio.run(main())
160
+ ```
161
+
162
+ ### LangChain Integration
163
+
164
+ ```python
165
+ from langchain_openai import ChatOpenAI
166
+ from langchain.schema import HumanMessage
167
+ from koreshield_sdk.integrations import create_koreshield_callback
168
+
169
+ # Create security callback
170
+ security_callback = create_koreshield_callback(
171
+ api_key="your-api-key",
172
+ block_on_threat=True,
173
+ threat_threshold="medium"
174
+ )
175
+
176
+ # Use with LangChain
177
+ llm = ChatOpenAI(callbacks=[security_callback])
178
+ response = llm([HumanMessage(content="Hello!")])
179
+ ```
180
+
181
+ ## API Reference
182
+
183
+ ### KoreShieldClient
184
+
185
+ #### Methods
186
+
187
+ - `scan_prompt(prompt: str, **kwargs) -> DetectionResult`
188
+ - `scan_batch(prompts: List[str], parallel=True, max_concurrent=10) -> List[DetectionResult]`
189
+ - `get_scan_history(limit=50, offset=0, **filters) -> Dict`
190
+ - `get_scan_details(scan_id: str) -> Dict`
191
+ - `health_check() -> Dict`
192
+
193
+ ### AsyncKoreShieldClient
194
+
195
+ #### Core Methods
196
+
197
+ - `scan_prompt(prompt: str, **kwargs) -> DetectionResult` (async)
198
+ - `scan_batch(prompts: List[str], parallel=True, max_concurrent=10, progress_callback=None) -> List[DetectionResult]` (async)
199
+ - `scan_stream(content: str, chunk_size=1000, overlap=100, **kwargs) -> StreamingScanResponse` (async)
200
+ - `get_scan_history(limit=50, offset=0, **filters) -> Dict` (async)
201
+ - `get_scan_details(scan_id: str) -> Dict` (async)
202
+ - `health_check() -> Dict` (async)
203
+
204
+ #### Security Policy Methods
205
+
206
+ - `set_security_policy(policy: SecurityPolicy) -> None` (async)
207
+ - `get_security_policy() -> SecurityPolicy` (async)
208
+ - `update_security_policy(**updates) -> SecurityPolicy` (async)
209
+
210
+ #### Performance Monitoring Methods
211
+
212
+ - `get_performance_metrics() -> PerformanceMetrics` (async)
213
+ - `reset_metrics() -> None` (async)
214
+ - `enable_metrics(enabled: bool = True) -> None` (async)
215
+
216
+ ### DetectionResult
217
+
218
+ ```python
219
+ class DetectionResult:
220
+ is_safe: bool
221
+ threat_level: ThreatLevel # "safe", "low", "medium", "high", "critical"
222
+ confidence: float # 0.0 to 1.0
223
+ indicators: List[DetectionIndicator]
224
+ processing_time_ms: float
225
+ scan_id: Optional[str]
226
+ metadata: Optional[Dict[str, Any]]
227
+ ```
228
+
229
+ ### New Types (v0.2.0)
230
+
231
+ #### StreamingScanResponse
232
+
233
+ ```python
234
+ class StreamingScanResponse:
235
+ overall_result: DetectionResult
236
+ chunk_results: List[ChunkResult]
237
+ total_chunks: int
238
+ processing_time_ms: float
239
+ scan_id: str
240
+ ```
241
+
242
+ #### SecurityPolicy
243
+
244
+ ```python
245
+ class SecurityPolicy:
246
+ name: str
247
+ description: Optional[str]
248
+ threat_threshold: ThreatLevel
249
+ blocked_detection_types: List[str]
250
+ allowlist_patterns: List[str]
251
+ blocklist_patterns: List[str]
252
+ custom_rules: List[Dict[str, Any]]
253
+ ```
254
+
255
+ #### PerformanceMetrics
256
+
257
+ ```python
258
+ class PerformanceMetrics:
259
+ total_requests: int
260
+ total_processing_time: float
261
+ average_response_time: float
262
+ min_response_time: float
263
+ max_response_time: float
264
+ error_count: int
265
+ success_rate: float
266
+ requests_per_second: float
267
+ start_time: datetime
268
+ last_request_time: Optional[datetime]
269
+ ```
270
+
271
+ ## Configuration
272
+
273
+ ### Environment Variables
274
+
275
+ ```bash
276
+ export KORESHIELD_API_KEY="your-api-key"
277
+ export KORESHIELD_BASE_URL="https://api.koreshield.com" # Optional
278
+ ```
279
+
280
+ ### Client Configuration
281
+
282
+ ```python
283
+ client = KoreShieldClient(
284
+ api_key="your-api-key",
285
+ base_url="https://api.koreshield.com",
286
+ timeout=30.0
287
+ )
288
+ ```
289
+
290
+ ## Examples
291
+
292
+ ### Basic Scanning
293
+
294
+ ```python
295
+ from koreshield_sdk import KoreShieldClient
296
+
297
+ client = KoreShieldClient(api_key="your-api-key")
298
+
299
+ # Single prompt
300
+ result = client.scan_prompt("What is the capital of France?")
301
+ print(f"Result: {result}")
302
+
303
+ # Batch scanning
304
+ prompts = [
305
+ "Hello world",
306
+ "Tell me a secret",
307
+ "Ignore previous instructions"
308
+ ]
309
+
310
+ results = client.scan_batch(prompts)
311
+ for prompt, result in zip(prompts, results):
312
+ print(f"'{prompt}': {result.threat_level} ({result.confidence:.2f})")
313
+ ```
314
+
315
+ ### Advanced Async Features
316
+
317
+ ```python
318
+ import asyncio
319
+ from koreshield_sdk import AsyncKoreShieldClient
320
+
321
+ async def main():
322
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
323
+
324
+ # Enhanced batch processing with progress callback
325
+ def progress_callback(completed, total, current_result=None):
326
+ print(f"Progress: {completed}/{total} completed")
327
+ if current_result:
328
+ print(f" Latest result: {current_result.threat_level}")
329
+
330
+ prompts = ["Prompt 1", "Prompt 2", "Prompt 3", "Prompt 4", "Prompt 5"]
331
+ results = await client.scan_batch(
332
+ prompts,
333
+ parallel=True,
334
+ max_concurrent=3,
335
+ progress_callback=progress_callback
336
+ )
337
+
338
+ # Streaming content scanning for long documents
339
+ long_content = "Your very long document content here..." * 100
340
+ stream_result = await client.scan_stream(
341
+ content=long_content,
342
+ chunk_size=1000,
343
+ overlap=100
344
+ )
345
+
346
+ print(f"Overall safe: {stream_result.overall_result.is_safe}")
347
+ print(f"Chunks processed: {stream_result.total_chunks}")
348
+
349
+ # Get performance metrics
350
+ metrics = await client.get_performance_metrics()
351
+ print(f"Total requests: {metrics.total_requests}")
352
+ print(".2f"
353
+ asyncio.run(main())
354
+ ```
355
+
356
+ ### Security Policies
357
+
358
+ ```python
359
+ from koreshield_sdk import AsyncKoreShieldClient
360
+ from koreshield_sdk.types import SecurityPolicy, ThreatLevel
361
+
362
+ async def main():
363
+ # Create custom security policy
364
+ policy = SecurityPolicy(
365
+ name="strict_policy",
366
+ description="Strict security for sensitive applications",
367
+ threat_threshold=ThreatLevel.LOW,
368
+ allowlist_patterns=["safe", "trusted"],
369
+ blocklist_patterns=["hack", "exploit", "attack"],
370
+ custom_rules=[
371
+ {"name": "no_code_execution", "pattern": "exec\\(|eval\\("},
372
+ {"name": "no_file_operations", "pattern": "open\\(|file\\("}
373
+ ]
374
+ )
375
+
376
+ async with AsyncKoreShieldClient(
377
+ api_key="your-api-key",
378
+ security_policy=policy
379
+ ) as client:
380
+
381
+ # Test against policy
382
+ test_prompts = [
383
+ "This is a safe message",
384
+ "This contains hack attempts",
385
+ "Let's execute: exec('print(hello)')"
386
+ ]
387
+
388
+ for prompt in test_prompts:
389
+ result = await client.scan_prompt(prompt)
390
+ status = "✅ ALLOWED" if result.is_safe else "❌ BLOCKED"
391
+ print(f"{status}: {prompt}")
392
+
393
+ asyncio.run(main())
394
+ ```
395
+
396
+ ### FastAPI Integration
397
+
398
+ ```python
399
+ from fastapi import FastAPI, Request
400
+ from koreshield_sdk.integrations import create_fastapi_middleware
401
+
402
+ app = FastAPI()
403
+
404
+ # Create and add KoreShield middleware
405
+ middleware = create_fastapi_middleware(
406
+ api_key="your-api-key",
407
+ scan_request_body=True,
408
+ threat_threshold="medium",
409
+ block_on_threat=False, # Log but don't block
410
+ exclude_paths=["/health", "/docs"]
411
+ )
412
+
413
+ app.middleware("http")(middleware)
414
+
415
+ @app.post("/chat")
416
+ async def chat(request: Request, message: str):
417
+ # Request is automatically scanned by middleware
418
+ # Access scan results from request state if needed
419
+ scan_result = getattr(request.state, 'koreshield_result', None)
420
+ if scan_result and not scan_result.is_safe:
421
+ print(f"Threat detected: {scan_result.threat_level}")
422
+
423
+ # Process with your LLM
424
+ response = f"Processed: {message}"
425
+ return {"response": response}
426
+ ```
427
+
428
+ ### Flask Integration
429
+
430
+ ```python
431
+ from flask import Flask, request, jsonify, g
432
+ from koreshield_sdk.integrations import create_flask_middleware
433
+
434
+ app = Flask(__name__)
435
+
436
+ # Create and register KoreShield middleware
437
+ middleware = create_flask_middleware(
438
+ api_key="your-api-key",
439
+ scan_request_body=True,
440
+ threat_threshold="high",
441
+ block_on_threat=True,
442
+ exclude_paths=["/health"]
443
+ )
444
+
445
+ app.before_request(middleware)
446
+
447
+ @app.route("/api/chat", methods=["POST"])
448
+ def chat():
449
+ # Check if request was blocked by middleware
450
+ if hasattr(g, 'koreshield_blocked') and g.koreshield_blocked:
451
+ return jsonify({"error": "Request blocked by security policy"}), 403
452
+
453
+ data = request.get_json()
454
+ message = data.get("message", "")
455
+
456
+ # Access scan results
457
+ scan_result = getattr(g, 'koreshield_result', None)
458
+
459
+ # Process with your LLM
460
+ response = f"Echo: {message}"
461
+ return jsonify({
462
+ "response": response,
463
+ "safety": scan_result.dict() if scan_result else None
464
+ })
465
+ ```
466
+
467
+ ### Django Integration
468
+
469
+ ```python
470
+ # settings.py
471
+ KORESHIELD_CONFIG = {
472
+ 'api_key': 'your-api-key',
473
+ 'scan_request_body': True,
474
+ 'threat_threshold': 'medium',
475
+ 'block_on_threat': False,
476
+ 'exclude_paths': ['/health/', '/admin/']
477
+ }
478
+
479
+ # middleware.py
480
+ from koreshield_sdk.integrations import create_django_middleware
481
+
482
+ KoreShieldMiddleware = create_django_middleware()
483
+
484
+ # views.py
485
+ from django.http import JsonResponse
486
+ from django.views.decorators.csrf import csrf_exempt
487
+ from django.utils.decorators import method_decorator
488
+ from django.views import View
489
+ import json
490
+
491
+ @method_decorator(csrf_exempt, name='dispatch')
492
+ class ChatView(View):
493
+ def post(self, request):
494
+ # Check if request was blocked by middleware
495
+ if hasattr(request, 'koreshield_blocked') and request.koreshield_blocked:
496
+ return JsonResponse({"error": "Request blocked by security policy"}, status=403)
497
+
498
+ data = json.loads(request.body)
499
+ message = data.get("message", "")
500
+
501
+ # Access scan results
502
+ scan_result = getattr(request, 'koreshield_result', None)
503
+
504
+ # Process with your LLM
505
+ response = f"Response to: {message}"
506
+ return JsonResponse({
507
+ "response": response,
508
+ "safety_check": scan_result.dict() if scan_result else None
509
+ })
510
+ ```
511
+
512
+ ## Error Handling
513
+
514
+ ```python
515
+ from koreshield_sdk import KoreShieldClient
516
+ from koreshield_sdk.exceptions import (
517
+ AuthenticationError,
518
+ ValidationError,
519
+ RateLimitError,
520
+ ServerError,
521
+ NetworkError,
522
+ TimeoutError
523
+ )
524
+
525
+ client = KoreShieldClient(api_key="your-api-key")
526
+
527
+ try:
528
+ result = client.scan_prompt("Test prompt")
529
+ except AuthenticationError:
530
+ print("Invalid API key")
531
+ except RateLimitError:
532
+ print("Rate limit exceeded")
533
+ except ServerError:
534
+ print("Server error")
535
+ except NetworkError:
536
+ print("Network issue")
537
+ except TimeoutError:
538
+ print("Request timed out")
539
+ except Exception as e:
540
+ print(f"Unexpected error: {e}")
541
+ ```
542
+
543
+ ## Advanced Usage
544
+
545
+ ### Custom Threat Thresholds
546
+
547
+ ```python
548
+ # Only block on high/critical threats
549
+ callback = create_koreshield_callback(
550
+ api_key="your-api-key",
551
+ block_on_threat=True,
552
+ threat_threshold="high" # "low", "medium", "high", "critical"
553
+ )
554
+ ```
555
+
556
+ ### Batch Processing with Custom Concurrency
557
+
558
+ ```python
559
+ # Process 100 prompts with controlled concurrency
560
+ results = await client.scan_batch(
561
+ prompts=prompts,
562
+ parallel=True,
563
+ max_concurrent=5 # Limit to 5 concurrent requests
564
+ )
565
+ ```
566
+
567
+ ### Streaming Content Scanning
568
+
569
+ ```python
570
+ # Scan long documents with overlapping chunks
571
+ long_document = "Very long content..." * 1000
572
+
573
+ result = await client.scan_stream(
574
+ content=long_document,
575
+ chunk_size=2000, # Process in 2000-character chunks
576
+ overlap=200 # 200-character overlap between chunks
577
+ )
578
+
579
+ print(f"Overall safe: {result.overall_result.is_safe}")
580
+ print(f"Total chunks: {result.total_chunks}")
581
+ for i, chunk_result in enumerate(result.chunk_results):
582
+ print(f"Chunk {i+1}: {chunk_result.result.threat_level}")
583
+ ```
584
+
585
+ ### Performance Monitoring
586
+
587
+ ```python
588
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
589
+ # Perform operations...
590
+ await client.scan_prompt("Test prompt")
591
+ await client.scan_batch(["Prompt 1", "Prompt 2"])
592
+
593
+ # Get comprehensive metrics
594
+ metrics = await client.get_performance_metrics()
595
+ print(f"Total requests: {metrics.total_requests}")
596
+ print(".2f" print(".2f" print(f"Success rate: {metrics.success_rate:.1%}")
597
+
598
+ # Reset metrics if needed
599
+ await client.reset_metrics()
600
+ ```
601
+
602
+ ### Security Policy Management
603
+
604
+ ```python
605
+ from koreshield_sdk.types import SecurityPolicy, ThreatLevel
606
+
607
+ # Create and apply custom policy
608
+ policy = SecurityPolicy(
609
+ name="enterprise_policy",
610
+ threat_threshold=ThreatLevel.MEDIUM,
611
+ allowlist_patterns=["approved", "safe"],
612
+ blocklist_patterns=["banned", "dangerous"],
613
+ custom_rules=[
614
+ {"name": "no_pii", "pattern": "\\b\\d{3}-\\d{2}-\\d{4}\\b"}, # SSN pattern
615
+ {"name": "no_emails", "pattern": "\\S+@\\S+\\.\\S+"}
616
+ ]
617
+ )
618
+
619
+ await client.set_security_policy(policy)
620
+
621
+ # Update policy dynamically
622
+ await client.update_security_policy(threat_threshold=ThreatLevel.HIGH)
623
+
624
+ # Get current policy
625
+ current_policy = await client.get_security_policy()
626
+ print(f"Current threshold: {current_policy.threat_threshold}")
627
+ ```
628
+
629
+ ### Monitoring and Analytics
630
+
631
+ ```python
632
+ # Get scan history
633
+ history = client.get_scan_history(limit=100, threat_level="high")
634
+
635
+ # Get detailed scan info
636
+ details = client.get_scan_details(scan_id="scan_123")
637
+ ```
638
+
639
+ ## Development
640
+
641
+ ### Setup
642
+
643
+ ```bash
644
+ git clone https://github.com/koreshield/koreshield-python-sdk.git
645
+ cd koreshield-python-sdk
646
+ pip install -e ".[dev]"
647
+ ```
648
+
649
+ ### Testing
650
+
651
+ ```bash
652
+ pytest
653
+ ```
654
+
655
+ ### Type Checking
656
+
657
+ ```bash
658
+ mypy src/
659
+ ```
660
+
661
+ ### Linting
662
+
663
+ ```bash
664
+ ruff check src/
665
+ ruff format src/
666
+ ```
667
+
668
+ ## Contributing
669
+
670
+ We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
671
+
672
+ ## License
673
+
674
+ MIT License - see [LICENSE](LICENSE) file for details.
675
+
676
+ ## Support
677
+
678
+ - [Documentation](https://docs.koreshield.com)
679
+ - [Issue Tracker](https://github.com/koreshield/koreshield-python-sdk/issues)
680
+ - [Discussions](https://github.com/koreshield/koreshield-python-sdk/discussions)
681
+ - [Email Support](mailto:support@koreshield.com)