Metadata-Version: 2.4
Name: qyrusai
Version: 1.0.10
Summary: Qyrus AI SDK
Home-page: 
Author: Qyrus Inc
Author-email: support@qyrus.com
Requires-Python: >=3.7
Description-Content-Type: text/markdown
Requires-Dist: httpx==0.25.0
Requires-Dist: pydantic==2.4.2
Requires-Dist: fastapi==0.111.0
Requires-Dist: requests<3,>=2.31.0
Dynamic: author
Dynamic: author-email
Dynamic: description
Dynamic: description-content-type
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# QyrusAI Python SDK

The **QyrusAI Python SDK** provides a _Python client_ to access our **_SOTA Single Use testing Agents_** for _test case generation_, _test data generation_, _API test case generation_, and many more.

## Key Features

- **Nova:** Nova generates functional **test scenarios**, then **test steps** (2-stage) from JIRA, Rally, Azure DevOps, or a user description. Supports optional **Guidance Prompts** (`guidance_prompt` parameter or `GUIDANCE_PROMPT` in `.env`) for injecting authoritative test execution data, credentials, and form values into ticketing workflows. `app_url` is optional.
- **Nova API Assertions:** Nova API Assertions provide a quick way to create assertions to test API responses. These assertions include _header, schema, JSON Path, and JSON Body_ test cases.
- **API Builder**: API builder helps in visualizing virtualized APIs and provide a well planned Swagger documentation with APIs for the provided use case description.
- **Vision Nova**: Vision Nova helps in creating functional tests from Figma design frames.
- **Data Amplification**: Data Amplification helps create highly realistic context specific data for testing needs.
- **LLM Evaluator**: LLM Evaluator provides comprehensive evaluation for RAG (Retrieval-Augmented Generation) and MCP (Model Context Protocol) systems with advanced metrics.

## Installation

You can install `qyrusai` from the source as of now.

### From Source

```
pip install git+https://github.com/QQyrus/qyrusai-sdk.git
```

## Usage

Nova is a **2-stage** flow:

1. **Generate scenarios** → wait for `job_id` and each scenario’s `test_script_id`
2. **Generate steps** → pass that `job_id` and the ids you want, e.g. `[1, 4, 5]`

`app_url` is optional on every scenario call. Skip it if you do not have an application URL.

### Initialize QyrusAI SDK

```py
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="sk_staging_...")
```

### Generate scenarios from a JIRA ticket

```py
scenarios_resp = client.nova.generate_scenarios.from_jira(
    jira_endpoint="https://your-domain.atlassian.net",
    jira_api_token="your_jira_token",
    jira_username="your_jira_email",
    jira_id="PROJ-123",
    # app_url="https://your-app.example.com",  # optional
    # guidance_prompt="Use username test_user@bank.com and password ValidPass@2026!",  # optional (falls back to .env)
)

print(scenarios_resp.job_id)
for scenario in scenarios_resp.scenarios or []:
    print(scenario.test_script_id, scenario.test_script_name)

steps_resp = client.nova.generate_steps.create(
    job_id=scenarios_resp.job_id,
    test_script_ids=[1, 4, 5],  # pick ids from the response above
    # guidance_prompt="...",  # optional override
)
```

### Generate scenarios from a user description

```py
scenarios_resp = client.nova.generate_scenarios.from_description(
    "Create tests for login page",
    # app_url="https://your-app.example.com",  # optional
)

steps_resp = client.nova.generate_steps.create(
    job_id=scenarios_resp.job_id,
    test_script_ids=[1, 4, 5],
)
```

### Generate scenarios from a Rally ticket

```py
scenarios_resp = client.nova.generate_scenarios.from_rally(
    rally_host_url="https://rally1.rallydev.com",
    rally_api_key="your_rally_api_key",
    ticket_id="US12345",
    rally_workspace_url="https://rally1.rallydev.com/slm/webservice/v2.0/workspace/...",
    # guidance_prompt="...",  # optional
)

steps_resp = client.nova.generate_steps.create(
    job_id=scenarios_resp.job_id,
    test_script_ids=[1, 4, 5],
)
```

