로고이미지
TOP
로고이미지 로고이미지

API 개발 가이드

행정문서 QA API

행정문서 QA API 란?

행정문서로 작성된 행정문서의 내용을 이해하여 사용자의 자연어 질문에 올바른 답과 근거를 제공하는 질의응답 API 입니다.
행정문서 QA는 규정/지침, 가이드라인/매뉴얼 등 행정 관련 행정문서의 단락 텍스트 뿐 아니라 테이블 데이터에 대해서도 올바른 답과 근거를 제공합니다.
행정문서 QA API는 HTTP 기반의 REST API 인터페이스로 JSON 포맷 기반의 입력 및 출력을 지원하며 ETRI에서 제공하는 Access Key 인증을 통해 사용할 수 있는 Open API입니다.

KorBERT based office QA

API 호출 1일 허용량

기술명 API명 1일 허용량

알림 사항

1) 행정문서QA API는 한글(hwp, hwpx) 문서에 대해서만 동작합니다.
- 행정문서QA 기술은 특정 행정SW에 국한되지 않으나, 입력 행정문서를 처리 가능한 JSON 구조로 변환하는 기능이 한글 문서에 대해서만 구현되어 있습니다.

2) 입력 문서의 길이가 길 경우 상위 100개 단락 내에서만 질의응답 서비스를 제공합니다.
- 제한된 서버 환경에서 다수 사용자에게 동시에 서비스를 제공하기 위함입나다.

행정문서 QA API 사용하기

행정문서 QA API는 두 가지로 구성되며, 첫번째는 질의응답의 대상이 되는 문서를 등록하는 API이며, 두번째는 질의응답을 하기위한 질문을 입력하는 API입니다. 두 API 모두 HTTP 통신으로 ETRI Open API 서버에 전달하면 됩니다. 서버가 제공하는 REST API의 URI는 다음과 같으며 POST 방식으로 호출해야 합니다.

1. 문서등록
http://aiopen.etri.re.kr:8000/DocUpload

HTTP 요청으로 문서 등록 API를 요청할 때 사전 준비 사항에서 발급받은 Access key 정보를 요청하는 본문에 포함시켜야 합니다. 다음은 HTTP 요청 메시지 예입니다.


  [HTTP Request Header]
  "Authorization" : "YOUR_ACCESS_KEY"
  Content-Type:multipart/form-data; boundary=----[파일 구분자 문자열]

  [HTTP Request Body]
  ------[파일 구분자 문자열]
  Content-Disposition: form-data; name="json"
  {
      "request_id": "reserved field",
      "argument": {"type":"hwp"} 
  }

  ------[파일 구분자 문자열]
  Content-Disposition: form-data; name="doc_file"; filename="[파일 명]"
  Content-Type: [파일 타입]

  [파일의 Byte 문자열]
  ------[파일 구분자 문자열]--
      

위와 같은 HTTP 요청을 ETRI Open API 서버로 전달하면 서버는 JSON 형태의 Text 데이터를 HTTP 응답 메시지로 반환합니다. 다음은 HTTP 응답 예제 입니다.


  [HTTP Response Header]
  Access-Control-Allow-Origin:*
  Connection:close
  Content-Length:0
  Content-Type:application/json; charset=UTF-8

  [HTTP Response Body]
  {
      "request_id": "reserved field",
      "result": 0,
      "return_type": "com.google.gson.internal.LinkedTreeMap",
      "return_object": {문서등록 결과 JSON}
  }

2. 질의응답 REST API

질의응답 REST API는 문서등록 API를 통하여 등록한 문서에 대해 질의응답을 수행하며, 문서를 등록하지 않았을 경우, 데모페이지에 표시된 기본 문서에 대해 질의응답을 수행합니다.

http://aiopen.etri.re.kr:8000/DocQA

HTTP 요청으로 질의응답 API를 요청할 때 사전 준비 사항에서 발급받은 Access key 정보와 문서등록후 리턴 받은 Doc key를 요청하는 본문에 포함시켜야 합니다. 다음은 HTTP 요청 메시지 예입니다.


  [HTTP Request Header]
  "Authorization" : "YOUR_ACCESS_KEY"

  [HTTP Request Body] 
  {
      "request_id": "reserved field",
      "argument": {
          "doc_key": "YOUR_Document_Key",
          "question": "YOUR_QUESTION"
      }
  }

