> ## Documentation Index
> Fetch the complete documentation index at: https://docs.morphllm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Report API

> Report failed or problematic completions to improve Morph model quality

## Overview

Report failed or problematic completions to help improve Morph's quality. This endpoint allows you to flag completions that produced incorrect, malformed, or problematic code so our team can investigate and improve the models.

**When to use this endpoint:**

* Generated code has syntax errors
* Applied changes broke existing functionality
* Model output doesn't match the intended instruction
* Generated code produces runtime errors or exceptions
* Code quality issues (security vulnerabilities, bad practices)

The completion ID can be found in the response headers (`x-completion-id`) or server logs from your original apply request.

## Request Body

<ParamField body="completion_id" type="string" required>
  The completion ID from the original request (found in response headers or logs)
</ParamField>

<ParamField body="failure_reason" type="string" required>
  Description of what went wrong (Error message, traceback, etc.)
</ParamField>

<ParamField body="user_query" type="string" optional>
  The original user instruction that led to the problematic completion. This helps provide context for debugging and improving the model. Maximum 2000 characters.
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Whether the report was successfully recorded
</ResponseField>

<ResponseField name="message" type="string">
  Confirmation message
</ResponseField>

<ResponseField name="data" type="object">
  <Expandable title="data">
    <ResponseField name="request_log_id" type="string">
      Internal ID of the reported request
    </ResponseField>

    <ResponseField name="reported_at" type="string">
      ISO timestamp when the report was recorded
    </ResponseField>
  </Expandable>
</ResponseField>

## Error Codes

| Status | Description                  |
| ------ | ---------------------------- |
| `200`  | Report successfully recorded |
| `400`  | Invalid request parameters   |
| `401`  | Invalid or missing API key   |
| `404`  | Completion ID not found      |
| `409`  | Request already reported     |

## Examples

### cURL

```bash theme={null}
curl -X POST "https://morphllm.com/api/report" \
  -H "Authorization: Bearer your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "completion_id": "chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d",
    "failure_reason": "Generated code had syntax errors: SyntaxError: Unexpected token in JSON",
    "user_query": "Add error handling to the user login function"
  }'
```

### JavaScript (fetch)

```javascript theme={null}
const reportFailure = async (completionId, failureReason, userQuery = null) => {
  const payload = {
    completion_id: completionId,
    failure_reason: failureReason,
  };
  
  // Include user_query only if provided
  if (userQuery) {
    payload.user_query = userQuery;
  }
  
  const response = await fetch('https://morphllm.com/api/report', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer your-api-key',
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(payload),
  });

  if (!response.ok) {
    throw new Error(`HTTP error! status: ${response.status}`);
  }

  return await response.json();
};

// Usage with user query
try {
  const result = await reportFailure(
    'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
    'Generated code produces runtime error: TypeError: Cannot read property',
    'Add validation to user input fields'
  );
  console.log('Report submitted:', result);
} catch (error) {
  console.error('Failed to submit report:', error);
}

// Usage without user query
try {
  const result = await reportFailure(
    'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
    'Generated code produces runtime error: TypeError: Cannot read property'
  );
  console.log('Report submitted:', result);
} catch (error) {
  console.error('Failed to submit report:', error);
}
```

### Python (requests)

```python theme={null}
import requests
import json

def report_failure(completion_id, failure_reason, api_key, user_query=None):
    url = "https://morphllm.com/api/report"
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Content-Type": "application/json"
    }
    payload = {
        "completion_id": completion_id,
        "failure_reason": failure_reason
    }
    
    # Include user_query only if provided
    if user_query:
        payload["user_query"] = user_query
    
    try:
        response = requests.post(url, headers=headers, json=payload)
        response.raise_for_status()  # Raises an HTTPError for bad responses
        return response.json()
    except requests.exceptions.RequestException as e:
        print(f"Error submitting report: {e}")
        return None

# Usage with user query
api_key = "your-api-key"
completion_id = "chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d"
failure_reason = """
Traceback (most recent call last):
  File "generated_code.py", line 10, in <module>
    result = process_data(invalid_input)
  File "generated_code.py", line 5, in process_data
    return data.split('.')
AttributeError: 'NoneType' object has no attribute 'split'
"""
user_query = "Refactor the data processing function to handle null values"

result = report_failure(completion_id, failure_reason, api_key, user_query)
if result:
    print(f"Report submitted successfully: {result}")

# Usage without user query  
result = report_failure(completion_id, failure_reason, api_key)
if result:
    print(f"Report submitted successfully: {result}")
```

### Node.js (axios)

```javascript theme={null}
const axios = require('axios');

async function reportFailure(completionId, failureReason, apiKey, userQuery = null) {
  try {
    const payload = {
      completion_id: completionId,
      failure_reason: failureReason,
    };
    
    // Include user_query only if provided
    if (userQuery) {
      payload.user_query = userQuery;
    }

    const response = await axios.post('https://morphllm.com/api/report', payload, {
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });

    return response.data;
  } catch (error) {
    if (error.response) {
      // Server responded with error status
      console.error('Server error:', error.response.data);
      throw new Error(`Server error: ${error.response.status} - ${error.response.data.error?.message}`);
    } else if (error.request) {
      // Request was made but no response received
      console.error('Network error:', error.request);
      throw new Error('Network error: No response received');
    } else {
      // Something else happened
      console.error('Request error:', error.message);
      throw new Error(`Request error: ${error.message}`);
    }
  }
}

// Usage with user query
(async () => {
  try {
    const result = await reportFailure(
      'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
      'Generated code fails unit tests: Expected 5 but got undefined',
      'your-api-key',
      'Add unit tests for the calculate function'
    );
    
    console.log('Success:', result.message);
    console.log('Report ID:', result.data?.request_log_id);
    console.log('Reported at:', result.data?.reported_at);
  } catch (error) {
    console.error('Failed to report:', error.message);
  }
})();

// Usage without user query
(async () => {
  try {
    const result = await reportFailure(
      'chatcmpl-9d9e2fc21c094f4eacbcee0009f2f12d',
      'Generated code fails unit tests: Expected 5 but got undefined',
      'your-api-key'
    );
    
    console.log('Success:', result.message);
    console.log('Report ID:', result.data?.request_log_id);
    console.log('Reported at:', result.data?.reported_at);
  } catch (error) {
    console.error('Failed to report:', error.message);
  }
})();
```

### Response Example

Successful response (200 OK):

```json theme={null}
{
  "success": true,
  "message": "Report successfully recorded",
  "data": {
    "request_log_id": "req_123456789",
    "reported_at": "2024-01-15T10:30:00Z"
  }
}
```

Error response (400 Bad Request):

```json theme={null}
{
  "error": {
    "message": "Missing required parameter: completion_id",
    "type": "invalid_request_error",
    "code": "missing_parameter"
  }
}
```