### Generate scenarios from Azure DevOps

```py
scenarios_resp = client.nova.generate_scenarios.from_azure(
    work_item_id=12345,
    personal_access_token="your_ado_pat",
    organization_name="your-ado-org",
    # guidance_prompt="...",  # optional
)

steps_resp = client.nova.generate_steps.create(
    job_id=scenarios_resp.job_id,
    test_script_ids=[1, 4, 5],
)
```

Legacy aliases (`client.nova.from_jira.create(...)`, `from_description.create(...)`, `from_rally.create(...)`) still map to `generate_scenarios`. Prefer `generate_scenarios` / `generate_steps`.

## Guidance Prompt (Ticketing Integrations & Test Execution Data)

When generating test scenarios and steps from enterprise ticketing tools (**Jira**, **Rally**, **Azure DevOps**), ticket descriptions define business requirements and acceptance criteria but frequently lack concrete execution test data (e.g. valid login credentials, MFA codes, or specific form input values like loan amounts, employment types, or account IDs).

The **Guidance Prompt** allows you to supply authoritative test execution data and instructions alongside the ticket without modifying the original ticket content in Jira/Rally/ADO.

### Key Capabilities & Rules:
1. **Scenario Generation**: The guidance prompt ensures generated test scenarios incorporate and test against specific roles, accounts, and input conditions.
2. **Step Generation**: In Step Generation, guidance prompt data takes top precedence—ensuring explicit credentials and form values are injected directly into each step's `dataValue` rather than generic dummy placeholders.
3. **Strict Scope**: Guidance prompt is strictly scoped to ticketing integrations (`jira`, `rally`, `azure`). Free-text descriptions (`from_description`) do not use guidance prompts.
4. **Zero-Code Environment Fallback**: If not provided directly in code, the SDK automatically reads `GUIDANCE_PROMPT` (or `NOVA_GUIDANCE_PROMPT`) from your environment or local `.env` file via `python-dotenv`.

### Configuration via `.env` (Zero-Code Automatic Fallback)
You can define `GUIDANCE_PROMPT` in your local `.env` file:

```env
# .env
QYRUS_API_TOKEN=sk_staging_...
JIRA_ENDPOINT=https://your-domain.atlassian.net
JIRA_USERNAME=user@qyrus.com
JIRA_API_TOKEN=your_jira_token
JIRA_ID=TX-1142

# Optional Guidance Prompt for Scenarios & Step Generation
GUIDANCE_PROMPT=Test Execution Guidance: User Role: Customer (Username: test_borrower@qbank.com, Password: ValidPassword@2026!), Loan Amount: 500000, Tenure: 36 Months, Monthly Income: 50000, Employment Type: Salaried.
```

When configured in `.env`, calling `stream_from_jira`, `from_jira`, `from_rally`, or `from_azure` without a `guidance_prompt` argument automatically resolves and attaches the guidance prompt from the environment.

### Passing Directly in Code (Override)
You can also pass `guidance_prompt` directly as a parameter. Explicit parameters take precedence over `.env` values:

```python
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="sk_staging_...")

guidance = (
    "Test Execution Guidance & Specific Form Values:\n"
    "- User Role: Customer (Username: test_borrower@qbank.com, Password: ValidPassword@2026!)\n"
    "- Loan Product Type: Personal Loan\n"
    "- Loan Amount: 500000\n"
    "- Tenure: 36 Months\n"
    "- Monthly Income: 50000\n"
    "- Employment Type: Salaried"
)

# 1. Generate scenarios with guidance prompt
scenarios_resp = client.nova.generate_scenarios.from_jira(
    jira_endpoint="https://your-domain.atlassian.net",
    jira_api_token="your_jira_token",
    jira_username="user@qyrus.com",
    jira_id="TX-1142",
    guidance_prompt=guidance,  # optional override
)

# 2. Generate steps with guidance prompt
steps_resp = client.nova.generate_steps.create(
    job_id=scenarios_resp.job_id,
    test_script_ids=[1, 4, 5],
    guidance_prompt=guidance,  # optional override
)
```

