Summary generation

Updated at:

This topic describes the syntax and examples of the Tongyi ZoneWit API for summary generation.

Request syntax

POST /zhiwen-chat/summary HTTP/1.1

Request parameters

Name

Type

Required

Description

Example

capabilityType

string

Yes

The capability type.

Summary generation:

SUMMARY_GEN

SUMMARY_GEN

userPrompt

string

Yes

The prompt.

You are an AI assistant that specializes in Named Entity Recognition (NER). Your task is to accurately extract all person names, place names, and organization names from the given text and organize them in the specified dictionary format.

fileIdList

array

Yes

A list of document IDs.

[

"file_zhiwen_XXX"

]

stream

boolean

Yes

Specifies whether to return the response in a streaming format.

true

Response parameters

Name

Type

Description

output

object

-choices

array

-finishReason

string

Termination Reason

-message

object

The message body.

-role

string

The role.

-content

string

The message content.

requestId

string

The request ID.

usage

object

The token usage information.

-inputTokens

int

The number of input tokens.

-outputTokens

int

The number of output tokens.

-totalTokens

int

The total number of tokens.

Examples

Call examples

import os
import requests

'''
API name: Summary generation
API path: https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/summary
Environment requirements: Python >= 3.7
'''

url = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/summary"
request_headers = {
    "Authorization": os.environ.get("DASHSCOPE_API_KEY"),  # If you have not configured the environment variable, replace your API key here.
    "Content-Type": "application/json"
}
# Summary generation: SUMMARY_GEN
request_body = {
    "capabilityType": "SUMMARY_GEN",
    "userPrompt": "What are these documents about? Summarize them in Markdown format.",
    "stream": True,
    "fileIdList": [
        "file_zhiwen_XXX"  # Replace this with your document ID.
    ]
}

with requests.post(url, json=request_body, headers=request_headers) as response:
    if request_body["stream"]:
        for line in response.iter_lines():
            if line:
                line = line.decode('utf-8')
                if line.startswith('data:'):
                    print("Received:", line[5:].strip())
    else:
        print("Received:", response.json())
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * API name: Summary generation
 * API path: https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/summary
 * Environment requirements: Java 8 or later
 */
public class SummaryDemo {
    // Step 1. API address and configuration
    private static final String API_KEY = System.getenv("DASHSCOPE_API_KEY");   // Enter the API key from the Alibaba Cloud Model Studio platform.
    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v2/apps/zhiwen-chat/summary";
    private static final String CHARSET = "UTF-8";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    public static void main(String[] args) throws IOException, InterruptedException {
        // Step 2. Parameter settings
        // The fileId field returned by the document upload API. The format is file_zhiwen_XXX.
        String fileId = "file_zhiwen_XXX";
        // Custom prompt: You can modify this as needed. For examples, see the Test page of the Tongyi ZoneWit light application.
        String userPrompt = "What are these documents about? Summarize them in Markdown format.";
        // Streaming mode: This example uses streaming output. You can configure this as needed.
        boolean isStreaming = true;

        // Step 3. Build the request body
        Map<String, Object> requestBodyMap = new HashMap<>();
        requestBodyMap.put("capabilityType", "SUMMARY_GEN");
        requestBodyMap.put("userPrompt", userPrompt);
        requestBodyMap.put("stream", isStreaming);
        requestBodyMap.put("fileIdList", new String[]{fileId});
        String requestBody = objectMapper.writeValueAsString(requestBodyMap);

        // Step 4. Configure the request timeout period
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30 * 1000).build();

        // Step 5. Execute the request. Choose between a streaming or non-streaming request as needed.
        try (CloseableHttpClient httpClient = HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .build()) {

            // Construct an HTTP POST request
            HttpPost httpPost = new HttpPost(API_URL);
            buildRequestHeaders(httpPost, requestBody);

            // Execute the request. This example uses streaming output. You can configure the stream parameter as needed.
            buildStreamingRequest(httpClient, httpPost); // Streaming request
            // buildNonStreamingRequest(httpClient, httpPost); // Non-streaming request
        }
    }

    /**
     * Build common request headers
     *
     * @param httpPost HTTP request object
     * @param requestBody request body string
     */
    private static void buildRequestHeaders(HttpPost httpPost, String requestBody) {
        httpPost.setHeader("Authorization", API_KEY);
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(requestBody, CHARSET));
    }

    /**
     * Build a streaming request
     * @param client HTTP client
     * @param httpPost HTTP request object
     * @return asynchronous CompletableFuture object
     */
    private static void buildStreamingRequest(CloseableHttpClient client, HttpPost httpPost) {
        System.out.println("Streaming request:");
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 && entity != null) {
                try (InputStream inputStream = entity.getContent();
                     BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
                    String line;
                    while ((line = reader.readLine()) != null) {
                        if (line.startsWith("data:")) {
                            String json = line.substring(5).trim();
                            System.out.println(json);
                        }
                    }
                }
            } else {
                String errorBody = EntityUtils.toString(response.getEntity());
                System.err.println("Request failed: " + errorBody);
            }
        } catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * Build a non-streaming request
     * @param client HTTP client
     * @param httpPost HTTP request object
     * @throws IOException when a network request or data read error occurs
     */
    private static void buildNonStreamingRequest(CloseableHttpClient client, HttpPost httpPost) throws IOException {
        System.out.println("Non-streaming request:");
        try (CloseableHttpResponse response = client.execute(httpPost)) {
            HttpEntity entity = response.getEntity();
            if (entity == null) {
                System.err.println("The response body is empty");
                return;
            }
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200 && entity != null){
                String responseBody = EntityUtils.toString(entity);
                System.out.println(responseBody);
            }else{
                String errorBody = EntityUtils.toString(entity);
                System.err.println("Request failed: " + errorBody);
            }
        }catch (IOException e) {
            System.err.println("Request failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Successful response example

JSON format

{
  "output": {
    "choices": [{
      "finishReason": "stop",
      "message": {
        "role": "assistant",
        "content": "Summary of the document 'XXX.pdf': The generated summary result."
      }
    }]
  },
  "requestId": "1e016036-ac87-9afa-b603-7443f9d4e093",
  "usage": {
    "inputTokens": 100,
    "outputTokens": 100,
    "totalTokens": 200
  }
}

Error codes

For more information, see Error codes for Tongyi ZoneWit.