koreshield 0.1.5__py3-none-any.whl → 0.2.1__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: koreshield
3
- Version: 0.1.5
3
+ Version: 0.2.1
4
4
  Summary: Python SDK for KoreShield LLM Security Platform
5
5
  Author-email: KoreShield Team <team@koreshield.com>
6
6
  Maintainer-email: KoreShield Team <team@koreshield.com>
@@ -10,6 +10,7 @@ Project-URL: Documentation, https://docs.koreshield.com
10
10
  Project-URL: Repository, https://github.com/koreshield/koreshield.git
11
11
  Project-URL: Issues, https://github.com/koreshield/koreshield/issues
12
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/
13
14
  Keywords: llm,security,ai,safety,prompt-injection,koreshield
14
15
  Classifier: Development Status :: 3 - Alpha
15
16
  Classifier: Intended Audience :: Developers
@@ -61,6 +62,16 @@ Dynamic: license-file
61
62
 
62
63
  A comprehensive Python SDK for integrating KoreShield's LLM security features into your applications with ease.
63
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
+
64
75
  ## Supported LLM Providers
65
76
 
66
77
  KoreShield supports multiple LLM providers through its proxy architecture. Configure your preferred provider in the KoreShield API:
@@ -80,11 +91,11 @@ providers:
80
91
  deepseek:
81
92
  enabled: true
82
93
  base_url: "https://api.deepseek.com/v1"
83
-
94
+
84
95
  openai:
85
96
  enabled: false
86
97
  base_url: "https://api.openai.com/v1"
87
-
98
+
88
99
  anthropic:
89
100
  enabled: false
90
101
  base_url: "https://api.anthropic.com/v1"
@@ -95,7 +106,7 @@ Set the corresponding API key as an environment variable:
95
106
  export DEEPSEEK_API_KEY="your-deepseek-key"
96
107
  # or
97
108
  export OPENAI_API_KEY="your-openai-key"
98
- # or
109
+ # or
99
110
  export ANTHROPIC_API_KEY="your-anthropic-key"
100
111
  ```
101
112
 
@@ -130,17 +141,21 @@ result = client.scan_prompt("Hello, how are you?")
130
141
  print(f"Safe: {result.is_safe}, Threat Level: {result.threat_level}")
131
142
  ```
132
143
 
133
- ### Async Usage
144
+ ### Enhanced Async Usage
134
145
 
135
146
  ```python
136
147
  import asyncio
137
148
  from koreshield_sdk import AsyncKoreShieldClient
138
149
 
139
150
  async def main():
140
- async with AsyncKoreShieldClient(api_key="your-api-key") as client:
151
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
141
152
  result = await client.scan_prompt("Tell me a joke")
142
153
  print(f"Confidence: {result.confidence}")
143
154
 
155
+ # Get performance metrics
156
+ metrics = await client.get_performance_metrics()
157
+ print(f"Total requests: {metrics.total_requests}")
158
+
144
159
  asyncio.run(main())
145
160
  ```
146
161
 
@@ -298,16 +313,29 @@ async with AsyncKoreShieldClient(api_key="your-key") as client:
298
313
 
299
314
  ### AsyncKoreShieldClient
300
315
 
301
- #### Methods
316
+ #### Core Methods
302
317
 
303
318
  - `scan_prompt(prompt: str, **kwargs) -> DetectionResult` (async)
304
- - `scan_batch(prompts: List[str], parallel=True, max_concurrent=10) -> List[DetectionResult]` (async)
319
+ - `scan_batch(prompts: List[str], parallel=True, max_concurrent=10, progress_callback=None) -> List[DetectionResult]` (async)
305
320
  - `scan_rag_context(user_query: str, documents: List[Union[Dict, RAGDocument]], config: Optional[Dict] = None) -> RAGScanResponse` (async)
306
321
  - `scan_rag_context_batch(queries_and_docs: List[Dict], parallel=True, max_concurrent= 5) -> List[RAGScanResponse]` (async)
322
+ - `scan_stream(content: str, chunk_size=1000, overlap=100, **kwargs) -> StreamingScanResponse` (async)
307
323
  - `get_scan_history(limit=50, offset=0, **filters) -> Dict` (async)
308
324
  - `get_scan_details(scan_id: str) -> Dict` (async)
309
325
  - `health_check() -> Dict` (async)
310
326
 