### Real-Time SSE Streaming with Guidance Prompt

```python
import os
from dotenv import load_dotenv
from qyrusai import SyncQyrusAI

load_dotenv()
client = SyncQyrusAI(api_key=os.environ.get("QYRUS_API_TOKEN"))

# Stream scenarios in real-time (picks up GUIDANCE_PROMPT from .env automatically)
job_id = None
scenario_ids = []

for event in client.nova.generate_scenarios.stream_from_jira(
    jira_endpoint=os.environ.get("JIRA_ENDPOINT"),
    jira_api_token=os.environ.get("JIRA_API_TOKEN"),
    jira_username=os.environ.get("JIRA_USERNAME"),
    jira_id=os.environ.get("JIRA_ID"),
    # guidance_prompt="...",  # optional override
):
    job_id = event.job_id or job_id
    if event.scenario:
        scenario_ids.append(event.scenario.test_script_id)
        print(f"[scenario] {event.scenario.test_script_id} {event.scenario.test_script_name}")
    elif event.job_status:
        print(f"[status] {event.job_status}")

# Stream steps in real-time (injects form inputs & credentials from guidance prompt)
for event in client.nova.generate_steps.stream(
    job_id=job_id,
    test_script_ids=scenario_ids[:3],
    # guidance_prompt="...",  # optional override
):
    if event.step:
        print(f"[step] {event.step.test_script_id} #{event.step.stepNumber}: {event.step.stepDescription} -> value: {event.step.dataValue}")
    elif event.job_status:
        print(f"[status] {event.job_status}")
```

## Data Amplification

### Generate Realistic Test Data

```py
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="your_api_key")

# Define your data structure
data = [
    {
        "column_name": "first_name",
        "column_description": "User's first name",
        "column_restriction": "no restrictions",
        "column_values": ["John", "Jane", "Michael", "Emily", "Sarah"]
    },
    {
        "column_name": "email",
        "column_description": "User's email address",
        "column_restriction": "valid email format",
        "column_values": ["john@example.com", "jane@test.com"]
    }
]

# Generate 10 new rows of data
result = client.data_amplifier.amplify(data, data_count=10)

print("Generated data:")
for key, values in result.data.items():
    print(f"{key}: {values}")
```

## API Builder

### Generate API Documentation from Description

```py
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="your_api_key")

swagger_spec = client.api_builder.build(
    email="developer@company.com",
    user_description="Generate APIs for e-commerce platform with user management and product catalog"
)

print("Generated Swagger specification:")
print(f"Title: {swagger_spec['info']['title']}")
print(f"Paths: {list(swagger_spec['paths'].keys())}")
```

## API Assertions

### Generate Header Assertions

```py
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="your_api_key")


assertions = client.api_assertions.headers.create(headers=headers)

for assertion in assertions:
    print(f"Assert {assertion['assertHeaderKey']}: {assertion['assertHeaderValue']}")
```

### Generate JSON Body Assertions

```py
response_data = {
    "status": "success",
    "data": {
        "user_id": 123,
        "username": "john_doe",
        "email": "john@example.com"
    },
    "message": "User retrieved successfully"
}

assertions = client.api_assertions.jsonbody.create(response=response_data)

for assertion in assertions:
    print(f"Assert contains: {assertion['value']} - {assertion['assertionDescription']}")
```

### Generate JSON Path Assertions

```py
jsonpath_assertions = client.api_assertions.jsonpath.create(response=response_data)

for assertion in jsonpath_assertions:
    print(f"JSONPath: {assertion['jsonPath']} == {assertion['jsonPathValue']}")
```