위와 같은 HTTP 요청을 ETRI Open API 서버로 전달하면 서버는 JSON 형태의 Text 데이터를 HTTP 응답 메시지로 반환합니다. 다음은 HTTP 응답 예제 입니다.


  [HTTP Response Header]
  Access-Control-Allow-Origin:*
  Connection:close
  Content-Length:0
  Content-Type:application/json; charset=UTF-8
  
  [HTTP Response Body]
  {
      "request_id": "reserved field",
      "result": 0,
      "return_type": "com.google.gson.internal.LinkedTreeMap",
      "return_object": {질의응답 결과 JSON}
  }

구현 예제

  • JAVA
  • PHP
  • C++
  • Python
  • Node.js

JSON parsing을 위해 Gson 라이브러리를 사용하여 제공하고 있습니다. Gson 라이브러리에 대한 자세한 설명은 https://github.com/google/gson 에서 확인 하실 수 있습니다.


    ////////////////////////// 문서 등록 REST API //////////////////////////
    import com.google.gson.Gson;  
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.UUID;
    
    public class Example {
    
        static public void main ( String[] args ) {
            String openApiURL = "http://aiopen.etri.re.kr:8000/DocUpload";
            String accessKey = "YOUR_ACCESS_KEY";   	// 발급받은 API Key
            Path path = Paths.get("YOUR_FILE");// 전체 경로가 포함된 업로드할 한글 문서 
    
            Gson gson = new Gson();
            Map<String, String> argument = new HashMap<>();
            argument.put("type", "hwp");
    
            Map<String, Object> json = new HashMap<>();
            json.put("argument", argument);
    
            URL url;
            Integer responseCode = null;
            String responBody = null;
            String boundary = null;
            try {
                url = new URL(openApiURL);
                HttpURLConnection con = (HttpURLConnection)url.openConnection();
                boundary = UUID.randomUUID().toString();
                con.setRequestMethod("POST");
                con.setDoOutput(true);
                con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
                con.setRequestProperty("Authorization", accessKey);
                con.setDoInput(true);
    
                con.setUseCaches(false);
                con.setRequestProperty("Connection", "Keep-Alive");
                con.setRequestProperty("Cache-Control", "no-cache");
                con.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
    
                DataOutputStream wr = new DataOutputStream(con.getOutputStream());
                wr.writeBytes("--" + boundary + "\r\n");
                wr.writeBytes("Content-Disposition: form-data; name=\"json\"\r\n\r\n");
                wr.writeBytes(gson.toJson(json) + "\r\n");
    
                wr.writeBytes("--" + boundary + "\r\n");
                wr.writeBytes("Content-Disposition: form-data; name=\"doc_file\"; filename=\"" + path.getFileName() + "\"\r\n\r\n");
                wr.write(Files.readAllBytes(path));
                wr.writeBytes("\r\n");
    
                wr.writeBytes("--" + boundary + "--\r\n");
                wr.flush();
                wr.close();
    
                responseCode = con.getResponseCode();
                InputStream is = con.getInputStream();
                byte[] buffer = new byte[is.available()];
                int byteRead = is.read(buffer);
                responBody = new String(buffer);
    
                System.out.println("[responseCode] " + responseCode);
                System.out.println("[responBody]");
                System.out.println(responBody);
    
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    ////////////////////////// 질의응답 REST API //////////////////////////
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.HashMap;
    import java.util.Map;
    
    import com.google.gson.Gson;
    
    public class Example {
    
        static public void main ( String[] args ) {
          String openApiURL = "http://aiopen.etri.re.kr:8000/DocQA";
          String accessKey = "YOUR_ACCESS_KEY";   	// 발급받은 API Key
          String question = "YOUR_QUESTION";          // 질문 데이터
          String doc_key= "YOUR_DOC_KEY";  
          Gson gson = new Gson();
        
          Map<String, Object> request = new HashMap<>();
          Map<String, String> argument = new HashMap<>();
        
          argument.put("question", question);
          argument.put("doc_key", doc_key);
              
          request.put("argument", argument);
        
        
          URL url;
          Integer responseCode = null;
          String responBody = null;
          try {
              url = new URL(openApiURL);
              HttpURLConnection con = (HttpURLConnection)url.openConnection();
              con.setRequestMethod("POST");
              con.setDoOutput(true);
              con.setRequestProperty("Authorization", accessKey);
        
              DataOutputStream wr = new DataOutputStream(con.getOutputStream());
              wr.write(gson.toJson(request).getBytes("UTF-8"));
              wr.flush();
              wr.close();
        
              responseCode = con.getResponseCode();
              InputStream is = con.getInputStream();
              byte[] buffer = new byte[is.available()];
              int byteRead = is.read(buffer);
              responBody = new String(buffer);
        
              System.out.println("[responseCode] " + responseCode);
              System.out.println("[responBody]");
              System.out.println(responBody);
        
          } catch (MalformedURLException e) {
              e.printStackTrace();
          } catch (IOException e) {
              e.printStackTrace();
          }
        }
    }
//////////////////////////// 문서 등록 REST API
<?php 
	$openApiURL = "http://aiopen.etri.re.kr:8000/DocUpload";
	$accessKey = "YOUR_ACCESS_KEY";
	$filePath = "YOUR_FILE_PATH";
            

	$uploadfile = file_get_contents($filePath);
	$request = array(		
		"argument" => array ("type" => "hwp")
	);

	try {
		$boundary = uniqid();
		$body = '';
		$eol = "\r\n";
		$delimiter = '-------------'.$boundary;
		$body .= "--".$delimiter.$eol
			.'Content-Disposition: form-data; name="json"'.$eol.$eol
			.json_encode($request).$eol;

		$body .= "--".$delimiter.$eol
			.'Content-Disposition: form-data; name="doc_file"; filename="'.basename($filePath).'"' . $eol
			.'Content-Transfer-Encoding: binary'.$eol;

		$body .= $eol;
		$body .= $uploadfile.$eol;

		$body .= "--" . $delimiter . "--".$eol;

		$server_output = "";
		$ch = curl_init();

		$header = array(
                               "Content-Type: multipart/form-data; boundary=" . $delimiter,"Authorization":{$accessKey}
                               "Content-Length: " . strlen($body)
		);

		curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
		curl_setopt($ch, CURLOPT_URL, $openApiURL);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
		curl_setopt($ch, CURLOPT_VERBOSE, true);
		curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $body );

		$server_output = curl_exec ($ch);
		if($server_output === false) {
			echo "Error Number:".curl_errno($ch)."\n";
			echo "Error String:".curl_error($ch)."\n";
		}

		curl_close ($ch);
	} catch ( Exception $e ) {
		echo $e->getMessage ();
	}

	echo "result = " . var_dump($server_output);
?>

//////////////////////////// 질의응답 REST API													
<?php
    $openApiURL = "http://aiopen.etri.re.kr:8000/DocQA";
    $accessKey = "YOUR_ACCESS_KEY";
    $question = "YOUR_QUESTION";
    $doc_key = "YOUR_DOC_KEY";    
    $request = array(      
        "argument" => array (
       	"question" => $question,
       	"doc_key" => $doc_key 
        )
    );
    
    try {
        $server_output = "";
        $ch = curl_init();
        $header = array(
        	"Content-Type:application/json; charset=UTF-8","Authorization":{$accessKey}
        );
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_URL, $openApiURL);
        curl_setopt($ch, CURLOPT_VERBOSE, true);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode ( $request) );
        
        $server_output = curl_exec ($ch);
        if($server_output === false) {
        	echo "Error Number:".curl_errno($ch)."\n";
        	echo "Error String:".curl_error($ch)."\n";
        }
        
        curl_close ($ch);
    } catch ( Exception $e ) {
    	echo $e->getMessage ();
    }
    
    echo "result = " . var_dump($server_output);
