API Reference
This section provides detailed technical documentation for the Trustwise SDK. For conceptual information and best practices, see the individual metric sections.
Platform Client (Recommended)
Note
TrustwiseClient is the recommended client for all new development. It provides access to agents, guardrails, policies, evaluations, metrics, risk classification, and more through a single unified interface.
Ergonomic client for the Trustwise Platform API (v1alpha).
Thin wrapper that provides user-friendly method names over PlatformHTTP.
When the OpenAPI spec adds a new endpoint, add a ~2-line method here.
By default, methods return the inner data model (e.g. AgentResponse)
so you can do agent.name directly. Pass raw=True to get the full
API envelope (with success, metadata, warnings, etc.).
- trustwise.sdk.platform.client._parse(data_model, response, *, raw=False)[source]
Parse API response.
Every endpoint that returns an API response uses the
{success, data, metadata, ...}envelope; by default this extracts.dataand parses it into data_model. Withraw=True, returns the full envelope as a dict.File downloads (the
/exportroutes, which setContent-Disposition: attachment) do not come through here at all — see_export_download(). The non-dict guard below is a safety net so an unexpected body is handed back rather than raisingAttributeError.
- class trustwise.sdk.platform.client.TrustwiseClient(config, *, timeout=30)[source]
Bases:
objectUser-friendly client for the Trustwise Harmony Platform API.
Provides access to all platform resources through sub-clients:
agents,assessments,gateway,guardrails,policies,evaluations,evaluators,organizations,projects,risk_engine,generation,metrics,events,subscriptions,runtime_providers,runtime_connectors,mcp_servers,models,jobs,artifacts,components,reports,users, andrbac.Example:
from trustwise.sdk.config import TrustwiseConfig from trustwise.sdk.platform import TrustwiseClient config = TrustwiseConfig(api_key="tw-...") client = TrustwiseClient(config) # Agents within one project agent = client.agents.get("project-id", "agent-id") print(agent.name) agents = client.agents.list("project-id", search="my-bot", limit=5) for a in agents: print(a.name) # ...or the organization-wide catalogue, assigned to projects for a in client.agents.org_list(limit=5): print(a.name) client.agents.assign("project-id", "agent-id") # Raw — returns the full API envelope resp = client.agents.get("project-id", "agent-id", raw=True) print(resp["success"], resp["data"]["name"])
- Parameters:
config (
TrustwiseConfig) – Trustwise configuration instance.timeout (
int) – HTTP request timeout in seconds.
- __init__(config, *, timeout=30)[source]
- Parameters:
config (TrustwiseConfig)
timeout (int)
- Return type:
None
- trustwise.sdk.platform.client._list_params(*, search=None, page=1, limit=10, sort_by='updated_at', sort_order='desc', project_id=None, tags=None, **extra)[source]
Build common list/filter query params.
- trustwise.sdk.platform.client._export_params(slugs, fmt, **extra)[source]
Build query params for the per-resource
/exportendpoints.
- trustwise.sdk.platform.client._export_download(http, path, *, slugs, fmt, as_file)[source]
Fetch a per-resource
/exportbundle.These routes answer with
Content-Disposition: attachment— the body is the exported file itself (a bare JSON list, or a YAML document), not the{success, data, ...}envelope the rest of the API uses. That header is what distinguishes the two, since both are served asapplication/json.
- trustwise.sdk.platform.client._import_files(file, file_name)[source]
Build the
multipart/form-datapayload for an/importendpoint.Accepts either raw
bytesor an open binary file object.
- class trustwise.sdk.platform.client.AgentResource(http)[source]
Bases:
objectManage project-scoped agents, deployments, and connections.
Accessible via
client.agents.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- patch(project_id, agent_id, *, if_match, raw=False, **body)[source]
Partially update an agent, changing only the fields supplied.
Unlike
update(), fields you omit keep their current values.- Parameters:
- Return type:
AgentResponse- Returns:
Parsed
AgentResponse, or the raw envelope.
- versions(project_id, agent_id, *, raw=False, **kwargs)[source]
List the version history of an agent.
- Parameters:
- Return type:
list[AgentResponse]- Returns:
List of
AgentResponse, one per version, or the raw envelope.
- query(project_id, agent_id, *, raw=False, **body)[source]
Send a query to an agent and get a response.
- risk_classify(project_id, agent_id, *, raw=False, **body)[source]
Run risk classification on an agent.
- deploy_gateway(project_id, agent_id, *, raw=False, **body)[source]
Deploy an agent to the AI Gateway with runtime guardrails.
- Parameters:
- Return type:
AIGatewayDeployResponse- Returns:
Parsed
AIGatewayDeployResponsecontaining the gateway URL, API key, and applied guardrails.
- regenerate_gateway_key(project_id, agent_id, *, raw=False, **body)[source]
Regenerate the AI Gateway API key for a deployed agent.
- Parameters:
- Return type:
AIGatewayDeployResponse- Returns:
Parsed
AIGatewayDeployResponsewith the new gateway key, or the raw envelope.
- status_history(project_id, agent_id, *, raw=False, **kwargs)[source]
Get the status history for an agent.
- update_status(project_id, agent_id, *, raw=False, **body)[source]
Update an agent’s operational status.
- assign_assessment(project_id, agent_id, *, raw=False, **body)[source]
Assign an assessment to an agent.
- unassign_assessment(project_id, agent_id, *, raw=False, **body)[source]
Remove an assessment assignment from an agent.
- export(*, slugs=None, format=None, as_file=False, raw=False)[source]
Export agent definitions as a portable bundle.
This route is a file download — the API sets
Content-Disposition: attachmentand the body is the exported file itself, not the usual{success, data, ...}envelope.- Parameters:
slugs (
list[str] |str|None) – Restrict the export to these agent slugs. Omit to export all.as_file (
bool) – Return aDownloadedFile— the raw bytes plus the server-suggested filename — ready to write to disk or pass straight toimport_().raw (
bool) – Accepted for consistency with the other methods; it has no effect here, because the body of a file download is already the payload and there is no envelope to unwrap.
- Return type:
DownloadedFile|list[dict[str,Any]] |dict[str,Any] |bytes- Returns:
A list of exported agent records;
byteswhen format is"yaml"; or aDownloadedFilewhen as_file is set.
- import_(project_id, file, *, file_name='agents.json', conflict_strategy=None, raw=False)[source]
Import agent definitions into a project from an exported bundle.
- Parameters:
project_id (
str) – Target project identifier.file (
Any) – Bundle contents — rawbytesor an open binary file object.file_name (
str) – Name to send with the upload.conflict_strategy (
str|None) – How to handle existing agents — e.g."skip","overwrite","rename".raw (
bool) – Return the full API envelope.
- Return type:
- org_list(*, raw=False, **kwargs)[source]
List agents across the whole organization.
- Parameters:
- Return type:
list[AgentListItem]- Returns:
List of
AgentListItem, or the raw envelope.
- org_patch(agent_id, *, if_match, raw=False, **body)[source]
Partially update an organization-scoped agent.
Unlike
org_update(), fields you omit keep their current values.
- org_versions(agent_id, *, raw=False, **kwargs)[source]
List the version history of an organization-scoped agent.
- Parameters:
- Return type:
list[AgentResponse]- Returns:
List of
AgentResponse, one per version, or the raw envelope.
- org_version(agent_id, version, *, raw=False)[source]
Get one specific version of an organization-scoped agent.
- org_status_history(agent_id, *, raw=False, **kwargs)[source]
Get the status history of an organization-scoped agent.
- org_update_status(agent_id, *, raw=False, **body)[source]
Update the status of an organization-scoped agent.
- org_assign_assessment(agent_id, *, raw=False, **body)[source]
Assign an assessment to an organization-scoped agent.
- org_unassign_assessment(agent_id, *, raw=False)[source]
Detach the assessment currently assigned to an agent.
- org_associations(agent_id, *, raw=False)[source]
List the components an organization-scoped agent is associated with.
- org_add_association(agent_id, *, raw=False, **body)[source]
Associate an organization-scoped agent with another component.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- org_remove_association(agent_id, *, raw=False, **body)[source]
Remove an association from an organization-scoped agent.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- assign(project_id, agent_id, *, raw=False)[source]
Assign an organization-scoped agent to a project.
- associations(project_id, agent_id, *, raw=False)[source]
List an agent’s associations as scoped to one project.
- add_association(project_id, agent_id, *, raw=False, **body)[source]
Associate an agent with another component within a project.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- class trustwise.sdk.platform.client.GatewayResource(http)[source]
Bases:
objectManage AI Gateway models and guardrails.
Accessible via
client.gateway.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- list_models(*, raw=False)[source]
List models available in the AI Gateway.
- Parameters:
raw (
bool) – Return the full API envelope.- Return type:
AIGatewayModelInfo- Returns:
Parsed
AIGatewayModelInfo, or the raw envelope.
- class trustwise.sdk.platform.client.MCPServerResource(http)[source]
Bases:
objectManage project-scoped MCP servers and gateway deployments.
Accessible via
client.mcp_servers.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- list(project_id, *, raw=False, **kwargs)[source]
List MCP servers within a project.
- Parameters:
- Return type:
list[MCPServerListItem]- Returns:
List of
MCPServerListItem, or the raw envelope.
- patch(project_id, mcp_server_id, *, raw=False, **body)[source]
Partially update an MCP server, changing only the fields supplied.
Unlike
update(), fields you omit keep their current values.
- versions(project_id, mcp_server_id, *, raw=False, **kwargs)[source]
List the version history of an MCP server.
- Parameters:
- Return type:
list[MCPServerResponse]- Returns:
List of
MCPServerResponse, one per version, or the raw envelope.
- version(project_id, mcp_server_id, version, *, raw=False)[source]
Get one specific version of an MCP server.
- deploy_gateway(project_id, mcp_server_id, *, raw=False, **body)[source]
Deploy an MCP server to the AI Gateway.
- export(*, slugs=None, format=None, as_file=False, raw=False)[source]
Export MCP server definitions as a portable bundle.
This route is a file download — the API sets
Content-Disposition: attachmentand the body is the exported file itself, not the usual{success, data, ...}envelope.- Parameters:
slugs (
list[str] |str|None) – Restrict the export to these server slugs. Omit to export all.as_file (
bool) – Return aDownloadedFile— the raw bytes plus the server-suggested filename — ready to write to disk or pass straight toimport_().raw (
bool) – Accepted for consistency with the other methods; it has no effect here, because the body of a file download is already the payload and there is no envelope to unwrap.
- Return type:
DownloadedFile|list[dict[str,Any]] |dict[str,Any] |bytes- Returns:
A list of exported MCP server records;
byteswhen format is"yaml"; or aDownloadedFilewhen as_file is set.
- import_(project_id, file, *, file_name='mcp-servers.json', conflict_strategy=None, raw=False)[source]
Import MCP server definitions into a project from a bundle.
- Parameters:
project_id (
str) – Target project identifier.file (
Any) – Bundle contents — rawbytesor an open binary file object.file_name (
str) – Name to send with the upload.conflict_strategy (
str|None) – How to handle existing servers — e.g."skip","overwrite","rename".raw (
bool) – Return the full API envelope.
- Return type:
- org_list(*, raw=False, **kwargs)[source]
List MCP servers across the whole organization.
- Parameters:
- Return type:
list[MCPServerListItem]- Returns:
List of
MCPServerListItem, or the raw envelope.
- org_patch(mcp_server_id, *, raw=False, **body)[source]
Partially update an organization-scoped MCP server.
Unlike
org_update(), fields you omit keep their current values.
- org_versions(mcp_server_id, *, raw=False, **kwargs)[source]
List the version history of an organization-scoped MCP server.
- Parameters:
- Return type:
list[MCPServerResponse]- Returns:
List of
MCPServerResponse, one per version, or the raw envelope.
- org_version(mcp_server_id, version, *, raw=False)[source]
Get one specific version of an organization-scoped MCP server.
- org_associations(mcp_server_id, *, raw=False)[source]
List the components an MCP server is associated with.
- org_add_association(mcp_server_id, *, raw=False, **body)[source]
Associate an organization-scoped MCP server with another component.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- org_remove_association(mcp_server_id, *, raw=False, **body)[source]
Remove an association from an organization-scoped MCP server.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- assign(project_id, mcp_server_id, *, raw=False)[source]
Assign an organization-scoped MCP server to a project.
- unassign(project_id, mcp_server_id, *, raw=False)[source]
Remove an MCP server’s assignment to a project.
- associations(project_id, mcp_server_id, *, raw=False)[source]
List an MCP server’s associations as scoped to one project.
- add_association(project_id, mcp_server_id, *, raw=False, **body)[source]
Associate an MCP server with another component within a project.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- class trustwise.sdk.platform.client.ModelResource(http)[source]
Bases:
objectManage project-scoped models and gateway deployments.
Accessible via
client.models.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- list(project_id, *, raw=False, **kwargs)[source]
List models within a project.
- Parameters:
- Return type:
list[ModelResponse]- Returns:
List of
ModelResponse, or the raw envelope.
- patch(project_id, model_id, *, raw=False, **body)[source]
Partially update a model, changing only the fields supplied.
Unlike
update(), fields you omit keep their current values.
- versions(project_id, model_id, *, raw=False, **kwargs)[source]
List the version history of a model.
- Parameters:
- Return type:
list[ModelResponse]- Returns:
List of
ModelResponse, one per version, or the raw envelope.
- deploy_gateway(project_id, model_id, *, raw=False, **body)[source]
Deploy a model to the AI Gateway.
- list_providers(*, raw=False)[source]
List available model providers and their supported models.
- Parameters:
raw (
bool) – Return the full API envelope.- Return type:
ModelProviderListResponse- Returns:
Parsed
ModelProviderListResponse, or the raw envelope.
- export(*, slugs=None, format=None, as_file=False, raw=False)[source]
Export model definitions as a portable bundle.
This route is a file download — the API sets
Content-Disposition: attachmentand the body is the exported file itself, not the usual{success, data, ...}envelope.- Parameters:
slugs (
list[str] |str|None) – Restrict the export to these model slugs. Omit to export all.as_file (
bool) – Return aDownloadedFile— the raw bytes plus the server-suggested filename — ready to write to disk or pass straight toimport_().raw (
bool) – Accepted for consistency with the other methods; it has no effect here, because the body of a file download is already the payload and there is no envelope to unwrap.
- Return type:
DownloadedFile|list[dict[str,Any]] |dict[str,Any] |bytes- Returns:
A list of exported model records;
byteswhen format is"yaml"; or aDownloadedFilewhen as_file is set.
- import_(project_id, file, *, file_name='models.json', conflict_strategy=None, raw=False)[source]
Import model definitions into a project from an exported bundle.
- Parameters:
project_id (
str) – Target project identifier.file (
Any) – Bundle contents — rawbytesor an open binary file object.file_name (
str) – Name to send with the upload.conflict_strategy (
str|None) – How to handle existing models — e.g."skip","overwrite","rename".raw (
bool) – Return the full API envelope.
- Return type:
- org_patch(model_id, *, raw=False, **body)[source]
Partially update an organization-scoped model.
Unlike
org_update(), fields you omit keep their current values.
- org_versions(model_id, *, raw=False, **kwargs)[source]
List the version history of an organization-scoped model.
- Parameters:
- Return type:
list[ModelResponse]- Returns:
List of
ModelResponse, one per version, or the raw envelope.
- org_version(model_id, version, *, raw=False)[source]
Get one specific version of an organization-scoped model.
- org_add_association(model_id, *, raw=False, **body)[source]
Associate an organization-scoped model with another component.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- org_remove_association(model_id, *, raw=False, **body)[source]
Remove an association from an organization-scoped model.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- assign(project_id, model_id, *, raw=False)[source]
Assign an organization-scoped model to a project.
- associations(project_id, model_id, *, raw=False)[source]
List a model’s associations as scoped to one project.
- add_association(project_id, model_id, *, raw=False, **body)[source]
Associate a model with another component within a project.
- Parameters:
- Return type:
AIComponentAssociationResponse- Returns:
Parsed
AIComponentAssociationResponse, or the raw envelope.
- class trustwise.sdk.platform.client.GuardrailResource(http)[source]
Bases:
objectManage guardrails and run evaluations.
Accessible via
client.guardrails.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- evaluate(guardrail_id, *, raw=False, **body)[source]
Run a guardrail evaluation against input data.
- get_evaluation(guardrail_id, evaluation_id, *, raw=False)[source]
Get a specific guardrail evaluation result.
- list_evaluations_for_guardrail(guardrail_id, *, raw=False, **kwargs)[source]
List past evaluations for a single guardrail.
- Parameters:
- Return type:
list[GuardrailEvaluationListItem]- Returns:
List of
GuardrailEvaluationListItem, or the raw envelope.
- org_list_evaluations(*, raw=False, **kwargs)[source]
List guardrail evaluations across the whole organization.
Unlike
list_evaluations_for_guardrail(), this spans every guardrail in the organization.- Parameters:
- Return type:
list[GuardrailEvaluationData]- Returns:
List of
GuardrailEvaluationData, or the raw envelope.
- get_evaluation_by_id(evaluation_id, *, raw=False)[source]
Get a guardrail evaluation by its evaluation ID alone.
- providers(*, raw=False)[source]
List available guardrail providers.
- Parameters:
raw (
bool) – Return the full API envelope.- Return type:
ProvidersListResponse- Returns:
Parsed
ProvidersListResponse, or the raw envelope.
- provider_guardrails(provider, *, raw=False, max_results=50, region=None, guardrail_id=None, next_token=None)[source]
List guardrails available from a specific provider.
- export(*, slugs=None, format=None, as_file=False, raw=False)[source]
Export guardrail definitions as a portable bundle.
This route is a file download — the API sets
Content-Disposition: attachmentand the body is the exported file itself, not the usual{success, data, ...}envelope.- Parameters:
slugs (
list[str] |str|None) – Restrict the export to these guardrail slugs. Omit to export all.as_file (
bool) – Return aDownloadedFile— the raw bytes plus the server-suggested filename — ready to write to disk or pass straight toimport_().raw (
bool) – Accepted for consistency with the other methods; it has no effect here, because the body of a file download is already the payload and there is no envelope to unwrap.
- Return type:
DownloadedFile|list[dict[str,Any]] |dict[str,Any] |bytes- Returns:
A list of exported guardrail records;
byteswhen format is"yaml"; or aDownloadedFilewhen as_file is set.
- class trustwise.sdk.platform.client.PolicyResource(http)[source]
Bases:
objectManage policies and run evaluations.
Accessible via
client.policies.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- recommend(*, tags, raw=False, **body)[source]
Get policy recommendations for a given agent or use-case.
- Parameters:
- Return type:
list[PolicyRecommendation]- Returns:
List of
PolicyRecommendation, or the raw envelope.
- evaluate_batch(*, raw=False, **body)[source]
Evaluate content against multiple policies in a single request.
- export(*, slugs=None, format=None, as_file=False, raw=False)[source]
Export policy definitions as a portable bundle.
This route is a file download — the API sets
Content-Disposition: attachmentand the body is the exported file itself, not the usual{success, data, ...}envelope.- Parameters:
slugs (
list[str] |str|None) – Restrict the export to these policy slugs. Omit to export all.as_file (
bool) – Return aDownloadedFile— the raw bytes plus the server-suggested filename — ready to write to disk or pass straight toimport_().raw (
bool) – Accepted for consistency with the other methods; it has no effect here, because the body of a file download is already the payload and there is no envelope to unwrap.
- Return type:
DownloadedFile|list[dict[str,Any]] |dict[str,Any] |bytes- Returns:
A list of exported policy records;
byteswhen format is"yaml"; or aDownloadedFilewhen as_file is set.
- class trustwise.sdk.platform.client.EvaluationResource(http)[source]
Bases:
objectManage evaluations and audit logs, scoped to a project.
Accessible via
client.evaluations.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- org_list(*, raw=False, **kwargs)[source]
List evaluations across the whole organization.
- Parameters:
- Return type:
list[EvaluationListItem]- Returns:
List of
EvaluationListItem, or the raw envelope.
- list_for_agent(project_id, agent_id, *, raw=False, **kwargs)[source]
List the evaluations recorded against one agent.
- Parameters:
- Return type:
list[EvaluationListItem]- Returns:
List of
EvaluationListItem, or the raw envelope.
- audit_logs(project_id, *, raw=False, **kwargs)[source]
List policy evaluation audit logs for a project.
- v2_list(project_id, *, raw=False, **kwargs)[source]
List evaluations for a project (v2alpha).
- Parameters:
- Return type:
list[EvaluationListItem]- Returns:
List of
EvaluationListItem, or the raw envelope.
- v2_create(project_id, *, type, raw=False, **body)[source]
Create a new evaluation in a project (v2alpha).
- Parameters:
- Return type:
Evaluation- Returns:
Parsed
Evaluation, or the raw envelope.
- v2_update(project_id, evaluation_id, *, raw=False, **body)[source]
Update an existing evaluation (v2alpha).
- v2_classification(project_id, evaluation_id, *, raw=False)[source]
Get classification results for an evaluation (v2alpha).
- v2_org_list(*, raw=False, **kwargs)[source]
List evaluations across the whole organization (v2alpha).
- Parameters:
- Return type:
list[EvaluationListItem]- Returns:
List of
EvaluationListItem, or the raw envelope.
- class trustwise.sdk.platform.client.EvaluatorResource(http)[source]
Bases:
objectBrowse available evaluators and metrics.
Accessible via
client.evaluators.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.OrganizationResource(http)[source]
Bases:
objectManage organizations.
Accessible via
client.organizations.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.ProjectResource(http)[source]
Bases:
objectManage projects and component assignments.
Accessible via
client.projects.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- remove_member(project_id, assignment_id, *, raw=False)[source]
Remove a member from a project.
- Parameters:
project_id (
str) – Project identifier.assignment_id (
str) – Identifier of the membership assignment to remove — theidof the correspondinglist_members()entry, not the user’s ID.raw (
bool) – Return the full API envelope.
- Return type:
AssignmentDeleteResponse- Returns:
Parsed
AssignmentDeleteResponse, or the raw envelope.
- list_assignable_roles(project_id, *, raw=False)[source]
List the roles that can be granted on a project.
- class trustwise.sdk.platform.client.RiskEngineResource(http)[source]
Bases:
objectRun risk classification and assessments.
Accessible via
client.risk_engine.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- classify(template_id, *, raw=False, **body)[source]
Classify risk for an AI system using a risk template.
- validate(template_id, *, raw=False, **body)[source]
Validate answers against a risk template without classifying.
- initiate_evidence_upload(assessment_id, *, raw=False, **body)[source]
Initiate an evidence upload and get a presigned upload URL.
- get_evidence(assessment_id, file_id, *, raw=False)[source]
Get metadata for a single evidence file.
- download_evidence(assessment_id, file_id, *, raw=False)[source]
Get a presigned download URL for an evidence file.
- class trustwise.sdk.platform.client.AssessmentResource(http)[source]
Bases:
objectManage risk assessments and their vendor workflow.
Accessible via
client.assessments. Covers the assessment lifecycle (create, answer, submit, validate, classify) and the review/vendor workflow (decide, send/revoke to vendor, magic links, clarifications).- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- export(assessment_id, *, raw=False)[source]
Export an assessment as a portable bundle.
Returns the bundle documents plus a presigned download URL for every evidence file, ready for the caller to fetch and zip.
- import_(*, raw=False, **body)[source]
Bootstrap an assessment from an unzipped bundle.
Creates the assessment in
importingstatus and mints one presigned upload per evidence file. Upload those files, hand the returneddraft_answerstosave_answers()— which verifies every object and promotes the assessment toin_progress— then callsubmit(). An attempt interrupted mid-upload leaves the assessment inimporting; resume it rather than re-importing.- Parameters:
- Return type:
AssessmentImportResponse- Returns:
Parsed
AssessmentImportResponsecarrying the upload targets and the ready-to-save answers document, or the raw envelope.
- get_classification(assessment_id, classification_id, *, raw=False)[source]
Get a single classification for an assessment.
- decide(assessment_id, *, raw=False, **body)[source]
Record a review decision (approve/reject) on an assessment.
- create_magic_link(assessment_id, *, raw=False, **body)[source]
Generate a magic link granting external access to an assessment.
- get_magic_link(assessment_id, *, raw=False)[source]
Get details of an assessment’s active magic link.
Returns the link’s holder and a masked token — never the full token.
- resolve_magic_link(*, raw=False, **kwargs)[source]
Resolve a magic link to the assessment it grants access to.
- request_clarification(assessment_id, *, raw=False, **body)[source]
Request clarification from the assessment respondent.
- revoke_from_vendor(assessment_id, *, raw=False)[source]
Revoke an assessment that was sent to a vendor.
- send_to_vendor(assessment_id, *, raw=False, **body)[source]
Send an assessment to a vendor for completion.
- get_submission(assessment_id, submission_id, *, raw=False)[source]
Get a single submission for an assessment.
- class trustwise.sdk.platform.client.GenerationResource(http)[source]
Bases:
objectGenerate red-team prompts and test inputs.
Accessible via
client.generation.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- dynamic_red(*, raw=False, **body)[source]
Generate a dynamic red-team prompt with adaptive strategy.
- functional_red_prompt(*, raw=False, **body)[source]
Generate functional red-team prompts that target specific capabilities.
- combine_prompts(*, raw=False, **body)[source]
Combine multiple prompts into composite red-team prompts.
- class trustwise.sdk.platform.client.MetricsResource(http)[source]
Bases:
objectEvaluate metrics via the platform API.
Accessible via
client.metrics. Each method corresponds to a single metric endpoint and returns a typed Pydantic model.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- faithfulness(*, raw=False, **body)[source]
Score how faithful a response is to the provided context.
- input_type(*, raw=False, **body)[source]
Detect encoded segments (e.g. binary, hex, base64) in text.
- prompt_manipulation(*, raw=False, **body)[source]
Detect prompt manipulation attempts (jailbreak, injection, role-play).
- class trustwise.sdk.platform.client.EventResource(http)[source]
Bases:
objectBrowse and manage event notifications.
Accessible via
client.events.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- list(*, raw=False, **kwargs)[source]
List event notifications with optional filtering.
- Parameters:
- Return type:
list[EventNotification]- Returns:
List of
EventNotification, or the raw envelope.
- class trustwise.sdk.platform.client.SubscriptionResource(http)[source]
Bases:
objectManage event subscriptions (webhooks, email, Slack, etc.).
Accessible via
client.subscriptions.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.RuntimeConnectorResource(http)[source]
Bases:
objectRegister, deploy, and manage organization-scoped runtime connectors.
Accessible via
client.runtime_connectors.A connector is registered, has its wheel and (optionally) TLS material uploaded, and is then deployed. Uploads come in two flavours: a direct
multipart/form-dataPOST (wheel_upload(),tls_upload()), or a presigned URL the caller PUTs to itself (wheel_upload_url(),tls_upload_url()).CLI names (
register,wheel_upload,get_status,test) are canonical.create,upload_wheel,status, andtest_connectionare aliases.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- list(*, raw=False, **kwargs)[source]
List runtime connectors for the organization.
- Parameters:
- Return type:
- Returns:
List of connector dicts, or the raw envelope.
- register(*, raw=False, **body)[source]
Register a new runtime connector.
- Parameters:
- Return type:
- Returns:
Connector dict, or the raw envelope.
- create(*, raw=False, **body)[source]
Alias for
register().
- update(connector_id, *, raw=False, **body)[source]
Update an existing runtime connector.
- Parameters:
- Return type:
- Returns:
Connector dict, or the raw envelope.
- status(connector_id, *, raw=False)[source]
Alias for
get_status().
- update_status(connector_id, status, *, raw=False)[source]
Transition a connector via
POST …/status.Prefer
deploy()for managed plugin-worker provisioning.
- wheel_upload(connector_id, file, *, file_name='package.whl', expected_sha256=None, raw=False)[source]
Upload a wheel via multipart (local/dev fallback).
- Parameters:
- Return type:
- Returns:
Upload result dict, or the raw envelope.
- upload_wheel(connector_id, file, file_name, *, expected_sha256=None, raw=False)[source]
Alias for
wheel_upload().
- wheel_upload_url(connector_id, *, filename, raw=False, **body)[source]
Request a presigned URL for quarantine wheel upload.
- request_wheel_upload_url(connector_id, *, filename, raw=False)[source]
Alias for
wheel_upload_url().
- tls_upload(connector_id, file, *, kind, file_name='tls.pem', raw=False)[source]
Multipart TLS PEM upload for local/dev when presign is unavailable.
- Parameters:
- Return type:
- Returns:
Upload result dict, or the raw envelope.
- upload_tls(connector_id, file, file_name, *, kind, raw=False)[source]
Alias for
tls_upload().
- class trustwise.sdk.platform.client.RuntimeProviderResource(http)[source]
Bases:
objectBrowse available runtime providers and auth schemas.
Accessible via
client.runtime_providers.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.BackgroundJobResource(http)[source]
Bases:
objectInspect long-running background jobs.
Accessible via
client.jobs. Asynchronous operations (such as artifact imports) return a job id; use these methods to poll for completion.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.ImportExportResource(http)[source]
Bases:
objectExport and import artifact bundles across resource types.
Accessible via
client.artifacts. Unlike the per-resourceexport/import_methods, these operate on a multi-type bundle (guardrails, policies, models, MCP servers, agents) delivered as a zip.The
restore_*variants carry record identifiers so a bundle can be restored onto the same organization, rather than copied to a new one.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- import_(file, *, file_name='artifacts.zip', conflict_strategy=None, target_project=None, raw=False)[source]
Import a multi-type artifact bundle.
- Parameters:
file (
Any) – Bundle contents — rawbytesor an open binary file object.file_name (
str) – Name to send with the upload.conflict_strategy (
str|None) – How to handle existing records — e.g."skip","overwrite","rename".target_project (
str|None) – Project to import project-scoped artifacts into.raw (
bool) – Return the full API envelope.
- Return type:
- Returns:
The submitted job details, or the raw envelope.
- restore_export(*, raw=False, **body)[source]
Export a restorable artifact bundle (retains record identifiers).
- restore_import(file, *, file_name='artifacts.zip', target_project=None, raw=False)[source]
Restore a bundle produced by
restore_export().- Parameters:
- Return type:
- Returns:
The submitted job details, or the raw envelope.
- class trustwise.sdk.platform.client.ComponentResource(http)[source]
Bases:
objectBrowse the AI components assigned to a project.
Agents, models and MCP servers are all AI components. This resource lists them together as one inventory, whatever their individual type.
Accessible via
client.components.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.ReportEngineResource(http)[source]
Bases:
objectGenerate, poll and download rendered reports.
Report generation is asynchronous:
generate()returns a report ID,status()polls its progress, andview(),download()orpdf()fetch the finished artifact. Thecatalogue_*methods describe the templates, components and datasources available to build one.Accessible via
client.reports.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- download(report_id, *, as_file=False)[source]
Download a generated report.
This route answers with the report artifact itself rather than the
{success, data, ...}envelope, so the bytes are returned unparsed.- Parameters:
- Return type:
- Returns:
The report bytes, or a
DownloadedFilewhen as_file is set.
- pdf(report_id, *, as_file=False)[source]
Download a generated report as a PDF.
- Parameters:
- Return type:
- Returns:
The PDF bytes, or a
DownloadedFilewhen as_file is set.
- catalogue_templates()[source]
List the report templates available to
generate().
- catalogue_template(name)[source]
Get a template’s source and front-matter.
- Parameters:
name (
str) – Template name, as listed bycatalogue_templates().- Return type:
- catalogue_component(name)[source]
Get a component’s source and description.
- Parameters:
name (
str) – Component name, as listed bycatalogue_components().- Return type:
- class trustwise.sdk.platform.client.UserResource(http)[source]
Bases:
objectRead the users in an organization.
Accessible via
client.users.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
- class trustwise.sdk.platform.client.RbacResource(http)[source]
Bases:
objectRead role-based access control metadata.
Only the discovery endpoint is exposed: the SDK does not wrap the RBAC role, permission, mapping or assignment management routes.
Accessible via
client.rbac.- Parameters:
http (PlatformHTTP)
- __init__(http)[source]
- Parameters:
http (PlatformHTTP)
- Return type:
None
Platform HTTP Transport
HTTP transport for the Platform API, reusing SDK conventions.
- class trustwise.sdk.platform._http.DownloadedFile(name, content, content_type=None)[source]
Bases:
NamedTupleA response the server marked as a file attachment.
nameis the server-suggested filename fromContent-Disposition;contentis the body verbatim, suitable for writing to disk or handing straight back to the matchingimport_endpoint.
- trustwise.sdk.platform._http._attachment_name(headers)[source]
Extract the filename from a
Content-Dispositionheader, if any.
- class trustwise.sdk.platform._http.PlatformHTTP(config, *, timeout=30)[source]
Bases:
objectLow-level HTTP helper built on the same
requests+TrustwiseConfigstack used byTrustwiseHTTPClient.Unlike the metrics client (POST-only), the platform API needs all four HTTP verbs.
- Parameters:
config (TrustwiseConfig)
timeout (int)
- __init__(config, *, timeout=30)[source]
- Parameters:
config (TrustwiseConfig)
timeout (int)
- Return type:
None
- get_file(path, **params)[source]
GET a route that answers with a file attachment.
The
/exportroutes setContent-Disposition: attachmentand return the file body itself — a bare JSON list or a YAML document — rather than the usual{success, data, ...}envelope. This keeps the bytes and the server-suggested filename together so the result can be written to disk or passed back to the matchingimport_endpoint unchanged.- Return type:
- Parameters:
- post_binary(path, body, **params)[source]
POST a JSON body to an endpoint that streams bytes back (e.g. zip).
Assessment Bundle Transfer
Helpers for the client-driven half of assessment import/export: moving evidence files to and from the presigned URLs the platform mints. These are module-level functions rather than client methods, so they stay out of the generated CLI.
Evidence transfer for the assessment import/export bundle flows.
These are module-level functions rather than AssessmentResource methods on
purpose. The CLI auto-generates a Click command for every public method it finds on
a resource class, and a method taking raw bytes would turn into a nonsense
subcommand. Keeping them here makes them invisible to that machinery.
The step order they serve is the same one the portal implements, so both clients behave identically against the same server:
POST /assessments/importreturns presigned uploads plus a ready-to-PUT draft.Upload every evidence file in parallel (
upload_evidence()).PUT /assessments/{id}/answerswith the echoed draft (answers_payload()).Re-upload anything the server rejected, then
POST /assessments/{id}/submit.
Export is the mirror: GET /assessments/{id}/export then
download_evidence().
- class trustwise.sdk.utils.assessment_bundle.EvidenceBlob(data, filename, content_type=None)[source]
Bases:
NamedTupleOne evidence file’s bytes plus the metadata an upload needs.
- Variables:
data – Raw file bytes.
filename – Original filename, sent as
x-filenameon a loopback upload (the local backend falls back to the file id without it).content_type – Content type, when the bundle recorded one.
- Parameters:
- trustwise.sdk.utils.assessment_bundle._as_dict(value)[source]
Normalize a pydantic model or mapping into a plain dict.
Responses arrive as generated models when the spec is current and as plain dicts otherwise (and in tests), so every accessor below works on one shape.
- trustwise.sdk.utils.assessment_bundle.answers_payload(draft_answers)[source]
Render the import response’s
draft_answersforPUT /answers.The server hands back a ready-to-PUT document and expects it echoed unchanged. This is that echo — JSON-rendered because
requestscannot serialize pydantic models, with unset fields dropped so nulls the server never sent (object_key) stay off the wire.
- trustwise.sdk.utils.assessment_bundle.answers_body(draft_answers, updated_at)[source]
Build the
PUT /answersbody from an import response.- Parameters:
- Return type:
- Returns:
The request body for
PUT /assessments/{id}/answers.- Raises:
TrustwiseValidationError – If no lock token is available. The server rejects a null one, so failing here beats sending an empty string.
- trustwise.sdk.utils.assessment_bundle.upload_evidence(uploads, payloads, *, api_base_url, api_key, max_workers=5)[source]
Upload every evidence file to the URL the import response minted for it.
Uploads run in parallel with no per-file retry: the first failure aborts the batch, and recovery is re-running the import (which mints fresh URLs for everything). This matches the portal.
Two kinds of URL come back, and they need opposite treatment:
A real presigned URL on the blob store’s own host gets only the headers the server signed. Sending a Trustwise credential there would leak it.
A URL on the API’s own origin is the local backend’s loopback route, which cannot presign and authenticates normally. That one needs the bearer token, plus
x-filenameso the stored file keeps its name.
- Parameters:
payloads (
dict[str,EvidenceBlob]) – Evidence bytes keyed by the bundle’s own file id, which the server echoes back assource_file_id.api_base_url (
str) – The Trustwise API base URL, used to recognise loopback URLs.api_key (
str) – Trustwise API key, sent only to a loopback URL.max_workers (
int) – Upper bound on concurrent uploads.
- Raises:
TrustwiseValidationError – If an upload references bytes the bundle lacks.
TrustwiseAPIError – If any upload fails.
- Return type:
- trustwise.sdk.utils.assessment_bundle.download_evidence(evidence, *, max_workers=5)[source]
Download every evidence file listed in an export manifest.
Downloads run in parallel and send no credentials — the presigned URL is the credential. Checksums are not verified here; the caller verifies them against the bundle’s own
answers.jsonbefore writing anything.
Blob Transfer
Direct blob-storage transfer helpers for presigned URLs.
Presigned PUT/GET targets point at the blob store (S3/MinIO/GCS/Azure), not the
Trustwise platform API, so these transfers must NOT go through PlatformHTTP —
that transport is locked to the platform base URL, forces Content-Type:
application/json, and would leak the Trustwise Authorization header to the
blob host. These helpers use requests directly instead.
Note that requests sends no Content-Type of its own for a bytes body.
That is deliberate and must stay that way: S3 and GCS sign the header set into the
URL, so an extra header the presign did not cover makes the store reject the PUT.
Pass exactly the headers the server handed back and nothing else.
- trustwise.sdk.utils.blob.put_presigned(upload_url, data, headers=None, *, timeout=60)[source]
PUT raw bytes to a presigned upload URL.
- Parameters:
upload_url (
str) – The presigned PUT URL.data (
bytes) – Raw file bytes to upload.headers (
dict[str,str] |None) – Headers to echo on the PUT (e.g. theContent-Typethe presign was signed with). S3/MinIO bindContent-Typeinto the signature, so it must match exactly or the store rejects the PUT.timeout (
int) – Request timeout in seconds.
- Raises:
TrustwiseAPIError – If the blob store returns a non-2xx status, or the request never completed (DNS, TLS, connection reset, timeout).
- Return type:
- trustwise.sdk.utils.blob.get_presigned(download_url, *, timeout=60)[source]
GET the bytes behind a presigned download URL.
No headers and no credentials are sent: the URL itself is the credential.
- Parameters:
- Return type:
- Returns:
The object’s raw bytes.
- Raises:
TrustwiseAPIError – If the blob store returns a non-2xx status, or the request never completed.
- trustwise.sdk.utils.blob.map_parallel(fn, items, *, max_workers=5)[source]
Call
fnon every item concurrently, preserving input order.Never raises: a failing item is reported in its own tuple so the caller can name the file that failed instead of losing the batch to one traceback.
- trustwise.sdk.utils.blob.same_origin(url, other)[source]
Report whether two URLs share a scheme, host and port.
Used to tell a real presigned blob URL from a loopback URL that points back at the Trustwise API itself (which the backend mints when it runs with a local storage provider, and which needs the Trustwise credential rather than none).
Exceptions
- exception trustwise.sdk.exceptions.TrustwiseSDKError[source]
Bases:
ExceptionBase exception for all Trustwise SDK errors.
- exception trustwise.sdk.exceptions.TrustwiseValidationError[source]
Bases:
TrustwiseSDKErrorException for validation errors in Trustwise SDK.
- exception trustwise.sdk.exceptions.TrustwiseAPIError(message, response, status_code)[source]
Bases:
TrustwiseSDKError
SDK (Legacy)
Deprecated since version ``TrustwiseSDK``: is deprecated. Migrate to TrustwiseClient.
See Migrating from TrustwiseSDK to TrustwiseClient for a step-by-step guide.
- class trustwise.sdk.TrustwiseSDK(config)[source]
Bases:
objectMain SDK class for Trustwise API access.
Provides access to all metrics through version-specific paths.
Deprecated since version Use:
trustwise.sdk.platform.client.TrustwiseClientinstead.TrustwiseClientis a superset of this SDK and covers all metrics, guardrails, policies, and platform APIs.- Parameters:
config (TrustwiseConfig)
- __init__(config)[source]
Initialize the Trustwise SDK with path-based versioning support.
- Parameters:
config (
TrustwiseConfig) – Trustwise configuration instance.- Return type:
None
- class trustwise.sdk.TrustwiseSDKAsync(config)[source]
Bases:
objectAsync SDK entrypoint for Trustwise. Use this class to access async metrics.
- Parameters:
config (TrustwiseConfig)
- __init__(config)[source]
Initialize the Trustwise SDK with path-based versioning support.
- Parameters:
config (
TrustwiseConfig) – Trustwise configuration instance.- Return type:
None
Configuration
Simple configuration for Trustwise API with environment variable support.
- class trustwise.sdk.config.TrustwiseConfig(**data)[source]
Bases:
BaseModelConfiguration for Trustwise API.
This class handles configuration for the Trustwise API, including authentication and endpoint URLs. It supports both direct initialization and environment variables.
- Parameters:
api_key (str, Optional) – API key for authentication. If not provided, will be read from TW_API_KEY environment variable. Required for API access.
base_url (str, Optional) – Base URL for API endpoints. If not provided, will be read from TW_BASE_URL environment variable or default to https://api.trustwise.ai.
- Environment Variables:
TW_API_KEY: API key for authentication
TW_BASE_URL: Base URL for API endpoints (defaults to https://api.trustwise.ai)
Example
>>> from trustwise.sdk.config import TrustwiseConfig >>> # Using environment variables >>> config = TrustwiseConfig() >>> # Using direct initialization >>> config = TrustwiseConfig(api_key="your-api-key", base_url="https://api.trustwise.ai")
- Raises:
ValueError – If API key is missing or invalid, or if base URL is invalid
- Parameters:
- __init__(**data)[source]
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Return type:
None
Types
Types for v4 metrics.
- class trustwise.sdk.metrics.v4.types.Score(**data)[source]
Bases:
SDKBaseModelA score value between 0 and 100.
- Parameters:
value (float) – Score value between 0 and 100.
- class trustwise.sdk.metrics.v4.types.ObjectStyleScore(**data)[source]
Bases:
SDKBaseModelObject style score with label.
- class trustwise.sdk.metrics.v4.types.ContextChunk(**data)[source]
Bases:
SDKBaseModelA single context chunk for v4 context relevancy evaluation.
- Parameters:
- class trustwise.sdk.metrics.v4.types.ContextRelevancyRequest(**data)[source]
Bases:
SDKRequestModelRequest type for v4 context relevancy evaluation.
- Parameters:
metadata (dict) – Optional metadata to be returned in the response.
query (str) – The input query string.
context (list) – A non-empty list of context chunks.
severity (float | None) – (Optional) severity level (0-1).
include_chunk_scores (bool | None) – (Optional) Whether to include individual chunk scores in the response.
- context: list[ContextChunk]
- class trustwise.sdk.metrics.v4.types.PromptManipulationRequest(**data)[source]
Bases:
SDKRequestModelRequest type for v4 prompt manipulation evaluation.
- Parameters:
- class trustwise.sdk.metrics.v4.types.PromptManipulationResponse(**data)[source]
Bases:
SDKResponseModelResponse type for prompt manipulation detection.
Higher scores indicate a greater likelihood that the text contains prompt manipulation attempts that could manipulate the AI system.
- Parameters:
- scores: list[ObjectStyleScore]
- class trustwise.sdk.metrics.v4.types.AnswerRelevancyRequest(**data)[source]
Bases:
SDKRequestModelRequest type for answer relevancy evaluation.
- Parameters:
- class trustwise.sdk.metrics.v4.types.AnswerRelevancyResponse(**data)[source]
Bases:
SDKResponseModelResponse type for answer relevancy evaluation.
Answer relevancy measures how well the response addresses the specific query. A higher score indicates the response is more directly relevant to the question asked.
- Parameters:
- class trustwise.sdk.metrics.v4.types.FaithfulnessRequest(**data)[source]
Bases:
SDKRequestModelRequest type for faithfulness evaluation.
- Parameters:
metadata (dict[str, object] | None) – Optional metadata for the request that will be included in the response.
query (str) – The input query string.
response (str) – The response to evaluate.
context (list) – A non-empty list of context chunks.
severity (float | None) – (Optional) severity level (0-1).
include_citations (bool | None) – Whether to include citations in the response. If true, a unique chunk_id must additionally be provided for each context chunk.
- context: list[ContextChunk]
- class trustwise.sdk.metrics.v4.types.Statement(**data)[source]
Bases:
SDKBaseModelA verified fact extracted from a response.
- Parameters:
statement (str) – The extracted statement from the response text that represents a ‘atomically’ fact
label (str) – The label indicating the fact’s hallucination status. One of (‘Safe’, ‘Unsafe’, ‘Intrinsic Hallucination’, ‘Extrinsic Hallucination’)
probability (float) – The associated probability of the label (0-1)
sentence_span (list) – A list of two integers [start, end] indicating the character positions of this statement in the response text
- class trustwise.sdk.metrics.v4.types.FaithfulnessResponse(**data)[source]
Bases:
SDKBaseModelResponse type for faithfulness evaluation.
Faithfulness measures how well the response adheres to the provided context. A higher score indicates better alignment with the source material.
- Parameters:
score (float) – Faithfulness score (0-100). A higher score, indicating a better response, is correlated with a higher confidence in each statement being true, and also a higher proportion of statements being true with respect to the context.
statements (list) – List of extracted ‘atomic’ statements from the response, each containing the statement, label, associated probability, and location in the text.
- class trustwise.sdk.metrics.v4.types.ContextRelevancyResponse(**data)[source]
Bases:
SDKResponseModelResponse type for context relevancy evaluation.
Context relevancy measures how well the provided context is relevant to the query. A higher score indicates the context is more directly relevant to the question asked.
- Parameters:
- scores: list[ObjectStyleScore]
- class trustwise.sdk.metrics.v4.types.ClarityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for clarity evaluation.
Clarity measures how easy text is to read. It gives higher scores to writing that contains words which are easier to read, and uses concise, self-contained sentences. It does not measure how well you understand the ideas in the text.
- Parameters:
- class trustwise.sdk.metrics.v4.types.ClarityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for clarity evaluation.
Clarity scores indicate how clear and understandable the response is. Higher scores suggest better readability and comprehension.
- Parameters:
score (float) – A score from 0-100 indicating how clear and understandable the response is. Higher scores indicate better clarity of the response.
- class trustwise.sdk.metrics.v4.types.FormalityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for formality evaluation.
Formality measures the level of formality in written text, distinguishing between casual, conversational, and formal writing styles.
- Parameters:
- class trustwise.sdk.metrics.v4.types.FormalityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for formality evaluation.
Formality scores indicate the level of formality in the text. Higher scores indicate more formal writing, lower scores indicate more casual writing.
- Parameters:
score (float) – Formality score (0-100). The Formality metric judges how formal a piece of text is. A higher score indicates the text is more formal, and a lower score indicates the text is more informal.
- class trustwise.sdk.metrics.v4.types.SimplicityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for simplicity evaluation.
Simplicity measures how easy it is to understand the words in a text. It gives higher scores to writing that uses common, everyday words instead of special terms or complicated words. Simplicity looks at the words you choose, not how you put them together in sentences.
- Parameters:
- class trustwise.sdk.metrics.v4.types.SimplicityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for simplicity evaluation.
Simplicity measures how easy it is to understand the words in a text. It gives higher scores to writing that uses common, everyday words instead of special terms or complicated words. Simplicity looks at the words you choose, not how you put them together in sentences.
- Parameters:
score (float) – Simplicity score (0-100). A higher score indicates a simpler response, with fewer words and simpler language which is easier to understand.
- class trustwise.sdk.metrics.v4.types.ToneRequest(**data)[source]
Bases:
SDKRequestModelRequest type for tone evaluation.
Tone evaluation identifies the emotional tone and sentiment expressed in the text across multiple emotional categories.
- Parameters:
- class trustwise.sdk.metrics.v4.types.ToneResponse(**data)[source]
Bases:
SDKResponseModelResponse type for tone evaluation.
Tone analysis identifies the emotional tones present in the text, with confidence scores for each detected tone category.
- Parameters:
scores (list) – List of detected tones with confidence scores (0-100). Higher scores indicate stronger presence of that tone.
- scores: list[ObjectStyleScore]
- class trustwise.sdk.metrics.v4.types.ToxicityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for toxicity evaluation.
Toxicity evaluation identifies harmful or inappropriate content across multiple categories like threats, insults, and hate speech.
- Parameters:
- class trustwise.sdk.metrics.v4.types.ToxicityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for toxicity evaluation.
Toxicity scores indicate the presence of harmful content across different categories. Higher scores indicate more toxic content, so lower scores are preferred.
- Parameters:
- scores: list[ObjectStyleScore]
- class trustwise.sdk.metrics.v4.types.PIIEntity(**data)[source]
Bases:
SDKBaseModelA detected piece of personally identifiable information.
PII entities represent sensitive information that has been identified in text, including its location and category.
- Parameters:
- class trustwise.sdk.metrics.v4.types.PIIRequest(**data)[source]
Bases:
SDKRequestModelRequest type for PII detection.
PII detection identifies personally identifiable information in text based on customizable allowlists and blocklists.
- Parameters:
metadata (dict[str, object] | None) – Optional metadata for the request that will be included in the response.
text (str) – The text to evaluate for PII detection.
allowlist (list[str] | None) – (Optional) List of allowed PII strings or regex patterns.
blocklist (list[str] | None) – (Optional) List of blocked PII strings or regex patterns.
categories (list[str] | None) – (Optional) List of PII categories to evaluate.
- class trustwise.sdk.metrics.v4.types.PIIResponse(**data)[source]
Bases:
SDKResponseModelResponse type for PII detection.
Contains all detected PII entities with their locations and categories for further processing or filtering.
- Parameters:
pii (list) – List of detected PII occurrences.
- class trustwise.sdk.metrics.v4.types.HelpfulnessRequest(**data)[source]
Bases:
SDKRequestModelRequest type for helpfulness evaluation.
Helpfulness measures how useful a given text is. It gives higher scores to texts that fully explain a topic. Helpful responses provide clear, complete information.
- Parameters:
- class trustwise.sdk.metrics.v4.types.HelpfulnessResponse(**data)[source]
Bases:
SDKResponseModelResponse type for helpfulness evaluation.
Helpfulness measureshow useful a given text is. It gives higher scores to texts that fully explain a topic. Helpful responses provide clear, complete information.
- Parameters:
score (float) – A score from 0-100 indicating how helpful the response is. Higher scores indicate better helpfulness of the response.
- class trustwise.sdk.metrics.v4.types.SensitivityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for sensitivity evaluation.
Exactly one of
topicsorhypothesesmust be provided - they are mutually exclusive.- Parameters:
metadata (dict[str, object] | None) – Optional metadata for the request that will be included in the response.
text (str) – The text to evaluate for sensitivity.
topics (list[str] | None) – List of topics to check for sensitivity. Mutually exclusive with hypotheses.
hypotheses (list[str] | None) – List of custom hypotheses to check for sensitivity. Mutually exclusive with topics.
- class trustwise.sdk.metrics.v4.types.SensitivityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for sensitivity evaluation.
Sensitivity evaluation checks for the presence of specific topics or themes in the text, providing scores for each requested topic.
- Parameters:
scores (list) – List of sensitivity scores for each requested topic (0-100). A high score for a topic indicates that the topic is present in the text.
- scores: list[ObjectStyleScore]
- class trustwise.sdk.metrics.v4.types.RefusalRequest(**data)[source]
Bases:
SDKRequestModelRequest type for refusal evaluation.
Refusal measures the likelihood that a response is a refusal to answer or comply with the query. This metric helps identify when AI systems decline to provide information or perform tasks.
- Parameters:
- class trustwise.sdk.metrics.v4.types.RefusalResponse(**data)[source]
Bases:
SDKResponseModelResponse type for refusal evaluation.
Refusal scores indicate the likelihood that the response is a refusal to answer or comply. Higher scores indicate stronger refusal behavior.
- Parameters:
score (float) – Refusal score (0-100). A higher score indicates a higher degree (firmness) of refusal.
- class trustwise.sdk.metrics.v4.types.CompletionRequest(**data)[source]
Bases:
SDKRequestModelRequest type for completion evaluation.
Completion measures how well the response completes or follows the query’s instruction.
- Parameters:
- class trustwise.sdk.metrics.v4.types.CompletionResponse(**data)[source]
Bases:
SDKResponseModelResponse type for completion evaluation.
Completion score indicates how well the response completes the query (0-100).
- Parameters:
score (float) – Completion score (0-100). A higher score indicates a better completion of the query.
- class trustwise.sdk.metrics.v4.types.AdherenceRequest(**data)[source]
Bases:
SDKRequestModelRequest type for adherence evaluation.
Adherence evaluation measures how well the response follows a given policy or instruction.
- Parameters:
- class trustwise.sdk.metrics.v4.types.AdherenceResponse(**data)[source]
Bases:
SDKResponseModelResponse type for adherence evaluation.
Adherence score indicates how well the response follows the policy (0-100).
- Parameters:
score (float) – Adherence score (0-100). A higher score indicates better adherence to the policy.
- class trustwise.sdk.metrics.v4.types.StabilityRequest(**data)[source]
Bases:
SDKRequestModelRequest type for stability evaluation.
Stability evaluation measures the consistency of responses to the same prompt.
- Parameters:
- class trustwise.sdk.metrics.v4.types.StabilityResponse(**data)[source]
Bases:
SDKResponseModelResponse type for stability evaluation.
Stability measures how consistent the responses are. A higher score indicates greater consistency among the responses.
- Parameters:
- class trustwise.sdk.metrics.v4.types.DetectedEncoding(**data)[source]
Bases:
SDKBaseModelA single encoded segment detected within the input text.
- Parameters:
- class trustwise.sdk.metrics.v4.types.InputTypeRequest(**data)[source]
Bases:
SDKRequestModelRequest type for input type evaluation.
Input type detection scans text for encoded segments such as binary, hex, or base64.
- Parameters:
- class trustwise.sdk.metrics.v4.types.InputTypeResponse(**data)[source]
Bases:
SDKResponseModelResponse type for input type detection.
Reports any encoded segments (e.g. binary, hex, base64) found in the input text, each with its label, character span, and the detected substring.
- Parameters:
encodings (list) – The list of detected encoded segments. Empty if no encodings were found.
- encodings: list[DetectedEncoding]
- class trustwise.sdk.metrics.v4.types.CarbonValue(**data)[source]
Bases:
SDKBaseModelA carbon value with unit.
- Parameters:
- class trustwise.sdk.metrics.v4.types.CarbonComponent(**data)[source]
Bases:
SDKBaseModelA carbon component breakdown.
- Parameters:
component (str) – The component name (e.g., ‘operational_gpu’, ‘operational_cpu’, ‘embodied_cpu’).
carbon (CarbonValue) – The carbon value for this component.
- carbon: CarbonValue
- class trustwise.sdk.metrics.v4.types.CarbonRequest(**data)[source]
Bases:
SDKRequestModelRequest type for carbon evaluation.
Carbon evaluation measures the carbon footprint of AI operations based on provider, instance type, region, and latency.
- class trustwise.sdk.metrics.v4.types.CarbonResponse(**data)[source]
Bases:
SDKResponseModelResponse type for carbon evaluation.
Carbon evaluation provides the total carbon footprint and breakdown by component (operational GPU, operational CPU, embodied CPU).
- Parameters:
carbon (CarbonValue) – The total carbon footprint.
components (list) – Breakdown of carbon footprint by component.
- carbon: CarbonValue
- components: list[CarbonComponent]
Base Types
- class trustwise.sdk.types.SDKBaseModel(**data)[source]
Bases:
BaseModelBase model for all SDK types with common functionality.
- to_json(**kwargs)[source]
Return a JSON string representation of the model. Ensures valid JSON output regardless of Pydantic version. Always excludes None fields by default.
- classmethod validate_score_range(v, min_value, max_value, label)[source]
Validate that a score or list/dict of scores falls within the specified range.
- static format_validation_error(model_cls, validation_error)[source]
Format a Pydantic ValidationError into a user-friendly error message using field types and descriptions. Distinguishes between missing and invalid arguments, and sets the error prefix accordingly.
- _get_field_description(field_name, field_info=None)[source]
Get the description for a field from its field info.
- _format_output(indent=0)[source]
Format the model’s output with proper indentation and descriptions. Used by both __repr__ and __str__ to ensure consistent output.
- _format_nested_dict(data, model_class=None, indent=0)[source]
Format a nested dictionary with field descriptions. If model_class is provided, it will be used to look up field descriptions.
- _repr_mimebundle_(include=None, exclude=None)[source]
Return multiple representations of the object. This is the preferred way to provide multiple representations in Jupyter.
- _format_html(indent_level=0)[source]
Format the model’s output as HTML with proper styling. Used by __repr_html__ to create a pretty representation in Jupyter notebooks.
- _get_value_css_class(value)[source]
Return the appropriate CSS class for a value based on its type.
- class trustwise.sdk.types.SDKRequestModel(**data)[source]
Bases:
SDKBaseModelBase model for all SDK request types.
- class trustwise.sdk.types.SDKResponseModel(**data)[source]
Bases:
SDKBaseModelBase model for all SDK response types.
- class trustwise.sdk.types.CostResponseV3(**data)[source]
Bases:
SDKResponseModelResponse type for cost evaluation.
- Parameters:
- class trustwise.sdk.types.CostRequestV3(**data)[source]
Bases:
SDKRequestModelRequest type for cost evaluation.
- Parameters:
metadata (dict[str, object] | None) – Optional metadata for the request that will be included in the response.
model_name (str) – Model name must be a non-empty string.
model_type (Literal) – Model type must be ‘LLM’ or ‘Reranker’.
model_provider (str) – Model provider must be a non-empty string. Should be one of [‘openai’, ‘togetherai’, ‘huggingface’, ‘nvidia’, ‘azure’]
number_of_queries (int) – Number of queries must be > 0.
total_prompt_tokens (int) – (Optional)Total number of prompt tokens (must be > 0).
total_completion_tokens (int) – (Optional)Total number of completion tokens (must be > 0).
total_tokens (Optional[Annotated]) – (Optional) Total tokens (optional, must be > 0 if provided).
instance_type (str | None) – (Optional) Instance type required for Hugging Face models.
average_latency (Optional[Annotated]) – (Optional) Average latency in milliseconds, must be > 0 if provided.
- model_name: Annotated[str, StringConstraints(strip_whitespace=True, to_upper=None, to_lower=None, strict=None, min_length=1, max_length=None, pattern=None, ascii_only=None)]