适用于低于v0.3.0版本镜像

PAI-RAG提供丰富的API接口,用于服务管理、对话等功能。本文为您介绍使用低于v0.3.0版本镜像部署的RAG服务所支持的接口类型及调用方式。

使用限制

该文档仅适用于使用低于v0.3.0版本镜像部署的RAG服务。

您可以前往模型在线服务(EAS)页面,单击RAG服务名称,然后在概览页面的环境信息区域,查看镜像版本。image

获取服务访问地址和Token

通过API接口调用RAG服务前,您需获取RAG服务的访问地址和Token:

  1. 登录PAI控制台,在页面上方选择目标地域,并在右侧选择目标工作空间,然后单击进入EAS

  2. 单击目标服务名称,然后在基本信息区域,单击查看调用信息

  3. 调用信息对话框中获取服务访问地址(EAS_SERVICE_URL)Token(EAS_Token)

    重要
    • 请将EAS_SERVICE_URL末尾的斜杠(/)删除。

    • 使用公网地址调用:调用客户端支持访问公网。

    • 使用VPC地址调用:调用客户端必须与RAG服务位于同一个专有网络内。

    image

Chat API(对话接口)

通过OpenAI-Compatiable API调用服务。调用服务前,您需根据使用的功能,提前在RAG服务的WebUI页面完成相应配置。

支持功能

  • web search:联网搜索。配置网络搜索参数

  • chat knowledgebase:知识库查询。需上传知识库文件

  • chat llm:使用LLM回答。需配置LLM服务

  • chat agent:智能体工具调用。需在WebUI页面配置Agent相关代码。

  • chat db:数据库/表格查询。需在WebUI页面配置DBChat相关参数。

调用方式

调用地址

{EAS_SERVICE_URL}/v1/chat/completions

请求方式

POST

请求HEADERS

Authorization: EAS_TOKEN(EAS调用Token)

HTTP Body样例

{
    "model": "default",  # 模型名称,填default
    "messages": [
        {"role": "user", "content": "您好"},
        {"role": "assistant", "content": "您好,有什么能帮到您?"},
        {"role": "user", "content": "浙江省会是哪里"},
        {"role": "assistant", "content": "杭州是浙江的省会。"},
        {"role": "user", "content": "有哪些好玩的"},
    ],
    "stream": true,  # 是否流式
    "chat_knowledgebase": true,  # 是否查询本地知识库
    "search_web": false,  # 是否使用联网搜索
    "chat_llm": false,  # 是否仅使用LLM聊天
    "chat_agent": false,  # 是否使用Agent
    "chat_db": false,  # 是否查询数据库
    "index_name": "default_index",  # 索引名称用于RAG场景,仅支持配置1个索引名称,若未指定,系统将使用默认索引
    "max_tokens": 1024,  # 最大输出长度,如1024
    "temperature": 0.1,  # 控制生成内容随机性,取值范围[0,1],值越低确定性越高,值越高内容越多样化
}
重要
  • 如果同时配置多个功能,系统会按照该优先级进行调用,优先级从高到低依次为search_web、chat_knowledgebase、chat_agent、chat_db、chat_llm。同时,在每个功能中,系统会进行前置意图识别,以区分是否调用该功能,或直接使用大语言模型(LLM)生成回复。

  • 如果所有功能开关都为 false 或未传递,则默认查询本地知识库(即"chat_knowledgebase": true)。

请求示例(单击此处,查看详情)

联网搜索

from openai import OpenAI

##### API 配置 #####
# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。

openai_api_key = "<EAS_TOKEN>"
openai_api_base = "<EAS_SERVICE_URL>/v1"
client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)


#### Chat ######
def chat():
    stream = True
    chat_completion = client.chat.completions.create(
        model="default",
        stream=stream,
        messages=[
            {"role": "user", "content": "你好"},
            {"role": "assistant", "content": "你好,有什么能帮到您?"},
            {"role": "user", "content": "浙江省会是哪里"},
            {"role": "assistant", "content": "杭州是浙江的省会。"},
            {"role": "user", "content": "有哪些好玩的"},
        ],
        extra_body={
            "search_web": True,
        },
    )

    if stream:
        for chunk in chat_completion:
            print(chunk.choices[0].delta.content, end="")
    else:
        result = chat_completion.choices[0].message.content
        print(result)


chat()

查询数据库

from openai import OpenAI

##### API 配置 #####
# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。

