deeprails 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.
@@ -0,0 +1,11 @@
1
+ MIT License
2
+
3
+ Copyright (c) [2025] [DeepRails Inc.ß]
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
10
+
11
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,154 @@
1
+ Metadata-Version: 2.4
2
+ Name: deeprails
3
+ Version: 0.2.0
4
+ Summary: Python SDK for interacting with the DeepRails API
5
+ Project-URL: Homepage, https://deeprails.com
6
+ Project-URL: Documentation, https://docs.deeprails.com
7
+ Author-email: Neil Mate <support@deeprails.ai>
8
+ License: MIT License
9
+
10
+ Copyright (c) [2025] [DeepRails Inc.ß]
11
+
12
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
13
+
14
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17
+
18
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19
+ License-File: LICENSE
20
+ Keywords: ai,deeprails,evaluation,genai,guardrails,sdk
21
+ Classifier: Intended Audience :: Developers
22
+ Classifier: License :: OSI Approved :: MIT License
23
+ Classifier: Operating System :: OS Independent
24
+ Classifier: Programming Language :: Python :: 3
25
+ Classifier: Programming Language :: Python :: 3.8
26
+ Classifier: Programming Language :: Python :: 3.9
27
+ Classifier: Programming Language :: Python :: 3.10
28
+ Classifier: Programming Language :: Python :: 3.11
29
+ Classifier: Programming Language :: Python :: 3.12
30
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
31
+ Requires-Python: >=3.8
32
+ Requires-Dist: httpx<0.29.0,>=0.28.1
33
+ Requires-Dist: pydantic<3.0.0,>=2.11.7
34
+ Description-Content-Type: text/markdown
35
+
36
+ # DeepRails Python SDK
37
+
38
+ A lightweight, intuitive Python SDK for interacting with the DeepRails API. DeepRails helps you evaluate and improve AI-generated outputs through a comprehensive set of guardrail metrics.
39
+
40
+ ## Installation
41
+
42
+ ```bash
43
+ pip install deeprails
44
+ ```
45
+
46
+ ## Quick Start
47
+
48
+ ```python
49
+ from deeprails import DeepRails
50
+
51
+ # Initialize with your API token
52
+ client = DeepRails(token="YOUR_API_KEY")
53
+
54
+ # Create an evaluation
55
+ evaluation = client.create_evaluation(
56
+ model_input={"user_prompt": "Prompt used to generate completion"},
57
+ model_output="Generated output",
58
+ model_used="gpt-4o-mini (LLM used to generate completion)",
59
+ guardrail_metrics=["correctness", "completeness"]
60
+ )
61
+
62
+ # Print evaluation ID
63
+ print(f"Evaluation created with ID: {evaluation.eval_id}")
64
+ ```
65
+
66
+ ## Features
67
+
68
+ - **Simple API**: Just a few lines of code to integrate evaluation into your workflow
69
+ - **Comprehensive Metrics**: Evaluate outputs on correctness, completeness, and more
70
+ - **Real-time Progress**: Track evaluation progress in real-time
71
+ - **Detailed Results**: Get detailed scores and rationales for each metric
72
+
73
+ ## Authentication
74
+
75
+ All API requests require authentication using your DeepRails API key. Your API key is a sensitive credential that should be kept secure.
76
+
77
+ ```python
78
+ # Best practice: Load token from environment variable
79
+ import os
80
+ token = os.environ.get("DEEPRAILS_API_KEY")
81
+ client = DeepRails(token=token)
82
+ ```
83
+
84
+ ## Creating Evaluations
85
+
86
+ ```python
87
+ try:
88
+ evaluation = client.create_evaluation(
89
+ model_input={"user_prompt": "Prompt used to generate completion"},
90
+ model_output="Generated output",
91
+ model_used="gpt-4o-mini (LLM used to generate completion)",
92
+ guardrail_metrics=["correctness", "completeness"]
93
+ )
94
+ print(f"ID: {evaluation.eval_id}")
95
+ print(f"Status: {evaluation.evaluation_status}")
96
+ print(f"Progress: {evaluation.progress}%")
97
+ except Exception as e:
98
+ print(f"Error: {e}")
99
+ ```
100
+
101
+ ### Parameters
102
+
103
+ - `model_input`: Dictionary containing the prompt and any context (must include `user_prompt`)
104
+ - `model_output`: The generated output to evaluate
105
+ - `model_used`: (Optional) The model that generated the output
106
+ - `run_mode`: (Optional) Evaluation run mode - defaults to "smart"
107
+ - `guardrail_metrics`: (Optional) List of metrics to evaluate
108
+ - `nametag`: (Optional) Custom identifier for this evaluation
109
+ - `webhook`: (Optional) URL to receive completion notifications
110
+
111
+ ## Retrieving Evaluations
112
+
113
+ ```python
114
+ try:
115
+ eval_id = "eval-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
116
+ evaluation = client.get_evaluation(eval_id)
117
+
118
+ print(f"Status: {evaluation.evaluation_status}")
119
+
120
+ if evaluation.evaluation_result:
121
+ print("\nResults:")
122
+ for metric, result in evaluation.evaluation_result.items():
123
+ score = result.get('score', 'N/A')
124
+ print(f" {metric}: {score}")
125
+ except Exception as e:
126
+ print(f"Error: {e}")
127
+ ```
128
+
129
+ ## Available Metrics
130
+
131
+ - `correctness`: Evaluates factual accuracy of the output
132
+ - `completeness`: Checks if the output addresses all aspects of the prompt
133
+ - `harmfulness`: Detects potentially harmful content
134
+ - `bias`: Identifies biased language or reasoning
135
+ - And more...
136
+
137
+ ## Error Handling
138
+
139
+ The SDK throws `DeepRailsAPIError` for API-related errors, with status code and detailed message.
140
+
141
+ ```python
142
+ from deeprails import DeepRailsAPIError
143
+
144
+ try:
145
+ # SDK operations
146
+ except DeepRailsAPIError as e:
147
+ print(f"API Error: {e.status_code} - {e.error_detail}")
148
+ except Exception as e:
149
+ print(f"Unexpected error: {e}")
150
+ ```
151
+
152
+ ## Support
153
+
154
+ For questions or support, please contact support@deeprails.ai.
@@ -0,0 +1,119 @@
1
+ # DeepRails Python SDK
2
+
3
+ A lightweight, intuitive Python SDK for interacting with the DeepRails API. DeepRails helps you evaluate and improve AI-generated outputs through a comprehensive set of guardrail metrics.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install deeprails
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```python
14
+ from deeprails import DeepRails
15
+
16
+ # Initialize with your API token
17
+ client = DeepRails(token="YOUR_API_KEY")
18
+
19
+ # Create an evaluation
20
+ evaluation = client.create_evaluation(
21
+ model_input={"user_prompt": "Prompt used to generate completion"},
22
+ model_output="Generated output",
23
+ model_used="gpt-4o-mini (LLM used to generate completion)",
24
+ guardrail_metrics=["correctness", "completeness"]
25
+ )
26
+
27
+ # Print evaluation ID
28
+ print(f"Evaluation created with ID: {evaluation.eval_id}")
29
+ ```
30
+
31
+ ## Features
32
+
33
+ - **Simple API**: Just a few lines of code to integrate evaluation into your workflow
34
+ - **Comprehensive Metrics**: Evaluate outputs on correctness, completeness, and more
35
+ - **Real-time Progress**: Track evaluation progress in real-time
36
+ - **Detailed Results**: Get detailed scores and rationales for each metric
37
+
38
+ ## Authentication
39
+
40
+ All API requests require authentication using your DeepRails API key. Your API key is a sensitive credential that should be kept secure.
41
+
42
+ ```python
43
+ # Best practice: Load token from environment variable
44
+ import os
45
+ token = os.environ.get("DEEPRAILS_API_KEY")
46
+ client = DeepRails(token=token)
47
+ ```
48
+
49
+ ## Creating Evaluations
50
+
51
+ ```python
52
+ try:
53
+ evaluation = client.create_evaluation(
54
+ model_input={"user_prompt": "Prompt used to generate completion"},
55
+ model_output="Generated output",
56
+ model_used="gpt-4o-mini (LLM used to generate completion)",
57
+ guardrail_metrics=["correctness", "completeness"]
58
+ )
59
+ print(f"ID: {evaluation.eval_id}")
60
+ print(f"Status: {evaluation.evaluation_status}")
61
+ print(f"Progress: {evaluation.progress}%")
62
+ except Exception as e:
63
+ print(f"Error: {e}")
64
+ ```
65
+
66
+ ### Parameters
67
+
68
+ - `model_input`: Dictionary containing the prompt and any context (must include `user_prompt`)
69
+ - `model_output`: The generated output to evaluate
70
+ - `model_used`: (Optional) The model that generated the output
71
+ - `run_mode`: (Optional) Evaluation run mode - defaults to "smart"
72
+ - `guardrail_metrics`: (Optional) List of metrics to evaluate
73
+ - `nametag`: (Optional) Custom identifier for this evaluation
74
+ - `webhook`: (Optional) URL to receive completion notifications
75
+
76
+ ## Retrieving Evaluations
77
+
78
+ ```python
79
+ try:
80
+ eval_id = "eval-xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
81
+ evaluation = client.get_evaluation(eval_id)
82
+
83
+ print(f"Status: {evaluation.evaluation_status}")
84
+
85
+ if evaluation.evaluation_result:
86
+ print("\nResults:")
87
+ for metric, result in evaluation.evaluation_result.items():
88
+ score = result.get('score', 'N/A')
89
+ print(f" {metric}: {score}")
90
+ except Exception as e:
91
+ print(f"Error: {e}")
92
+ ```
93
+
94
+ ## Available Metrics
95
+
96
+ - `correctness`: Evaluates factual accuracy of the output
97
+ - `completeness`: Checks if the output addresses all aspects of the prompt
98
+ - `harmfulness`: Detects potentially harmful content
99
+ - `bias`: Identifies biased language or reasoning
100
+ - And more...
101
+
102
+ ## Error Handling
103
+
104
+ The SDK throws `DeepRailsAPIError` for API-related errors, with status code and detailed message.
105
+
106
+ ```python
107
+ from deeprails import DeepRailsAPIError
108
+
109
+ try:
110
+ # SDK operations
111
+ except DeepRailsAPIError as e:
112
+ print(f"API Error: {e.status_code} - {e.error_detail}")
113
+ except Exception as e:
114
+ print(f"Unexpected error: {e}")
115
+ ```
116
+
117
+ ## Support
118
+
119
+ For questions or support, please contact support@deeprails.ai.
@@ -0,0 +1 @@
1
+ from .client import DeepRails
@@ -0,0 +1,101 @@
1
+ import httpx
2
+ from typing import List, Optional, Dict, Any
3
+
4
+ from .schemas import EvaluationResponse
5
+ from .exceptions import DeepRailsAPIError
6
+
7
+ class DeepRails:
8
+ """
9
+ Python SDK client for the DeepRails API.
10
+ """
11
+ def __init__(self, token: str, base_url: str = "https://api.deeprails.com"):
12
+ """
13
+ Initializes the DeepRails client.
14
+
15
+ Args:
16
+ token: Your DeepRails API key (starts with 'sk_').
17
+ base_url: The base URL of the DeepRails API.
18
+ """
19
+ if not token:
20
+ raise ValueError("A valid DeepRails API token is required.")
21
+
22
+ self._base_url = base_url
23
+ self._headers = {
24
+ "Authorization": f"Bearer {token}",
25
+ "Content-Type": "application/json",
26
+ "User-Agent": "deeprails-python-sdk/0.2.0"
27
+ }
28
+ self._client = httpx.Client(base_url=self._base_url, headers=self._headers, timeout=30.0)
29
+
30
+ def _request(self, method: str, endpoint: str, **kwargs) -> httpx.Response:
31
+ """Helper method to make requests and handle API errors."""
32
+ try:
33
+ response = self._client.request(method, endpoint, **kwargs)
34
+ response.raise_for_status()
35
+ return response
36
+ except httpx.HTTPStatusError as e:
37
+ error_detail = "No detail provided."
38
+ try:
39
+ error_detail = e.response.json().get("detail", error_detail)
40
+ except Exception:
41
+ error_detail = e.response.text
42
+ raise DeepRailsAPIError(status_code=e.response.status_code, error_detail=error_detail) from e
43
+ except httpx.RequestError as e:
44
+ raise DeepRailsAPIError(status_code=500, error_detail=f"Request failed: {e}") from e
45
+
46
+ def create_evaluation(
47
+ self,
48
+ *,
49
+ model_input: Dict[str, Any],
50
+ model_output: str,
51
+ model_used: Optional[str] = None,
52
+ run_mode: Optional[str] = "smart", # Set default to "smart"
53
+ guardrail_metrics: Optional[List[str]] = None,
54
+ nametag: Optional[str] = None,
55
+ webhook: Optional[str] = None
56
+ ) -> EvaluationResponse:
57
+ """
58
+ Creates a new evaluation and immediately processes it.
59
+
60
+ Args:
61
+ model_input: A dictionary containing the inputs for the model.
62
+ Must contain a "user_prompt" key.
63
+ model_output: The response generated by the model you are evaluating.
64
+ model_used: The name or identifier of the model being evaluated.
65
+ run_mode: The evaluation mode (e.g., "smart", "dev").
66
+ guardrail_metrics: A list of metrics to evaluate.
67
+ nametag: A user-defined name or tag for the evaluation.
68
+ webhook: A URL to send a POST request to upon evaluation completion.
69
+
70
+ Returns:
71
+ An EvaluationResponse object with the details of the created evaluation.
72
+ """
73
+ if "user_prompt" not in model_input:
74
+ raise ValueError("`model_input` must contain a 'user_prompt' key.")
75
+
76
+ payload = {
77
+ "model_input": model_input,
78
+ "model_output": model_output,
79
+ "model_used": model_used,
80
+ "run_mode": run_mode,
81
+ "guardrail_metrics": guardrail_metrics,
82
+ "nametag": nametag,
83
+ "webhook": webhook,
84
+ }
85
+ json_payload = {k: v for k, v in payload.items() if v is not None}
86
+
87
+ response = self._request("POST", "/evaluate", json=json_payload)
88
+ return EvaluationResponse.parse_obj(response.json())
89
+
90
+ def get_evaluation(self, eval_id: str) -> EvaluationResponse:
91
+ """
92
+ Retrieves the status and results of a specific evaluation.
93
+
94
+ Args:
95
+ eval_id: The unique identifier of the evaluation.
96
+
97
+ Returns:
98
+ An EvaluationResponse object with the full, up-to-date details of the evaluation.
99
+ """
100
+ response = self._request("GET", f"/evaluate/{eval_id}")
101
+ return EvaluationResponse.parse_obj(response.json())
@@ -0,0 +1,10 @@
1
+ class DeepRailsError(Exception):
2
+ """Base exception class for the DeepRails SDK."""
3
+ pass
4
+
5
+ class DeepRailsAPIError(DeepRailsError):
6
+ """Raised when the DeepRails API returns an error."""
7
+ def __init__(self, status_code: int, error_detail: str):
8
+ self.status_code = status_code
9
+ self.error_detail = error_detail
10
+ super().__init__(f"API Error {status_code}: {error_detail}")
@@ -0,0 +1,30 @@
1
+ from typing import List, Optional, Dict, Any
2
+ from pydantic import BaseModel, Field
3
+ from datetime import datetime
4
+
5
+
6
+ class EvaluationResponse(BaseModel):
7
+ """Represents the response for an evaluation from the DeepRails API."""
8
+ eval_id: str
9
+ evaluation_status: str
10
+ guardrail_metrics: Optional[List[str]] = None
11
+ model_used: Optional[str] = None
12
+ run_mode: Optional[str] = None
13
+ model_input: Optional[Dict[str, Any]] = None
14
+ model_output: Optional[str] = None
15
+ estimated_cost: Optional[float] = None
16
+ input_tokens: Optional[int] = None
17
+ output_tokens: Optional[int] = None
18
+ nametag: Optional[str] = None
19
+ progress: Optional[int] = Field(None, ge=0, le=100)
20
+ start_timestamp: Optional[datetime] = None
21
+ completion_timestamp: Optional[datetime] = None
22
+ error_message: Optional[str] = None
23
+ error_timestamp: Optional[datetime] = None
24
+ evaluation_result: Optional[Dict[str, Any]] = None
25
+ evaluation_total_cost: Optional[float] = None
26
+ created_at: Optional[datetime] = None
27
+ modified_at: Optional[datetime] = None
28
+
29
+ class Config:
30
+ extra = 'ignore'
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "deeprails"
7
+ version = "0.2.0"
8
+ description = "Python SDK for interacting with the DeepRails API"
9
+ readme = {file = "README.md", content-type = "text/markdown"}
10
+ authors = [{name = "Neil Mate", email = "support@deeprails.ai"}]
11
+ license = {file = "LICENSE"}
12
+ classifiers = [
13
+ "Programming Language :: Python :: 3",
14
+ "Programming Language :: Python :: 3.8",
15
+ "Programming Language :: Python :: 3.9",
16
+ "Programming Language :: Python :: 3.10",
17
+ "Programming Language :: Python :: 3.11",
18
+ "Programming Language :: Python :: 3.12",
19
+ "License :: OSI Approved :: MIT License",
20
+ "Operating System :: OS Independent",
21
+ "Intended Audience :: Developers",
22
+ "Topic :: Software Development :: Libraries :: Python Modules",
23
+ ]
24
+ keywords = ["ai", "evaluation", "guardrails", "sdk", "genai", "deeprails"]
25
+ dependencies = [
26
+ "httpx>=0.28.1,<0.29.0",
27
+ "pydantic>=2.11.7,<3.0.0",
28
+ ]
29
+ requires-python = ">=3.8"
30
+
31
+ [project.urls]
32
+ "Homepage" = "https://deeprails.com"
33
+ "Documentation" = "https://docs.deeprails.com"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["deeprails"]
37
+
38
+ [tool.hatch.build.targets.sdist]
39
+ include = [
40
+ "deeprails",
41
+ "LICENSE",
42
+ "README.md",
43
+ ]