# DeepCore API

## Overview

DeepCore API is a powerful set of RESTful API interfaces that provide the ability to interact with the DeepCore platform. These interfaces allow developers to create and manage agents, models, files, tools, prompts, categories, and other resources.

### Base URL

All API requests are based on the following base URL:

```
https://api.deepcore.top
```

### Authentication

DeepCore API uses API Token authentication, which is simple to implement and suitable for both development and production environments.

#### API Token Authentication

API Token is a long-term authentication credential used to access DeepCore APIs. It simplifies the authentication process and is recommended for all integration scenarios.

**Obtaining an API Token**

You can obtain an API Token from one of the following sources:

1. **DeepCore Official Website**: Log in to [deepcore.top](https://deepcore.top/) and navigate to your profile settings to find your API Token.
2. **API Token Endpoint**: If you already have account credentials, you can use the following endpoint to obtain an API Token:

```
POST /api/open/token
```

**Using API Token**

After obtaining an API Token, include it in the `X-API-Token` request header for all API calls:

```
import requests
​
# Use API Token to call interfaces
headers = {"X-API-Token": "tk_your_api_token"}  # Replace with your API Token
​
# For example, get the list of agents
response = requests.get(
    "https://api.deepcore.top/api/agents",
    headers=headers
)
​
print(response.json())
```

**API Token Format**

API Tokens follow a specific format: `tk_` followed by a 20-character string. For example:

```
tk_a1b2c3d4e5f6g7h8i9j0
```

**Resetting API Token**

If your API Token is compromised or you need to reset it for security reasons, you can use the reset endpoint:

```
POST /api/open/token/reset
```

Note: Resetting your API Token will invalidate the previous token.

### Open Dialogue API

The Open Dialogue API is a mechanism provided by DeepCore that allows third-party applications to integrate agent dialogue functionality in a simplified way.

#### Interface Definition

```
POST /api/open/agents/{agent_id}/dialogue
```

#### Authentication Method

Uses API Token authentication via the `X-API-Token` request header.

#### Request Parameters

| Parameter         | Type   | Required | Description                                                                                                                                                              |
| ----------------- | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `message`         | string | Yes      | User message content                                                                                                                                                     |
| `conversation_id` | string | No       | Conversation ID, used to continue an existing conversation. Developers are recommended to define and pass their own conversation ID for tracking and management purposes |

#### Example Request

```
# Use API Token for dialogue (supports streaming response)
curl -X POST https://api.deepcore.top/api/open/agents/your_agent_id/dialogue \
  -H "Content-Type: application/json" \
  -H "X-API-Token: tk_your_api_token" \
  -d '{
    "message": "Hello, please introduce yourself",
    "conversation_id": "your-custom-conversation-id"
  }'
​
# Response will be returned in Server-Sent Events format
```

#### Response Format

The interface returns Server-Sent Events (SSE) format streaming responses. Each event is prefixed with `event:` and `data:`, and comes in two main types:

1. **Status events**: Indicate the current status of the request processing
2. **Message events**: Contain actual response content, usually in small chunks

**Example Response**

```
event: status
data: {"message": "task understanding"}
​
event: status
data: {"message": "generate response"}
​
event: message
data: {"type": "markdown", "text": "H"}
​
event: message
data: {"type": "markdown", "text": "e"}
​
event: message
data: {"type": "markdown", "text": "l"}
​
event: message
data: {"type": "markdown", "text": "l"}
​
event: message
data: {"type": "markdown", "text": "o"}
​
event: message
data: {"type": "markdown", "text": "!"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "H"}
​
event: message
data: {"type": "markdown", "text": "o"}
​
event: message
data: {"type": "markdown", "text": "w"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "c"}
​
event: message
data: {"type": "markdown", "text": "a"}
​
event: message
data: {"type": "markdown", "text": "n"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "I"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "a"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "i"}
​
event: message
data: {"type": "markdown", "text": "s"}
​
event: message
data: {"type": "markdown", "text": "t"}
​
event: message
data: {"type": "markdown", "text": " "}
​
event: message
data: {"type": "markdown", "text": "you today?"}
```

#### Usage Example (Python)

```
import requests
​
# Using API Token
token = "tk_your_api_token"
agent_id = "your_agent_id"
​
# Send request and handle streaming response
response = requests.post(
    f"https://api.deepcore.top/api/open/agents/{agent_id}/dialogue",
    headers={
        "X-API-Token": token
    },
    json={
        "message": "Hello, please introduce yourself",
        "conversation_id": "your-custom-conversation-id"  # Custom conversation ID
    },
    stream=True  # Enable streaming
)
​
# Handle streaming response
for chunk in response.iter_lines():
    if chunk:
        data = chunk.decode('utf-8')
        if data.startswith('data: '):
            # Remove 'data: ' prefix
            content = data[6:]
            print(content)
```

#### Usage Example (JavaScript)

```
// Using API Token for dialogue
const token = "tk_your_api_token";
const agentId = "your_agent_id";
​
fetch(`https://api.deepcore.top/api/open/agents/${agentId}/dialogue`, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'X-API-Token': token
  },
  body: JSON.stringify({
    message: "Hello, please introduce yourself",
    conversation_id: "your-custom-conversation-id"  // Custom conversation ID
  })
})
.then(response => {
  // Create stream reader
  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = '';
  
  function read() {
    return reader.read().then(({ done, value }) => {
      if (done) return;
      
      // Decode received data
      const chunk = decoder.decode(value, { stream: true });
      buffer += chunk;
      
      // Process complete lines
      const lines = buffer.split('\n');
      buffer = lines.pop(); // Keep the last potentially incomplete line
      
      // Process each line of data
      for (const line of lines) {
        if (line.startsWith('data: ')) {
          // Remove 'data: ' prefix
          const content = line.substring(6);
          console.log(content);
        }
      }
      
      // Continue reading
      return read();
    });
  }
  
  return read();
})
.catch(error => {
  console.error('Dialogue error:', error);
});
```

### API Routes

#### Authentication API

| Path                    | Method | Description     |
| ----------------------- | ------ | --------------- |
| `/api/open/token`       | POST   | Get API Token   |
| `/api/open/token/reset` | POST   | Reset API Token |

#### Agent API

| Path                          | Method | Description                |
| ----------------------------- | ------ | -------------------------- |
| `/api/agents`                 | GET    | Get list of all agents     |
| `/api/agents`                 | POST   | Create new agent           |
| `/api/agents/{agent_id}`      | GET    | Get specific agent details |
| `/api/agents/{agent_id}`      | PUT    | Update specific agent      |
| `/api/agents/{agent_id}`      | DELETE | Delete specific agent      |
| `/api/agents/{agent_id}/chat` | POST   | Chat with an agent         |

#### Open Dialogue API

| Path                                   | Method | Description                                                 |
| -------------------------------------- | ------ | ----------------------------------------------------------- |
| `/api/open/agents/{agent_id}/dialogue` | POST   | Open agent dialogue interface, supports streaming responses |
| `/api/open/examples`                   | GET    | Get API usage example code                                  |

#### Model API

| Path                     | Method | Description                |
| ------------------------ | ------ | -------------------------- |
| `/api/models`            | GET    | Get list of all models     |
| `/api/models`            | POST   | Add new model              |
| `/api/models/{model_id}` | GET    | Get specific model details |
| `/api/models/{model_id}` | PUT    | Update specific model      |
| `/api/models/{model_id}` | DELETE | Delete specific model      |

#### File API

| Path                            | Method | Description               |
| ------------------------------- | ------ | ------------------------- |
| `/api/files`                    | GET    | Get list of all files     |
| `/api/files`                    | POST   | Upload new file           |
| `/api/files/{file_id}`          | GET    | Get specific file details |
| `/api/files/{file_id}`          | DELETE | Delete specific file      |
| `/api/files/{file_id}/download` | GET    | Download specific file    |

#### Tool API

| Path                   | Method | Description               |
| ---------------------- | ------ | ------------------------- |
| `/api/tools`           | GET    | Get list of all tools     |
| `/api/tools`           | POST   | Create new tool           |
| `/api/tools/{tool_id}` | GET    | Get specific tool details |
| `/api/tools/{tool_id}` | PUT    | Update specific tool      |
| `/api/tools/{tool_id}` | DELETE | Delete specific tool      |

#### Prompt API

| Path                       | Method | Description                 |
| -------------------------- | ------ | --------------------------- |
| `/api/prompts`             | GET    | Get list of all prompts     |
| `/api/prompts`             | POST   | Create new prompt           |
| `/api/prompts/{prompt_id}` | GET    | Get specific prompt details |
| `/api/prompts/{prompt_id}` | PUT    | Update specific prompt      |
| `/api/prompts/{prompt_id}` | DELETE | Delete specific prompt      |

#### Category API

| Path                            | Method | Description                   |
| ------------------------------- | ------ | ----------------------------- |
| `/api/categories`               | GET    | Get list of all categories    |
| `/api/categories`               | POST   | Create new category           |
| `/api/categories/{category_id}` | GET    | Get specific category details |
| `/api/categories/{category_id}` | PUT    | Update specific category      |
| `/api/categories/{category_id}` | DELETE | Delete specific category      |

#### Image API

| Path                  | Method | Description                  |
| --------------------- | ------ | ---------------------------- |
| `/api/images`         | POST   | Generate image               |
| `/api/images/history` | GET    | Get image generation history |

#### Open API

| Path               | Method | Description                            |
| ------------------ | ------ | -------------------------------------- |
| `/api/open/chat`   | POST   | Open chat interface                    |
| `/api/open/agents` | GET    | Get list of publicly accessible agents |

#### MCP API

| Path                            | Method   | Description                            |
| ------------------------------- | -------- | -------------------------------------- |
| `/api/mcp/create`               | POST     | Create new MCP server                  |
| `/api/mcp/list`                 | GET      | List all MCP servers                   |
| `/api/mcp/{mcp_name}`           | DELETE   | Delete specified MCP server            |
| `/api/mcp/{mcp_name}/prompts`   | POST     | Add prompt template to MCP server      |
| `/api/mcp/{mcp_name}/resources` | POST     | Add resource to MCP server             |
| `/api/mcp/tools/{tool_id}`      | GET      | Get MCP service information for a tool |
| `/mcp/{mcp_name}`               | GET/POST | MCP server endpoint                    |

### Error Handling

All API responses follow a unified format:

```
{
  "code": 0,        // Error code, 0 indicates success
  "msg": "Success", // Error message
  "data": {}        // Response data
}
```

#### Common Error Codes

| Error Code | Description                  |
| ---------- | ---------------------------- |
| 0          | Success                      |
| 10001      | Invalid token                |
| 10002      | Token expired                |
| 10003      | Invalid username or password |
| 10004      | User not found               |
| 20001      | Resource doesn't exist       |
| 20002      | Resource already exists      |
| 30001      | Parameter error              |
| 40001      | API call error               |
| 50001      | Internal server error        |

### Example Requests

#### Using API Token to Call Interfaces

```
curl -X GET https://api.deepcore.top/api/agents \
  -H "X-API-Token: tk_your_api_token"
```

### Integration and Usage

DeepCore API can be integrated with various programming languages and frameworks, including Python, JavaScript, Java, etc. Requests can be initiated through HTTP client libraries or using our official SDK.

#### Python Example

```
import requests
​
# Use API Token to call APIs
token = "tk_your_api_token"
headers = {"X-API-Token": token}
​
# Get agents list
response = requests.get("https://api.deepcore.top/api/agents", headers=headers)
agents = response.json()["data"]
print(agents)
```

#### JavaScript Example

```
// Use API Token to call APIs
const token = "tk_your_api_token";
​
// Get agents list
fetch("https://api.deepcore.top/api/agents", {
  headers: {
    "X-API-Token": token
  }
})
.then(response => response.json())
.then(data => {
  console.log(data.data);
});
```

### Rate Limits

To ensure service quality, API requests have the following limitations:

* Maximum 60 requests per minute per IP address
* Maximum 120 requests per minute per user
* Maximum 10 chat API requests per minute per user

Exceeding these limits will result in HTTP 429 status code.

### More Information

For more information and detailed documentation about the API, please visit [DeepCore Official Documentation](https://docs.deepcore.top/).


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.deepcore.top/developer-guide/deepcore-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