openai_api_key = "<EAS_TOKEN>"
openai_api_base = "<EAS_SERVICE_URL>/v1"
client = OpenAI(
    api_key=openai_api_key,
    base_url=openai_api_base,
)


#### Chat ######
def chat():
    stream = True
    chat_completion = client.chat.completions.create(
        model="default",
        stream=stream,
        messages=[
            {"role": "user", "content": "有多少只猫"},
            {"role": "assistant", "content": "有2只猫"},
            {"role": "user", "content": "狗呢"},
        ],
        extra_body={
            "chat_db": True,
        },
    )

    if stream:
        for chunk in chat_completion:
            print(chunk.choices[0].delta.content, end="")
    else:
        result = chat_completion.choices[0].message.content
        print(result)


chat()

Management API(管理接口)

上传知识库文件

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/upload_data

请求方式

POST

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: multipart/form-data

请求参数

  • files:文件

  • oss_path:对象存储OSS路径

  • index_name:索引名称(默认为default_index)

cURL请求示例(单击此处,查看详情)

  • 上传单个文件

     # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
     # "-F 'files=@"后的路径需替换为您的文件路径。 
     # index_name配置为您的知识库索引名称。 
       curl -X 'POST' <EAS_SERVICE_URL>/api/v1/upload_data \
      -H 'Authorization: <EAS_TOKEN>' \
      -H 'Content-Type: multipart/form-data' \
      -F 'files=@example_data/paul_graham/paul_graham_essay.txt' \
      -F 'index_name=default_index'
  • 上传多份文件,可以使用多个-F 'files=@path'参数,每个参数对应一个要上传的文件,示例如下:

      # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
      # “-F 'files=@”后的路径需替换为您的文件路径。 
      # index_name配置为您的知识库索引名称。 
      curl -X 'POST' <EAS_SERVICE_URL>/api/v1/upload_data \
      -H 'Authorization: <EAS_TOKEN>' \
      -H 'Content-Type: multipart/form-data' \
      -F 'files=@example_data/paul_graham/paul_graham_essay.txt' \
      -F 'files=@example_data/another_file1.md' \
      -F 'files=@example_data/another_file2.pdf' \
      -F 'index_name=default_index'

返回示例(单击此处,查看详情)

  { "task_id": "2c1e557733764fdb9fefa0635389****" }

检查上传任务状态

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/get_upload_state

请求方式

GET

请求HEADERS

Authorization: EAS_TOKEN # EAS调用Token

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
# task_id配置为“上传知识库文件”返回的task_id。 
curl -X 'GET' '<EAS_SERVICE_URL>/api/v1/get_upload_state?task_id=2c1e557733764fdb9fefa0635389****' -H 'Authorization: <EAS_TOKEN>'

返回示例(单击此处,查看详情)

  {
    "task_id": "2c1e557733764fdb9fefa0635389****",
    "status": "completed",
    "detail": null
  }

知识库检索

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/query/retrieval

请求方式

POST

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: application/json

请求参数

  • question:用户检索问题

  • index_name:索引名称(默认为default_index)

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
# question:配置为用户检索问题。 
# index_name:配置为索引名称。 
  curl -X 'POST' '<EAS_SERVICE_URL>/api/v1/query/retrieval' \
  -H 'Authorization: <EAS_TOKEN>' \
  -H 'Content-Type: application/json' \
  -d '{
      "question": "What can I do when the x13-auto-arima component reports an error?",
      "index_name": "default_index"
  }'

返回示例(单击此处,查看详情)

{
  "docs": [
    {
      "text": "2.PAl-Studio/Designer FAQ 2.1. FAQ about algorithm components : \nCharacters that cannot be transcoded are displayed as \"blob.\" Ignore this error, because nodes in the downstream can read and process the data.\nWhat can I do when the x13-auto-arima component reports an error?\nMake sure that up to 1,200 training data samples are imported into the x13-auto-arima component.\nWhat can I do when the Doc2Vec component reports the CallExecutorToParseTaskFail error?",
      "score": 0.83608,
      "metadata": {
        "file_path": "***/pai_document.md",
        "file_name": "pai_document.md",
        "file_size": 3794,
        "creation_date": "2025-03-20",
        "last_modified_date": "2025-03-20"
      },
      "image_url": null
    }
  ]
}

上传Excel/CSV文件用于Chat_DB的表格内容查询

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/upload_datasheet

请求方式