?>

JSON parsing을 위해 jsoncpp 라이브러리를 사용하여 제공하고 있습니다. jsoncpp 라이브러리에 대한 자세한 설명은 https://github.com/open-source-parsers/jsoncpp 에서 확인 하실 수 있습니다.

HTTP 통신을 위해 curl 라이브러리를 사용하여 제공하고 있습니다. curl 라이브러리에 대한 자세한 설명은 https://curl.haxx.se/libcurl 에서 확인 하실 수 있습니다.

컴파일을 위해서는 아래와 같이 추가된 LIB에 대한 옵션을 추가해야 합니다.

g++ (c++파일명) (JSONCPP)/json/json.h (JSONCPP)/json/json-forwards.h (JSONCPP)/jsoncpp.cpp -I(CURL)/include -lcurl

//////////////////////////// 문서 등록 REST API
#include <curl/curl.h>
#include <json/json.h>
#include <iostream>
#include <string>
#include <memory.h>
#include <fstream>
#include <math.h>
#include <cstdlib>
#include <filesystem>

using namespace std;
namespace fs = std::filesystem;

size_t writeDataFunc(void *ptr, size_t size, size_t nmemb, string stream);

int main() {
  char* openApiURL = (char*)"http://aiopen.etri.re.kr:8000/DocUpload";
  char* uploadFilePath = (char*)"YOUR_FILE_PATH";
  string accessKey = "YOUR_ACCESS_KEY";

  Json::Value request;
  Json::Value argument;

  argument["type"] = "hwp";	
  request["argument"] = argument;

  CURL *curl;
  curl_slist* responseHeaders = NULL;
  curl = curl_easy_init();

  if( curl == NULL ) {
  } else {
    string body;
    long bodySize = 0L;

    // read file
    ifstream fl(uploadFilePath, ios::binary | ios::ate);
    size_t fileSize = fl.tellg();
    string fileContent(fileSize, '\0');
    fl.seekg(0);
    fl.read(&fileContent[0], fileSize);
    fl.close();

    string CRLF = "\r\n";
    srand((unsigned int)time(NULL));
    string BOUNDARY = std::to_string( rand() );
    string DELIMITER = "-------------" + BOUNDARY;


    body.append("--"+DELIMITER+CRLF);
    body.append("Content-Disposition: form-data; name=\"json\""+CRLF+CRLF);
    body.append(CRLF);
    body.append(request.toStyledString()+CRLF);

    // now we add the file
    string fileName = fs::path(uploadFilePath).filename();
    body.append("--"+DELIMITER+CRLF);
    body.append("Content-Disposition: form-data; name=\"doc_file\"; filename=\""+fileName+"\""+CRLF);
    body.append("Content-Transfer-Encoding: binary"+CRLF+CRLF);

    string bodyEnd = CRLF+"--"+DELIMITER+"--"+CRLF;

    body.append(fileContent);
    body.append(bodyEnd);

    char *bodyChars = &body[0];
    bodySize = strlen(body.c_str()) + fileSize + strlen(bodyEnd.c_str());

    responseHeaders = curl_slist_append(responseHeaders, ("Content-Type: multipart/form-data; boundary="+DELIMITER).c_str());
    responseHeaders = curl_slist_append(responseHeaders, ("Authorization: " + accessKey).c_str() ) ; 
    responseHeaders = curl_slist_append(responseHeaders, ("Content-Length: " + to_string(bodySize)).c_str() ) ;


    long statusCode;
    string response;
    
    curl_easy_setopt(curl, CURLOPT_URL, openApiURL);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, responseHeaders ) ;
    curl_easy_setopt(curl, CURLOPT_POST, 1);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_MAXREDIRS, 10);
    curl_easy_setopt(curl, CURLOPT_VERBOSE, true);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, bodyChars);
    curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, bodySize);

    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeDataFunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    curl_easy_perform(curl);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
    curl_easy_cleanup(curl);
    
    cout << "[responseCode] " << statusCode << endl;
    cout << "[responBody]" << endl;
    cout << response << endl;
  }

  return 0;
}

