# opensearch-algorithm

Part of **OPENSEARCH**

# OpenSearch Algorithm Management

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|----------------|--------------|-------------|
| List Function Resources | Synchronous | Lists algorithm resources in an OpenSearch application group, including details about feature generators and raw files. The API supports filtering by resource type and pagination. |
| Get Deployed Model Details | Synchronous | Describes the data structure of an algorithm model deployed in an OpenSearch application, including fields such as model name, ID, progress, status, project ID, and algorithm type. |
| Get Deployed Algorithm Details | Synchronous | Describes the data structure of a deployed algorithm in an OpenSearch application, including its deployment status, associated models, and operational scenario. |
| Get Deployed Model Status | Synchronous | Describes the data structure of a deployed algorithm model in an OpenSearch application, including fields such as model name, ID, deployment progress, status, project ID, and algorithm type. |

## API Calling Patterns

### Authentication
Use **Bearer Token** authentication as the primary method.

- Include the header: `Authorization: Bearer <your_api_key>`
- Store your API key in the environment variable: `DASHSCOPE_API_KEY`
- Example: `export DASHSCOPE_API_KEY=sk-xxxxxx`

While some endpoints may support other auth methods (e.g., Alibaba Cloud AccessKey), bearer token is recommended for simplicity and consistency across OpenSearch algorithm APIs.

### Service Endpoint
The base URL for algorithm management APIs is:

`https://api.aliyun.com/v4/openapi`

This is a global endpoint (not region-specific). All requests use this base URL regardless of your OpenSearch instance region.

### Synchronous API Pattern
All functions in this domain use the **Synchronous** calling pattern:

1. Send a single HTTP request (GET or POST) to the endpoint
2. Receive a complete JSON response immediately
3. Parse the response body for results or error details
4. No polling or streaming is required

For example, listing function resources returns all matching items (paginated) in one response. Similarly, fetching model or algorithm details returns the full object in a single call.

## Parameter Reference

### List Function Resources

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| appGroupIdentity | string | Yes | — | — | The application ID. |
| functionName | string | Yes | — | — | The function name. |
| resourceType | string | No | — | One of: feature_generator, raw_file | The resource type. |
| output | string | No | detail | One of: detail | The output level. |
| pageNumber | integer | No | 1 | — | The page number. |
| pageSize | integer | No | 10 | — | The page size. |

### Get Deployed Model Status

| Parameter | Type | Required | Default | Constraints | Description |
|----------|------|----------|---------|-------------|-------------|
| modelName | string | No | — | — | The name of the model. |
| modelId | integer | No | — | — | The ID of the model. |
| progress | integer | No | — | — | The prediction status, in percentage. |
| status | string | No | — | — | The deployment status. For valid values, see the status field in DeployedAlgorithm. |
| projectId | integer | No | — | — | The ID of the algorithm project. |
| algorithmType | string | No | — | one of: POP, CP | The algorithm type. Valid values: POP (popularity model) and CP (category prediction model). |

> **Note**: The "Get Deployed Model Details" and "Get Deployed Algorithm Details" functions do not accept input parameters—they return static data structures describing deployed entities.

## Code Examples

### List Function Resources - curl - all regions

```bash
curl -X GET 'https://api.aliyun.com/v4/openapi/app-groups/{appGroupIdentity}/functions/{functionName}/resources?resourceType=feature_generator&output=detail&pageNumber=1&pageSize=10' \
-H 'Authorization: Bearer $DASHSCOPE_API_KEY'
```

### Get Deployed Algorithm Details - Python - all regions

```python
import requests
import os

api_key = os.getenv("DASHSCOPE_API_KEY")
headers = {"Authorization": f"Bearer {api_key}"}

# Note: Actual endpoint for retrieving deployed algorithm details is typically part of a larger API path.
# Based on documentation, this is a data structure reference; real usage would involve a specific GET endpoint.
# Example assumes a hypothetical endpoint consistent with OpenSearch patterns.
response = requests.get(
    "https://api.aliyun.com/v4/openapi/app-groups/my_app/algorithms/281",
    headers=headers
)

if response.status_code == 200:
    algorithm = response.json()
    print(f"Algorithm ID: {algorithm['id']}")
    print(f"Status: {algorithm['status']}")
    print(f"Scene: {algorithm['scene']}")
else:
    print(f"Error: {response.status_code} - {response.text}")
```

### Get Deployed Model Details - Java - all regions