327
+ #### Security Policy Methods
328
+
329
+ - `set_security_policy(policy: SecurityPolicy) -> None` (async)
330
+ - `get_security_policy() -> SecurityPolicy` (async)
331
+ - `update_security_policy(**updates) -> SecurityPolicy` (async)
332
+
333
+ #### Performance Monitoring Methods
334
+
335
+ - `get_performance_metrics() -> PerformanceMetrics` (async)
336
+ - `reset_metrics() -> None` (async)
337
+ - `enable_metrics(enabled: bool = True) -> None` (async)
338
+
311
339
  ### DetectionResult
312
340
 
313
341
  ```python
@@ -321,6 +349,48 @@ class DetectionResult:
321
349
  metadata: Optional[Dict[str, Any]]
322
350
  ```
323
351
 
352
+ ### New Types (v0.2.0)
353
+
354
+ #### StreamingScanResponse
355
+
356
+ ```python
357
+ class StreamingScanResponse:
358
+ overall_result: DetectionResult
359
+ chunk_results: List[ChunkResult]
360
+ total_chunks: int
361
+ processing_time_ms: float
362
+ scan_id: str
363
+ ```
364
+
365
+ #### SecurityPolicy
366
+
367
+ ```python
368
+ class SecurityPolicy:
369
+ name: str
370
+ description: Optional[str]
371
+ threat_threshold: ThreatLevel
372
+ blocked_detection_types: List[str]
373
+ allowlist_patterns: List[str]
374
+ blocklist_patterns: List[str]
375
+ custom_rules: List[Dict[str, Any]]
376
+ ```
377
+
378
+ #### PerformanceMetrics
379
+
380
+ ```python
381
+ class PerformanceMetrics:
382
+ total_requests: int
383
+ total_processing_time: float
384
+ average_response_time: float
385
+ min_response_time: float
386
+ max_response_time: float
387
+ error_count: int
388
+ success_rate: float
389
+ requests_per_second: float
390
+ start_time: datetime
391
+ last_request_time: Optional[datetime]
392
+ ```
393
+
324
394
  ## Configuration
325
395
 
326
396
  ### Environment Variables
@@ -365,93 +435,200 @@ for prompt, result in zip(prompts, results):
365
435
  print(f"'{prompt}': {result.threat_level} ({result.confidence:.2f})")