size_t writeDataFunc(void *ptr, size_t size, size_t nmemb, string stream) {
  size_t realsize = size * nmemb;
  string temp(static_cast<const char*>(ptr), realsize);
  stream.append(temp);
  return realsize;
}

//////////////////////////// 질의응답 REST API
#include <curl/curl.h>
#include <json/json.h>
#include <iostream>
#include <string>

using namespace std;

size_t writeDataFunc(void *ptr, size_t size, size_t nmemb, std::string stream);

int main() {
  char* openApiURL = (char*)"http://aiopen.etri.re.kr:8000/DocQA";
  string accessKey = "YOUR_ACCESS_KEY";
  string question = "YOUR_QUESTION";
  string doc_key  = "YOUR_DOC_KEY";

  Json::Value request;
  Json::Value argument;

  argument["question"] = question ;
  argument["doc_key "] = doc_key  ;

  request["argument"] = argument;

  CURL *curl;
  curl_slist* responseHeaders = NULL;
  curl = curl_easy_init();

  if( curl == NULL ) {
    cout << "Unable to initialize cURL interface" << endl ;
  } else {
    responseHeaders = curl_slist_append( responseHeaders , "Content-Type: application/json; charset=UTF-8" ) ;
    responseHeaders = curl_slist_append(responseHeaders, ("Authorization: " + accessKey).c_str() ) ;
    string requestJson = request.toStyledString();
    long statusCode;
    string response;

    curl_easy_setopt(curl, CURLOPT_URL, openApiURL);
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, responseHeaders ) ;
    curl_easy_setopt(curl, CURLOPT_TIMEOUT, 5);
    curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(curl, CURLOPT_POSTFIELDS, requestJson.c_str());
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeDataFunc);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);

    curl_easy_perform(curl);

    curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &statusCode);
    curl_easy_cleanup(curl);

    cout << "[responseCode] " << statusCode << endl;
    cout << "[responBody]" << endl;
    cout << response << endl;
  }

  return 0;
}