POST

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: multipart/form-data

请求参数

ExcelCSV文件。

cURL请求示例(单击此处,查看详情)

  # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
  # “-F 'file=@”后的路径替换为实际文件路径。 
  curl -X 'POST' <EAS_SERVICE_URL>/api/v1/upload_datasheet \
  -H 'Authorization: <EAS_TOKEN>' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@example_data/titanic_train.csv'

返回示例(单击此处,查看详情)

  {
    "task_id": "3b12cf5fabee4a99a32895d2f693****",
    "destination_path": "./localdata/data_analysis/titanic_train.csv",
    "data_preview": "xxx"
  }

上传JSON文件用于Chat_DB的数据库信息补充-问答对

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/upload_db_history

请求方式

POST

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: multipart/form-data

请求参数

  • file:JSON文件

  • db_name:数据库名称

cURL请求示例(单击此处,查看详情)

  # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
  # “-F 'file=@”配置为您的JSON文件路径。 
  # db_name配置为您的数据库名称。 
  curl -X 'POST' <EAS_SERVICE_URL>/api/v1/upload_db_history \
  -H 'Authorization: <EAS_TOKEN>' \
  -H 'Content-Type: multipart/form-data' \
  -F 'file=@example_data/db_query_history.json' \
  -F 'db_name=my_pets'

返回示例(单击此处,查看详情)

  {
    "task_id": "204191f946384a54a48b13ec00fd****",
    "destination_path": "./localdata/data_analysis/nl2sql/history/my_pets_db_query_history.json"
  } 

加载数据库信息

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/query/load_db_info

请求方式

POST

请求HEADERS

Authorization: EAS_TOKEN # EAS调用Token

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
curl -X 'POST' <EAS_SERVICE_URL>/api/v1/query/load_db_info -H 'Authorization: <EAS_TOKEN>'

返回示例(单击此处,查看详情)

"Load database info successfully."

获取当前所有知识库索引

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/indexes

请求方式

GET

请求HEADERS

Authorization: EAS_TOKEN # EAS调用Token

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
curl -X 'GET' '<EAS_SERVICE_URL>/api/v1/indexes' -H 'Authorization: <EAS_TOKEN>'

返回示例(单击此处,查看详情)

  {
    "indexes": {
      "default_index": {
        "index_name": "default_index",
        "vector_store_config": {
          "persist_path": "localdata/storage",
          "type": "faiss",
          "is_image_store": false
        },
        "embedding_config": {
          "source": "huggingface",
          "model": "bge-m3",
          "embed_batch_size": 10,
          "enable_sparse": false
        }
      }
    },
    "current_index_name": "default_index"
  }

创建知识库索引

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/indexes/{index_name}

请求方式

POST

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: application/json

请求参数

  • index_name:索引名称

  • vector_store_config:向量库配置

  • embedding_config:Embedding模型配置

cURL请求示例(单击此处,查看详情)

    # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
    # <my_index>替换为新增的知识库索引。 
    # vector_store_config需配置为向量数据库配置。
    curl -X 'POST' '<EAS_SERVICE_URL>/api/v1/indexes/<my_index>' \
    -H 'Authorization: <EAS_TOKEN>' \
    -H 'Content-Type: application/json' \
    -d '{
        "index_name": "<my_index>",
        "vector_store_config": {
            "type": "faiss"
        },
        "embedding_config": {
            "model": "bge-m3",
            "source": "huggingface"
        }
    }'

上述代码中vector_store_config配置以faiss为例,其他向量数据库vector_store_config配置说明如下:

milvus

"vector_store_config":
      {
          "type":"milvus",
          "host":"c-xxxxx.milvus.aliyuncs.com",
          "port":19530,
          "user":"root",
          "password":"xxx",
          "database":"default",
          "collection_name":"test",
          "reranker_weights":[0.5,0.5]
      }

hologres

"vector_store_config":
      {
          "type":"hologres",
          "host":"xxx",
          "port":xxx,
          "user":"xxx",
          "password":"xxx",
          "database":"default",
          "table_name":"test",
          "pre_delete_table":"false"
      }

elasticsearch

"vector_store_config":
      {
          "type":"elasticsearch",
          "es_url":"xxx",
          "es_user":xxx,
          "es_password":"xxx",
          "es_index":"xxx"
      }

opensearch