366
436
  ```
367
437
 
438
+ ### Advanced Async Features
439
+
440
+ ```python
441
+ import asyncio
442
+ from koreshield_sdk import AsyncKoreShieldClient
443
+
444
+ async def main():
445
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
446
+
447
+ # Enhanced batch processing with progress callback
448
+ def progress_callback(completed, total, current_result=None):
449
+ print(f"Progress: {completed}/{total} completed")
450
+ if current_result:
451
+ print(f" Latest result: {current_result.threat_level}")
452
+
453
+ prompts = ["Prompt 1", "Prompt 2", "Prompt 3", "Prompt 4", "Prompt 5"]
454
+ results = await client.scan_batch(
455
+ prompts,
456
+ parallel=True,
457
+ max_concurrent=3,
458
+ progress_callback=progress_callback
459
+ )
460
+
461
+ # Streaming content scanning for long documents
462
+ long_content = "Your very long document content here..." * 100
463
+ stream_result = await client.scan_stream(
464
+ content=long_content,
465
+ chunk_size=1000,
466
+ overlap=100
467
+ )
468
+
469
+ print(f"Overall safe: {stream_result.overall_result.is_safe}")
470
+ print(f"Chunks processed: {stream_result.total_chunks}")
471
+
472
+ # Get performance metrics
473
+ metrics = await client.get_performance_metrics()
474
+ print(f"Total requests: {metrics.total_requests}")
475
+ print(".2f"
476
+ asyncio.run(main())
477
+ ```
478
+
479
+ ### Security Policies
480
+
481
+ ```python
482
+ from koreshield_sdk import AsyncKoreShieldClient
483
+ from koreshield_sdk.types import SecurityPolicy, ThreatLevel
484
+
485
+ async def main():
486
+ # Create custom security policy
487
+ policy = SecurityPolicy(
488
+ name="strict_policy",
489
+ description="Strict security for sensitive applications",
490
+ threat_threshold=ThreatLevel.LOW,
491
+ allowlist_patterns=["safe", "trusted"],
492
+ blocklist_patterns=["hack", "exploit", "attack"],
493
+ custom_rules=[
494
+ {"name": "no_code_execution", "pattern": "exec\\(|eval\\("},
495
+ {"name": "no_file_operations", "pattern": "open\\(|file\\("}
496
+ ]
497
+ )
498
+
499
+ async with AsyncKoreShieldClient(
500
+ api_key="your-api-key",
501
+ security_policy=policy
502
+ ) as client:
503
+
504
+ # Test against policy
505
+ test_prompts = [
506
+ "This is a safe message",
507
+ "This contains hack attempts",
508
+ "Let's execute: exec('print(hello)')"
509
+ ]
510
+
511
+ for prompt in test_prompts:
512
+ result = await client.scan_prompt(prompt)
513
+ status = "✅ ALLOWED" if result.is_safe else "❌ BLOCKED"
514
+ print(f"{status}: {prompt}")
515
+
516
+ asyncio.run(main())
517
+ ```
518
+
368
519
  ### FastAPI Integration
369
520
 
370
521
  ```python
371
- from fastapi import FastAPI, HTTPException
372
- from koreshield_sdk import KoreShieldClient
522
+ from fastapi import FastAPI, Request
523
+ from koreshield_sdk.integrations import create_fastapi_middleware
373
524
 
374
525
  app = FastAPI()
375
- client = KoreShieldClient(api_key="your-api-key")
376
526
 
377
- @app.post("/chat")
378
- async def chat(message: str):
379
- # Scan user input
380
- result = client.scan_prompt(message)
527
+ # Create and add KoreShield middleware
528
+ middleware = create_fastapi_middleware(
529
+ api_key="your-api-key",
530
+ scan_request_body=True,
531
+ threat_threshold="medium",
532
+ block_on_threat=False, # Log but don't block
533
+ exclude_paths=["/health", "/docs"]
534
+ )
381
535
 
382
- if not result.is_safe and result.threat_level in ["high", "critical"]:
383
- raise HTTPException(status_code=400, detail="Unsafe content detected")
536
+ app.middleware("http")(middleware)
537
+
538
+ @app.post("/chat")
539
+ async def chat(request: Request, message: str):
540
+ # Request is automatically scanned by middleware
541
+ # Access scan results from request state if needed
542
+ scan_result = getattr(request.state, 'koreshield_result', None)
543
+ if scan_result and not scan_result.is_safe:
544
+ print(f"Threat detected: {scan_result.threat_level}")
384
545
 
385
546
  # Process with your LLM
386
547
  response = f"Processed: {message}"
387
- return {"response": response, "safety": result.dict()}
548
+ return {"response": response}
388
549
  ```
389
550
 
390
551
  ### Flask Integration
391
552
 
392
553
  ```python
393
- from flask import Flask, request, jsonify
394
- from koreshield_sdk import KoreShieldClient
554
+ from flask import Flask, request, jsonify, g
555
+ from koreshield_sdk.integrations import create_flask_middleware
395
556
 
396
557
  app = Flask(__name__)
397
- client = KoreShieldClient(api_key="your-api-key")
558
+
559
+ # Create and register KoreShield middleware
560
+ middleware = create_flask_middleware(
561
+ api_key="your-api-key",
562
+ scan_request_body=True,
563
+ threat_threshold="high",
564
+ block_on_threat=True,
565
+ exclude_paths=["/health"]
566
+ )
567
+
568
+ app.before_request(middleware)
398
569
 
399
570
  @app.route("/api/chat", methods=["POST"])
400
571
  def chat():
572
+ # Check if request was blocked by middleware
573
+ if hasattr(g, 'koreshield_blocked') and g.koreshield_blocked:
574
+ return jsonify({"error": "Request blocked by security policy"}), 403
575
+
401
576
  data = request.get_json()
402
577
  message = data.get("message", "")
403
578
 
404
- # Scan user input
405
- result = client.scan_prompt(message)
406
-
407
- if not result.is_safe:
408
- return jsonify({
409
- "error": "Unsafe content detected",
410
- "threat_level": result.threat_level,
411
- "confidence": result.confidence
412
- }), 400
579
+ # Access scan results
580
+ scan_result = getattr(g, 'koreshield_result', None)
413
581
 
414
582
  # Process with your LLM
415
583
  response = f"Echo: {message}"
416
- return jsonify({"response": response})
584
+ return jsonify({
585
+ "response": response,
586
+ "safety": scan_result.dict() if scan_result else None
587
+ })
417
588
  ```
418
589
 
419
590
  ### Django Integration
420
591
 
421
592
  ```python
593
+ # settings.py
594
+ KORESHIELD_CONFIG = {
595
+ 'api_key': 'your-api-key',
596
+ 'scan_request_body': True,
597
+ 'threat_threshold': 'medium',
598
+ 'block_on_threat': False,
599
+ 'exclude_paths': ['/health/', '/admin/']
600
+ }
601
+
602
+ # middleware.py
603
+ from koreshield_sdk.integrations import create_django_middleware
604
+
605
+ KoreShieldMiddleware = create_django_middleware()
606
+
422
607
  # views.py
423
608
  from django.http import JsonResponse
424
609
  from django.views.decorators.csrf import csrf_exempt
425
610
  from django.utils.decorators import method_decorator
426
611
  from django.views import View
427
612
  import json
428
- from koreshield_sdk import KoreShieldClient
429
-
430
- client = KoreShieldClient(api_key="your-api-key")
431
613
 
432
614
  @method_decorator(csrf_exempt, name='dispatch')
433
615
  class ChatView(View):
434
616
  def post(self, request):
617
+ # Check if request was blocked by middleware
618
+ if hasattr(request, 'koreshield_blocked') and request.koreshield_blocked:
619
+ return JsonResponse({"error": "Request blocked by security policy"}, status=403)
620
+
435
621
  data = json.loads(request.body)
436
622
  message = data.get("message", "")
437
623
 
438
- # Scan user input
439
- result = client.scan_prompt(message)
440
-
441
- if not result.is_safe and result.threat_level == "critical":
442
- return JsonResponse({
443
- "error": "Critical threat detected"
444
- }, status=400)
624
+ # Access scan results
625
+ scan_result = getattr(request, 'koreshield_result', None)
445
626
 
446
627
  # Process with your LLM
447
628
  response = f"Response to: {message}"
448
629
  return JsonResponse({
449
630
  "response": response,
450
- "safety_check": {
451
- "safe": result.is_safe,
452
- "threat_level": result.threat_level,
453
- "confidence": result.confidence
454
- }
631
+ "safety_check": scan_result.dict() if scan_result else None
455
632
  })
456
633
  ```
457
634
 
@@ -510,6 +687,68 @@ results = await client.scan_batch(
510
687
  )
511
688
  ```
512
689
 
690
+ ### Streaming Content Scanning
691
+
692
+ ```python
693
+ # Scan long documents with overlapping chunks
694
+ long_document = "Very long content..." * 1000
695
+
696
+ result = await client.scan_stream(
697
+ content=long_document,
698
+ chunk_size=2000, # Process in 2000-character chunks
699
+ overlap=200 # 200-character overlap between chunks
700
+ )
701
+
702
+ print(f"Overall safe: {result.overall_result.is_safe}")
703
+ print(f"Total chunks: {result.total_chunks}")
704
+ for i, chunk_result in enumerate(result.chunk_results):
705
+ print(f"Chunk {i+1}: {chunk_result.result.threat_level}")
706
+ ```
707
+
708
+ ### Performance Monitoring
709
+
710
+ ```python
711
+ async with AsyncKoreShieldClient(api_key="your-api-key", enable_metrics=True) as client:
712
+ # Perform operations...
713
+ await client.scan_prompt("Test prompt")
714
+ await client.scan_batch(["Prompt 1", "Prompt 2"])
715
+
716
+ # Get comprehensive metrics
717
+ metrics = await client.get_performance_metrics()
718
+ print(f"Total requests: {metrics.total_requests}")
719
+ print(".2f" print(".2f" print(f"Success rate: {metrics.success_rate:.1%}")
720
+
721
+ # Reset metrics if needed
722
+ await client.reset_metrics()
723
+ ```
724
+
725
+ ### Security Policy Management
726
+
727
+ ```python
728
+ from koreshield_sdk.types import SecurityPolicy, ThreatLevel
729
+
730
+ # Create and apply custom policy
731
+ policy = SecurityPolicy(
732
+ name="enterprise_policy",
733
+ threat_threshold=ThreatLevel.MEDIUM,
734
+ allowlist_patterns=["approved", "safe"],
735
+ blocklist_patterns=["banned", "dangerous"],
736
+ custom_rules=[
737
+ {"name": "no_pii", "pattern": "\\b\\d{3}-\\d{2}-\\d{4}\\b"}, # SSN pattern
738
+ {"name": "no_emails", "pattern": "\\S+@\\S+\\.\\S+"}
739
+ ]
740
+ )
741
+
742
+ await client.set_security_policy(policy)
743
+
744
+ # Update policy dynamically
745
+ await client.update_security_policy(threat_threshold=ThreatLevel.HIGH)
746
+
747
+ # Get current policy
748
+ current_policy = await client.get_security_policy()
749
+ print(f"Current threshold: {current_policy.threat_threshold}")
750
+ ```
751
+
513
752
  ### Monitoring and Analytics
514
753
 
515
754
  ```python
@@ -559,7 +798,7 @@ MIT License - see [LICENSE](LICENSE) file for details.
559
798
 
560
799
  ## Support
561
800
 
562
- - 📖 [Documentation](https://docs.koreshield.com)
563
- - 🐛 [Issue Tracker](https://github.com/koreshield/koreshield-python-sdk/issues)
564
- - 💬 [Discussions](https://github.com/koreshield/koreshield-python-sdk/discussions)
565
- - 📧 [Email Support](mailto:support@koreshield.com)
801
+ - [Documentation](https://docs.koreshield.com)
802
+ - [Issue Tracker](https://github.com/koreshield/koreshield-python-sdk/issues)
803
+ - [Discussions](https://github.com/koreshield/koreshield-python-sdk/discussions)
804
+ - [Email Support](mailto:support@koreshield.com)
@@ -0,0 +1,14 @@
1
+ koreshield-0.2.1.dist-info/licenses/LICENSE,sha256=k3qeCwQxhbOO1GtxA10Do4-_veQzgflqjOp5uZD5mug,1071
2
+ koreshield_sdk/__init__.py,sha256=dAPYcLFKoP6pmaDQscfVXmrKLdQgijLn5bMQ00wlQ8c,1054
3
+ koreshield_sdk/async_client.py,sha256=23G41vUUEz2Q2r4kz1SsGnyzKt7XW9rp2pv9w7OlIyc,25785
4
+ koreshield_sdk/client.py,sha256=LHuCrHwugzDeoMY5bxmYRmIyRUwJUNgL_Vv3f5ncqpE,13217
5
+ koreshield_sdk/exceptions.py,sha256=3j1FR4VFbe1Vv4i0bofBgQ_ZGwBfpOInBd9OyNQFUxo,945
6
+ koreshield_sdk/py.typed,sha256=8ZJUsxZiuOy1oJeVhsTWQhTG_6pTVHVXk5hJL79ebTk,25
7
+ koreshield_sdk/types.py,sha256=SH8abPngey6ZfRjWN5MXRWBs-V6F7f5iQSdAHJjlzwA,8322
8
+ koreshield_sdk/integrations/__init__.py,sha256=NHu1Nl9vRaVT8LZy8zeTGQDA9Fd01CzYJVHtWUYcN_w,970
9
+ koreshield_sdk/integrations/frameworks.py,sha256=i4NxWqnlRZ_kREhkvmZUH_TZa90ALNQxcS3hOGxQGmQ,15426
10
+ koreshield_sdk/integrations/langchain.py,sha256=w3BXs3tVk7R4ldFPhAm7qXbJPsHoamY3z2Ke0WPBVas,16542
11
+ koreshield-0.2.1.dist-info/METADATA,sha256=uNALcPudFoQZwUxhTmtelbLIm6lJEIiAJNBVNazmgac,22980
12
+ koreshield-0.2.1.dist-info/WHEEL,sha256=wUyA8OaulRlbfwMtmQsvNngGrxQHAvkKcvRmdizlJi0,92
13
+ koreshield-0.2.1.dist-info/top_level.txt,sha256=ePw2ZI3SrHZ5CaTRCyj3aya3j_qTcmRAQjoU7s3gAdM,15
14
+ koreshield-0.2.1.dist-info/RECORD,,
@@ -15,8 +15,16 @@ from .types import (
15
15
  DetectionType,
16
16
  AuthConfig,
17
17
  )
18
+ # RAG Imports
19
+ from .types import (
20
+ RAGDocument,
21
+ RAGScanRequest,
22
+ RAGScanResponse,
23
+ DocumentThreat,
24
+ CrossDocumentThreat,
25
+ )
18
26
 
19
- __version__ = "0.1.0"
27
+ __version__ = "0.2.0"
20
28
  __all__ = [
21
29
  "KoreShieldClient",
22
30
  "AsyncKoreShieldClient",
@@ -30,4 +38,10 @@ __all__ = [
30
38
  "ThreatLevel",
31
39
  "DetectionType",
32
40
  "AuthConfig",
41
+ # RAG Types
42
+ "RAGDocument",
43
+ "RAGScanRequest",
44
+ "RAGScanResponse",
45
+ "DocumentThreat",
46
+ "CrossDocumentThreat",
33
47
  ]