size_t writeDataFunc(void *ptr, size_t size, size_t nmemb, std::string stream) {
  size_t realsize = size * nmemb;
  std::string temp(static_cast<const char*>(ptr), realsize);
  stream.append(temp);
  return realsize;
}

python 3.0을 기준으로 작성되었습니다.

HTTP 통신을 위해 urllib3 라이브러리를 사용하여 제공하고 있습니다. Python 3.0 이하의 버전에서 예제를 실행하기 위해서는 별도로 urllib3의 설치가 필요합니다. 설치에 대한 설명은 https://pypi.python.org/pypi/urllib3 를 참고하시기 바랍니다. urllib3 라이브러리에 대한 자세한 설명은 https://urllib3.readthedocs.io/en/latest/ 에서 확인 하실 수 있습니다.

############################# 문서 등록 REST API
  #-*- coding:utf-8 -*-
  import urllib3
  import json
  import os
  
  openApiURL = "http://aiopen.etri.re.kr:8000/DocUpload"
  accessKey = "YOUR_ACCESS_KEY"
  uploadFilePath = "YOUR_FILE_PATH"
  
  file = open(uploadFilePath,'rb')
  fileContent = file.read()
  file.close();
  
  requestJson = {	
    "argument": {"type" : "hwp"}
  }
  
  http = urllib3.PoolManager()
  response = http.request(
    "POST",
    openApiURL,
    headers={"Authorization": accessKey},
    fields={
      'json': json.dumps(requestJson),
      'doc_file': (os.path.basename(file.name), fileContent)
    }
  )
  
  print("[responseCode] " + str(response.status))
  print("[responBody]")
  print(response.data)
  
  ############################# 질의응답 REST API
  import urllib3
  import json
  
  openApiURL = "http://aiopen.etri.re.kr:8000/DocQA"
  accessKey = "YOUR_ACCESS_KEY"
  question = "YOUR_QUESTION"
  doc_key  = "YOUR_DOC_KEY"
  
  requestJson = {
    "argument": {
       "question": question,
       "doc_key": doc_key
    }
  }
  
  http = urllib3.PoolManager()
  response = http.request(
    "POST",
    openApiURL,
    headers={"Content-Type": "application/json; charset=UTF-8","Authorization": accessKey},
    body=json.dumps(requestJson)
  )
  
  print("[responseCode] " + str(response.status))
  print("[responBody]")
  print(str(response.data,"utf-8"))