"vector_store_config":
      {
          "type":"opensearch",
          "endpoint":"xxx",
          "instance_id":xxx,
          "username":"xxx",
          "password":"xxx",
          "table_name":"xxx"
      }

analyticdb

"vector_store_config":
      {
          "type":"analyticdb",
          "ak":"xxx",
          "sk":xxx,
          "region_id":"xxx",
          "instance_id":"xxx",
          "account":"xxx",
          "account_password":"xxx",
          "namespace":"xxx",
          "collection":"xxx"
      }

tablestore

"vector_store_config":
      {
          "type":"tablestore",
          "endpoint":"xxx",
          "instance_name":xxx,
          "access_key_id":"xxx",
          "access_key_secret":"xxx",
          "table_name":"xxx"
      }

dashvector

"vector_store_config":
      {
          "type":"dashvector",
          "endpoint":"xxx",
          "api_key":xxx,
          "collection_name":"xxx",
          "partition_name":"xxx"
      }

返回示例(单击此处,查看详情)

  { "msg": "Add index 'my_index' successfully." }

更新知识库索引

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/indexes/{index_name}

请求方式

PATCH

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: application/json

请求参数

  • index_name:索引名称

  • vector_store_config:向量库配置

  • embedding_config:Embedding模型配置

cURL请求示例 (单击此处,查看详情)

    # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
    # <my_index>替换为待更新的知识库索引。 
    # vector_store_config需配置为待更新的向量数据库配置。
    curl -X 'PATCH' '<EAS_SERVICE_URL>/api/v1/indexes/<my_index>' \
    -H 'Authorization: <EAS_TOKEN>' \
    -H 'Content-Type: application/json' \
    -d '{
        "index_name": "<my_index>",
        "vector_store_config": {
            "type": "faiss"
        },
        "embedding_config": {
            "model": "bge-m3",
            "source": "huggingface"
        }
    }'

上述代码中vector_store_config配置以faiss为例,其他向量数据库vector_store_config配置说明,请参见创建知识库索引

返回示例(单击此处,查看详情)

  { "msg": "Update index 'my_index' successfully." }

删除知识库索引

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/indexes/{index_name}

请求方式

DELETE

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: application/json

请求参数

index_name:索引名称

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
# <my_index>替换为待删除的知识库索引。 
curl -X 'DELETE' '<EAS_SERVICE_URL>/api/v1/indexes/<my_index>' -H 'Authorization: <EAS_TOKEN>' -H 'Content-Type: application/json' -d '{"index_name":"<my_index>"}'

返回示例(单击此处,查看详情)

  { "msg": "Delete index 'my_index' successfully." }

获取RAG服务配置

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/config

请求方式

GET

请求HEADERS

Authorization: EAS_TOKEN # EAS调用Token

cURL请求示例(单击此处,查看详情)

# <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
curl -X 'GET' '<EAS_SERVICE_URL>/api/v1/config' -H 'Authorization: <EAS_TOKEN>'