### Generate JSON Schema Assertions

```py
schema = client.api_assertions.jsonschema.create(response=response_data)

print("Generated JSON Schema:")
print(schema)
```

## Vision Nova

### Generate Tests from UI Images

```py
from qyrusai import SyncQyrusAI

client = SyncQyrusAI(api_key="your_api_key")

# Generate functional tests from image URL
image_url = "https://example.com/login-page-screenshot.jpg"
test_scenarios = client.vision_nova.generate_test.generate(image_url)

print(f"Generated {len(test_scenarios.scenarios)} test scenarios from image:")
for scenario in test_scenarios.scenarios:
    print(f"- {scenario['scenario_name']}: {scenario['objective']}")
    print(f"  Steps: {len(scenario['steps'])} steps")
```

### Verify UI Accessibility

```py
# Verify accessibility compliance of UI design
accessibility_report = client.vision_nova.verify_accessibility.verify(image_url)

print("Accessibility Report:")
for item in accessibility_report.visual_accessibility:
    print(f"- {item['accessibility_type']}: {item['accessibility_comment']}")
```

## LLM Evaluator

### Initialize LLM Evaluator

```py
from qyrusai import AsyncQyrusAI
from qyrusai._types import RAGRequest, MCPRequest

client = AsyncQyrusAI(api_key="your_api_key")
evaluator = client.llm_evaluator.evaluator
```

### Evaluate RAG (Retrieval-Augmented Generation) Systems

```py
# Basic RAG evaluation
rag_request = RAGRequest(
    app_name="customer_support_rag",
    qid="test_001",
    question="How do I reset my password?",
    answer="Click 'Forgot Password' on the sign-in page. The reset link expires in 24 hours.",
    retrieved=[
        {
            "doc_id": "kb-12",
            "text": "To reset your password, click 'Forgot Password' on the sign-in page. An email link is valid for 24 hours.",
            "score": 0.89
        }
    ],
    citations=[0],
    params={"model": "gpt-4o-mini", "temperature": 0.2}
)

# Evaluate the RAG system
result = await evaluator.evaluate_rag(rag_request)
print(f"Status: {result['status']}")
print(f"Faithfulness: {result['metrics']['faithfulness']}")
print(f"Relevance: {result['metrics']['relevance']}")
```

### Evaluate MCP (Model Context Protocol) Tool-Calling Systems

```py
# Basic MCP evaluation
mcp_request = MCPRequest(
    app_name="customer_support_mcp",
    qid="test_002",
    question="What's my order status?",
    answer="Your order ABC-123 has shipped and will arrive tomorrow.",
    tools=[
        {
            "name": "orders.getStatus",
            "args": {"order_id": "ABC-123"},
            "args_valid": True,
            "status": "ok",
            "latency_ms": 150,
            "result_text": "Order ABC-123 status: shipped, estimated delivery: tomorrow"
        }
    ]
)

# Evaluate the MCP system
result = await evaluator.evaluate_mcp(mcp_request)
print(f"Status: {result['status']}")
print(f"Tool Selection Quality: {result['metrics']['tool_selection_quality']}")
print(f"Args Valid Rate: {result['metrics']['args_valid_rate']}")
```

### Batch Evaluation

```py
# Evaluate multiple requests at once
requests = [rag_request, mcp_request]

batch_result = await evaluator.evaluate_batch(requests)
print(f"Total: {batch_result['total']}")
print(f"Successful: {batch_result['successful']}")
print(f"Failed: {batch_result['failed']}")

for result in batch_result['results']:
    print(f"- {result['qid']}: {result['status']}")
```

### Using JSON Input (Alternative to Pydantic)