//////////////////////////// 문서 등록 REST API
var fs = require('fs');
var path = require("path");

var openApiURL = 'http://aiopen.etri.re.kr:8000/DocUpload';
var accessKey = 'YOUR_ACCESS_KEY';
var uploadFilePath = 'YOUR_FILE_PATH';
var fileData;

var fileData = fs.readFileSync(uploadFilePath);

var requestJson = {	
	'argument': {'type' : 'hwp'}
};

var BOUNDARY = Math.random() * Date.now();
var DELIMITER = "-------------" + BOUNDARY;
var CRLF = "\r\n";

// request json data
var data = "--" + DELIMITER + CRLF;
data += "Content-Disposition: form-data; name=\"json\""+CRLF+CRLF;
data += JSON.stringify(requestJson)+CRLF;

// request file data
data += "--" + DELIMITER + CRLF;
data += "Content-Disposition: form-data; name=\"doc_file\"; filename=\""+path.basename(uploadFilePath)+"\""+CRLF;
data += "Content-Transfer-Encoding: binary"+CRLF+CRLF

var payload = Buffer.concat([
	new Buffer(data),
	new Buffer(fileData, 'binary'),
	new Buffer(CRLF+"--"+DELIMITER+"--"+CRLF)
]);

var request = require('request');
var options = {
	url: openApiURL,
	body: payload,
	headers: {"Content-Type": "multipart/form-data; boundary=" + DELIMITER,'Authorization':access_key}
};

request.post(options, function (error, response, body) {
	console.log('responseCode = ' + response.statusCode);
	console.log('responseBody = ' + body);
});

//////////////////////////// 질의응답 REST API	
var openApiURL = 'http://aiopen.etri.re.kr:8000/DocQA';
var access_key = 'YOUR_ACCESS_KEY';
var question = 'YOUR_QUESTION';
var doc_key  = "YOUR_DOC_KEY";
var requestJson = {
    'argument': {
      'question': question,
      'doc_key':doc_key
    }
};

var request = require('request');
var options = {
    url: openApiURL,
    body: JSON.stringify(requestJson),
    headers: {'Content-Type':'application/json; charset=UTF-8','Authorization':access_key}
};
request.post(options, function (error, response, body) {
    console.log('responseCode = ' + response.statusCode);
    console.log('responseBody = ' + body);
});

행정문서 QA API 레퍼런스

  • 요청 파라미터
  • 응답
  • 오류코드
1. 문서등록

문서등록 API에 필요한 요청 본문에 다음과 같은 파라미터를 작성해야 합니다.


[HTTP Request Header]
Content-Type:multipart/form-data; boundary=----[파일 구분자 문자열]

[HTTP Request Body]
------[파일 구분자 문자열]
Content-Disposition: form-data; name="json"
{
    "request_id": "reserved field",
    "access_key": “YOUR_ACCESS_KEY”,
    "argument": {"type":"hwp"}
}

------[파일 구분자 문자열]
Content-Disposition: form-data; name="doc_file"; filename="[파일 명]"
Content-Type: [파일 타입]

[파일의 Byte 문자열]
------[파일 구분자 문자열]--

다음은 파라미터에 대한 설명입니다.

Field 명 타입 필수 여부 설명
access_key String API 사용을 위해 ETRI에서 발급한 사용자 API Key
doc_file File 업로드할 문서 파일
argument Object API 사용 요청 시 분석을 위해 전달할 내용
type String 문서 파일의 확장자(hwp/hwpx)

2. 질의응답

질의응답 API에 필요한 요청 본문에 다음과 같은 파라미터를 작성해야 합니다.


[HTTP Request Header] 
"Authorization" : "YOUR_ACCESS_KEY"

[HTTP Request Body]
{
"argument": {
    "doc_key": "YOUR_Document_Key",
    "question": "YOUR_QUESTION"
    }
}

다음은 파라미터에 대한 설명입니다.