返回示例(单击此处,查看详情)

  {
    "system": {
      "default_web_search": false,
      "query_type": "websearch"
    },
    "data_reader": {
      "concat_csv_rows": false,
      "enable_mandatory_ocr": false,
      "format_sheet_data_to_json": false,
      "sheet_column_filters": null,
      "number_workers": 4
    },
    "node_parser": {
      "type": "Sentence",
      "chunk_size": 500,
      "chunk_overlap": 10,
      "enable_multimodal": true,
      "paragraph_separator": "\n\n\n",
      "sentence_window_size": 3,
      "sentence_chunk_overlap": 200,
      "breakpoint_percentile_threshold": 95,
      "buffer_size": 1
    },
    "index": {
      "vector_store": {
        "persist_path": "localdata/storage",
        "type": "faiss",
        "is_image_store": false
      },
      "enable_multimodal": true,
      "persist_path": "localdata/storage"
    },
    "embedding": {
      "source": "huggingface",
      "model": "bge-m3",
      "embed_batch_size": 10,
      "enable_sparse": false
    },
    "multimodal_embedding": {
      "source": "cnclip",
      "model": "ViT-L-14",
      "embed_batch_size": 10,
      "enable_sparse": false
    },
    "llm": {
      "source": "openai_compatible",
      "temperature": 0.1,
      "system_prompt": null,
      "max_tokens": 4000,
      "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
      "api_key": "sk-xxx",
      "model": "qwen-max"
    },
    "multimodal_llm": {
      "source": "openai_compatible",
      "temperature": 0.1,
      "system_prompt": null,
      "max_tokens": 4000,
      "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
      "api_key": "sk-xxx",
      "model": ""
    },
    "functioncalling_llm": null,
    "agent": {
      "system_prompt": "你是一个旅游小助手,xxx",
      "python_scripts": "xxx",
      "function_definition": "xxx",
      "api_definition": "xxx"
    },
    "chat_store": {
      "type": "local",
      "persist_path": "localdata/storage"
    },
    "data_analysis": {
      "type": "mysql",
      "nl2sql_prompt": "给定一个输入问题,xxx",
      "synthesizer_prompt": "给定一个输入问题,xxx",
      "database": "my_pets",
      "tables": [],
      "descriptions": {},
      "enable_enhanced_description": false,
      "enable_db_history": true,
      "enable_db_embedding": true,
      "max_col_num": 100,
      "max_val_num": 1000,
      "enable_query_preprocessor": true,
      "enable_db_preretriever": true,
      "enable_db_selector": true,
      "user": "root",
      "password": "xxx",
      "host": "127.0.0.1",
      "port": 3306
    },
    "intent": {
      "descriptions": {
        "rag": "\nThis tool can help you get more specific information from the knowledge base.\n",
        "tool": "\nThis tool can help you get travel information about time, weather, flights, train and hotels.\n"
      }
    },
    "node_enhancement": {
      "tree_depth": 3,
      "max_clusters": 52,
      "proba_threshold": 0.1
    },
    "oss_store": {
      "bucket": "",
      "endpoint": "oss-cn-hangzhou.aliyuncs.com",
      "ak": null,
      "sk": null
    },
    "postprocessor": {
      "reranker_type": "no-reranker",
      "similarity_threshold": 0.5
    },
    "retriever": {
      "vector_store_query_mode": "default",
      "similarity_top_k": 3,
      "image_similarity_top_k": 2,
      "search_image": false,
      "hybrid_fusion_weights": [0.7, 0.3]
    },
    "search": {
      "source": "google",
      "search_count": 10,
      "serpapi_key": "142xxx",
      "search_lang": "zh-CN"
    },
    "synthesizer": {
      "use_multimodal_llm": false,
      "system_role_template": "您是xxx",
      "custom_prompt_template": "您的目标是提供准确、有用且易于理解的信息。xxx"
    },
    "query_rewrite": {
      "enabled": true,
      "rewrite_prompt_template": "# 角色\n您是一位专业的信息检索专家,xxx",
      "llm": {
        "source": "openai_compatible",
        "temperature": 0.1,
        "system_prompt": null,
        "max_tokens": 4000,
        "base_url": "https://dashscope.aliyuncs.com/compatible-mode/v1",
        "api_key": null,
        "model": ""
      }
    },
    "guardrail": {
      "endpoint": null,
      "region": null,
      "access_key_id": null,
      "access_key_secret": null,
      "custom_advice": null
    }
  }

更新RAG服务配置

调用方式

调用地址

{EAS_SERVICE_URL}/api/v1/config

请求方式

PATCH

请求HEADERS

  • Authorization: EAS_TOKEN # EAS调用Token

  • Content-Type: application/json

请求参数

new_config:更新的配置信息

cURL请求示例(单击此处,查看详情)

    # <EAS_TOKEN>和<EAS_SERVICE_URL>需分别替换为服务Token和访问地址。
    curl -X 'PATCH' '<EAS_SERVICE_URL>/api/v1/config' \
    -H 'Authorization: <EAS_TOKEN>' \
    -H 'Content-Type: application/json' \
    -d '{
        "system": {
          "default_web_search": false,
          "query_type": "websearch"
        },
        "data_reader": {
          "concat_csv_rows": false,
          "enable_mandatory_ocr": false,
          "format_sheet_data_to_json": false,
          "sheet_column_filters": null,
          "number_workers": 4
        },
        "node_parser": {
          "type": "Sentence",
          "chunk_size": 500,
          "chunk_overlap": 10,
          "enable_multimodal": true,
          "paragraph_separator": "\n\n\n",
          "sentence_window_size": 3,
          "sentence_chunk_overlap": 200,
          "breakpoint_percentile_threshold": 95,
          "buffer_size": 1
        },
        ...
    }' # (更多配置信息可参考 获取RAG配置 的返回示例)

返回示例(单击此处,查看详情)

  { "msg": "Update RAG configuration successfully." }