```py
# You can also use plain dictionaries instead of Pydantic models
rag_dict = {
    "app_name": "customer_support_rag",
    "qid": "test_003",
    "question": "What are the pricing plans?",
    "answer": "We offer Basic ($10/month) and Premium ($25/month) plans.",
    "retrieved": [
        {
            "doc_id": "pricing-1",
            "text": "Basic plan costs $10/month. Premium plan costs $25/month.",
            "score": 0.95
        }
    ],
    "citations": [0]
}

# The evaluator automatically validates and converts JSON to Pydantic
result = await evaluator.evaluate_rag(rag_dict)
```

### Legacy Judge Evaluation (Backwards Compatibility)

```py
# Original evaluate method still works
score = await evaluator.evaluate(
    context="User wants to reset password",
    expected_output="Provide reset link instructions",
    executed_output=["Click 'Forgot Password' on login page"],
    guardrails="Always mention link expiration time"
)

print(f"Evaluation score: {score}")
```

### Synchronous Usage

```py
from qyrusai import SyncQyrusAI

# All methods are available in synchronous versions
client = SyncQyrusAI(api_key="your_api_key")
evaluator = client.llm_evaluator.evaluator

# Synchronous RAG evaluation
result = evaluator.evaluate_rag(rag_request)

# Synchronous batch evaluation
batch_result = evaluator.evaluate_batch([rag_request, mcp_request])
```

### Advanced MCP with Schema Validation

```py
# MCP with automatic argument validation
mcp_with_schema = MCPRequest(
    app_name="advanced_mcp_app",
    qid="test_004",
    question="Search for customer orders",
    answer="Found 5 orders for customer John Doe.",
    tool_schemas={
        "database.query": {
            "type": "object",
            "properties": {
                "sql": {"type": "string"},
                "timeout": {"type": "number", "minimum": 1}
            },
            "required": ["sql"]
        }
    },
    tools=[
        {
            "name": "database.query",
            "args": {"sql": "SELECT * FROM orders WHERE customer_name='John Doe'"},
            # args_valid will be automatically computed from schema
            "status": "ok",
            "latency_ms": 245,
            "result_text": "Found 5 orders"
        }
    ]
)

result = await evaluator.evaluate_mcp(mcp_with_schema)
```

## Complete Example

```py
import os
import asyncio
from qyrusai import AsyncQyrusAI
from qyrusai._types import RAGRequest, MCPRequest

async def main():
    # Initialize client
    client = AsyncQyrusAI(api_key=os.getenv("QYRUS_API_KEY"))

    # Generate test scenarios from JIRA
    scenarios = await client.nova.from_description.create(
        "Create tests for user registration form"
    )
    print(f"Generated {len(scenarios.scenarios)} test scenarios")

    # Generate test data
    data_schema = [{
        "column_name": "username",
        "column_description": "unique username",
        "column_restriction": "alphanumeric only",
        "column_values": ["user1", "testuser", "admin"]
    }]

    test_data = client.data_amplifier.amplify(data_schema, data_count=5)
    print(f"Generated test data: {test_data.data}")

    # Build API documentation
    api_spec = client.api_builder.build(
        email="dev@company.com",
        user_description="User management API with registration and authentication"
    )
    print(f"Generated API with {len(api_spec['paths'])} endpoints")

    # Evaluate RAG system
    rag_evaluation = await client.llm_evaluator.evaluator.evaluate_rag({
        "app_name": "help_desk_rag",
        "qid": "eval_001",
        "question": "How to reset password?",
        "answer": "Use the forgot password link",
        "retrieved": [{"doc_id": "kb1", "text": "Click forgot password link", "score": 0.9}],
        "citations": [0]
    })
    print(f"RAG Status: {rag_evaluation['status']}")

if __name__ == "__main__":
    asyncio.run(main())
```

> **Note**: Both Asynchronous and Synchronous interactions are available. Replace `AsyncQyrusAI` with `SyncQyrusAI` and remove `await` for synchronous usage.

> **Note**: Store your API key securely using environment variables. Get your API key from the Qyrus platform.