Field 명 타입 필수 여부 설명
access_key String API 사용을 위해 ETRI에서 발급한 사용자 API Key
argument Object API 사용 요청 시 분석을 위해 전달할 내용
doc_key String 문서 등록 API에서 리턴 받은 doc key 로서 UTF-8 인코딩된 텍스트만 지원
question String 질문하고자 하는 text로서 UTF-8 인코딩된 텍스트만 지원
1. 문서등록

문서등록 API는 사용자가 등록한 문서에 대해 언어분석을 한 후, 사용자에게 JSON 형태의 Doc Key를 반환합니다.

다음은 정상적인 요청 처리에 대한 HTTP 응답 예입니다.


[HTTP Respone Header]
Access-Control-Allow-Origin:*
Connection:close
Content-Length:50783
Content-Type:application/json; charset=UTF-8

[HTTP Respone Body]
{
    "request_id": "reserved field",
    "result": 0,
    "return_type": "com.google.gson.internal.LinkedTreeMap",
    "return_object": {문서 등록 결과 JSON}
}

다음은 오류가 발생한 요청 처리에 대한 HTTP 응답 예입니다.


[HTTP Respone Header]
Access-Control-Allow-Origin:*
Connection:close
Content-Length:0
Content-Type:application/json; charset=UTF-8

[HTTP Respone Body]
{
    "request_id": "reserved field",
    "result": -1,
    "reason": {오류 메시지}
}

분석된 결과는 다음과 같은 내용이 포함되어 있습니다.

구분 JSON Key 이름 설명
DocInfo doc_key 등록된 파일에 대한 고유 document key

2. 질의응답

문서 등록 API는 사용자가 등록한 문서에 대해 언어분석을 한 후, 사용자에게 JSON 형태의 Doc Key를 반환합니다.

다음은 정상적인 요청 처리에 대한 HTTP 응답 예입니다.


[HTTP Respone Header]
Access-Control-Allow-Origin:*
Connection:close
Content-Length:50783
Content-Type:application/json; charset=UTF-8

[HTTP Respone Body]
{
    "request_id": "reserved field",
    "result": 0,
    "return_type": "com.google.gson.internal.LinkedTreeMap",
    "return_object": {문서 QA 결과 JSON}
}

다음은 오류가 발생한 요청 처리에 대한 HTTP 응답 예입니다.


[HTTP Respone Header]
Access-Control-Allow-Origin:*
Connection:close
Content-Length:0
Content-Type:application/json; charset=UTF-8

[HTTP Respone Body]
{
    "request_id": "reserved field",
    "result": -1,
    "reason": {오류 메시지}
}

분석된 결과는 다음과 같은 내용이 포함되어 있습니다.

구분 JSON Key 이름 설명
DocInfo question 질문
answer 정답
confidence 신뢰도
passage 정답이 포함된 단락
evidence 정답의 근거 문장(리스트)

행정 문서 QA API의 오류 코드 목록은 다음과 같습니다.

http status code result reason 설명
403 -1 Empty Auth Header Authorization 헤더가 없는 경우
403 -1 Invalid Key KEY API 키가 없는 경우
403
-1 Blocked KEY API 키가 관리자에 의해서 차단된 경우
403
-1 Daily Limit Exceeded 일간 호출 제한에 걸린 경우
403
-1 Monthly Limit Exceeded
월간 호출 제한에 걸린 경우
403
-1 Yearly Limit Exceeded
연간 호출 제한에 걸린 경우
403
-1 Too Many Keys 같은 IP에서 여러 API 키가 사용된 경우
403
-1 Too Many IPs 하나의 API 키를 여러 IP 에서 사용한 경우
403
-1 Not Allowed IP API 호출 가능한 IP 가 아닌경우
(API 설정에서 허용된 IP가 아닌경우)
403
-1 Not Allowed Subpath 하위경로 접근 제한이 되어 있는 경우
403 -1 Invalid API
등록되지 않은 API를 요청한 경우
408 -1
Request Timeout
서버의 요청 대기가 시간을 초과한 경우
413
-1 Body Size Limit Exceeded
요청 바디가 설정된 값보다 큰 경우
429
-1 Concurrent Limit Exceeded
연속호출 허용 범위를 넘어서 호출한 경우
500 -1 Internal Server Error 내부 오류 발생한 경우