```java
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.URI;

public class OpenSearchModelDetails {
    public static void main(String[] args) throws Exception {
        String apiKey = System.getenv("DASHSCOPE_API_KEY");
        HttpClient client = HttpClient.newHttpClient();
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("https://api.aliyun.com/v4/openapi/app-groups/my_app/models/363"))
            .header("Authorization", "Bearer " + apiKey)
            .GET()
            .build();
            
        HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
        
        if (response.statusCode() == 200) {
            System.out.println("Model details: " + response.body());
        } else {
            System.out.println("Error: " + response.statusCode() + " - " + response.body());
        }
    }
}
```

### Check Model Status via Console Navigation - text - all regions

```text
To view deployed model status via the Alibaba Cloud Console:

1. Go to https://opensearch.console.aliyun.com
2. In the left navigation panel, click "Deployed Models"
3. In the main content area, click on a specific model name to view its details

Prerequisites:
- An OpenSearch application must be created
- The algorithm model must have been successfully deployed
```

## Response Format

```json
{
  "Status": "OK",
  "HttpCode": 200,
  "TotalCount": 2,
  "RequestId": "\"3A809095-C554-5CF5-8FCE-BE19D4673790\"",
  "Message": "Invalid resource name.",
  "Code": "Resource.InvalidResourceName",
  "Result": [
    {
      "CreateTime": 1234,
      "Data": {
        "Content": "\"abc\"",
        "Generators": [
          {
            "Generator": "combo",
            "Input": {
              "Features": [
                {
                  "Name": "system_item_id",
                  "Type": "item"
                }
              ]
            },
            "Output": "feature1"
          }
        ]
      },
      "Description": "resource description",
      "FunctionName": "rank",
      "ModifyTime": 1234,
      "ReferencedInstances": [
        "rank_model1"
      ],
      "ResourceName": "fg_json",
      "ResourceType": "feature_generator"
    }
  ],
  "Latency": 123
}
```

**Key Fields**:
- `Status` — Overall request status (e.g., "OK" or error)
- `HttpCode` — HTTP status code of the response
- `TotalCount` — Total number of resources matching the query
- `RequestId` — Unique identifier for troubleshooting
- `Code` — Error code if the request failed
- `Result[].ResourceName` — Name of the algorithm resource
- `Result[].ResourceType` — Type of resource (e.g., feature_generator)
- `Result[].FunctionName` — Associated function name
- `Result[].Status` — Deployment status (e.g., "IN_SERVICE")
- `Result[].Progress` — Deployment completion percentage (0–100)

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|-------------------|----------------------------|----------------------------------------|
| Resource.InvalidResourceName | The specified resource name is invalid. Check the resource name format and ensure it meets the requirements. | Verify that the resource name follows OpenSearch naming conventions (alphanumeric, underscores, no spaces). |

## Pricing & Billing

### Billing Model
Billing occurs per request; async tasks are billed upon completion.

### Price Reference

| Tier | Input Price | Output Price |
|------|-------------|--------------|
| default | 0.001 / | 0.001 / |
| default | 0.001 / | 0.002 / |

> **Note**: Pricing varies slightly between functions. The first row applies to "List Function Resources"; the second applies to model-related operations.

### Free Tier
Monthly free quota of 500 requests for model-related operations. No free tier for resource listing.

### Usage Limits
Model-related APIs are limited to 100 QPS. No explicit limits for other operations.

### Billing Notes
- Billed per request, regardless of input/output size
- Free tier applies only to model detail/status queries
- All charges are in Chinese Yuan (CNY)

## FAQ

Q: How do I authenticate my OpenSearch algorithm API requests?
A: Use a bearer token in the `Authorization` header: `Authorization: Bearer $DASHSCOPE_API_KEY`. Set your API key in the `DASHSCOPE_API_KEY` environment variable.

Q: Are these APIs region-specific?
A: No. All algorithm management APIs use the global endpoint `https://api.aliyun.com/v4/openapi`, regardless of your OpenSearch instance region.

Q: What does "IN_SERVICE" status mean for a deployed model?
A: It indicates the model has been successfully deployed and is actively serving traffic in your OpenSearch application.

Q: Can I filter resources by type when listing function resources?
A: Yes. Use the `resourceType` parameter with values `feature_generator` or `raw_file` to filter results.

Q: Why am I getting "Invalid resource name" errors?
A: Ensure your resource name contains only valid characters (letters, digits, underscores) and matches the exact name used during deployment. Avoid spaces or special characters.