文档

Python SDK(旧版)

更新时间:
一键部署

本文主要描述通过Python SDK调用阿里云百炼云服务的使用方式。Python SDK支持3.7以上版本.

重要

本文档适用于使用Python SDK 1.1.9及以下的旧版本,最新版本请参照文档安装SDK

获取和安装SDK

pip install broadscope-bailian==1.1.9

接口说明

公共参数

所有接口调用需要设置公共参数Access Key、Access Secret Key和Agent Key, 获取方式请参考Access Key、Access Secret Key、Agent Key、AppId获取方式

生成文本

文本生成接口输入对应的参数后,阿里云百炼处理所有的逻辑,将最终的结果返回。

import broadscope_bailian

app_id = "******"
prompt = "帮我查询下酒店"

resp = broadscope_bailian.Completions().call(app_id=app_id, prompt=prompt)

请求参数说明

文本生成请求参数。

参数名

参数类型

是否必填

说明

request_id

str

请求唯一标识。

session_id

str

上下文唯一标识。

app_id

str

阿里云百炼应用ID, 请参考Completion API文档(旧版)方式获取。

prompt

str

提示词。

top_p

float

生成过程中核采样方法概率阈值,例如,取值为0.8时,仅保留概率加起来大于等于0.8的最可能token的最小集合作为候选集。取值范围为(0,1.0),取值越大,生成的随机性越高;取值越低,生成的确定性越高。默认是0.2。

stream

bool

是否流式输出。

has_thoughts

bool

是否输出模型推理中间结果。

biz_params

Dict

插件使用的业务参数,调用api插件是会直接透传。

doc_reference_type

str

启用文档检索后,文档引用类型, 取值包括:simple | indexed。

simple: 返回文档引用信息,但文本中不包含文档角标的索引位置。

indexed: 返回文档引用信息,文本中包含文档角标的索引位置。

top_k

int

排名最高的K个结果

seed

int

初始化值

temperature

float

采样温度在0到2之间。较高的值(如0.8)将使输出更加随机,而较低的值(如0.2)将使输出更加集中和确定。我们通常建议修改temperature或top_p,但不建议两者都修改。

max_tokens

int

模型生成的token的最大数量。输入token数量和生成token数量的总长度受模型上下文长度的限制。

use_raw_prompt

bool

是否使用原始prompt。

doc_tag_ids

List[int]

文档标签id。

history

list[ChatQaMessage]

调用侧的上下文历史。

ChatQaMessage

user

str

对话历史的用户消息。

bot

str

对话历史的大模型消息。

响应结果说明

文本生成响应参数。

参数

类型

描述

Success

bool

请求是否成功, true: 是, false: 否

Code

int

失败错误码,0表示成功,其他值则表示调用出错

Message

str

失败错误消息,仅当失败是有错误消息

RequestId

str

请求的唯一标识

Data

Dict

文本生成结果

Data: 文本生成的内容。

参数

类型

描述

ResponseId

str

相应唯一标识

SessionId

str

上下文唯一标识

Text

str

最终输出结果

Thoughts

list[thought]

思考过程

DocReferences

list[DocReference]

文档引用信息

Usage

list[Usage]

应用级别的token消耗

Thought: 推理过程数据格式定义

参数

类型

描述

Thought

str

LLM思考结果

ActionType

str

llm返回的执行步骤类型, api: 执行api插件,

response: 返回最终结果

ActionName

str

执行的action名称, 如文档检索

Action

str

执行的步骤

ActionInputStream

str

入参的流式结果

ActionInput

str

插件的输入参数

Response

str

LLM返回的结果

Observation

str

插件的返回结果

DocReference: 文档引用数据格式定义

参数

类型

描述

IndexId

string

引用的角标索引

Title

string

引用的文档标题

DocId

string

引用的文档Id

DocName

string

引用的文档名

DocUrl

string

文档下载地址

Text

string

引用的文档内容

BizId

string

业务关联标识

Usage: token用量数据格式定义

参数

类型

描述

InputTokens

int

输出文本消耗的token

OutputTokens

int

输出文本消耗的token

代码示例

import os
import broadscope_bailian


def test_completions():
    access_key_id = os.environ.get("ACCESS_KEY_ID")
    access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
    agent_key = os.environ.get("AGENT_KEY")
    app_id = os.environ.get("APP_ID")

    client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
                                                  agent_key=agent_key)
    token = client.get_token()

    prompt = "帮我生成一篇200字的文章,描述一下春秋战国的政治、军事和经济"
    resp = broadscope_bailian.Completions(token=token).call(app_id=app_id, prompt=prompt)

    if not resp.get("Success"):
        print('failed to create completion, request_id: %s, code: %s, message: %s' % (
            resp.get("RequestId"), resp.get("Code"), resp.get("Message")))
        return

    print("request_id: %s, text: %s" % (resp.get("RequestId"), resp.get("Data", "").get("Text")))
    if resp.get("Data", "").get("Usage") is not None and len(resp.get("Data", "").get("Usage")) > 0:
        usage = resp.get("Data", "").get("Usage")[0]
        print("input tokens: %d, output tokens: %d" % (usage.get("InputTokens"), usage.get("OutputTokens")))


test_completions()

其他参数使用代码示例

import os
import broadscope_bailian
from broadscope_bailian import ChatQaMessage
import uuid
import json


def test_completions_with_params():
    access_key_id = os.environ.get("ACCESS_KEY_ID")
    access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
    agent_key = os.environ.get("AGENT_KEY")
    app_id = os.environ.get("APP_ID")

    client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
                                                  agent_key=agent_key)
    token = client.get_token()

    session_id = str(uuid.uuid4()).replace("-", "")

    chat_history = [ChatQaMessage("我想去北京", "北京的天气很不错"),
                    ChatQaMessage("背景有哪些景点呢", "背景有故宫、长城等景点")]

    prompt = "云南近5年GNP总和是多少"
    sql_schema = """
        {
            "sqlInput": {
              "synonym_infos": "国民生产总值: GNP|Gross National Product",
              "schema_infos": [
                {
                  "columns": [
                    {
                      "col_caption": "地区",
                      "col_name": "region"
                    },
                    {
                      "col_caption": "年份",
                      "col_name": "year"
                    },
                    {
                      "col_caption": "国民生产总值",
                      "col_name": "gross_national_product"
                    }
                  ],
                  "table_id": "t_gross_national_product_1",
                  "table_desc": "国民生产总值表"
                }
              ]
            }
          }
        """

    resp = broadscope_bailian.Completions(token=token).call(
        app_id=app_id, prompt=prompt,
        # 设置模型参数topP的值
        top_p=0.2,
        # 设置历史上下文, 由调用侧维护历史上下文
        session_id=session_id,
        # 设置历史上下文, 由调用侧维护历史上下文, 如果同时传入sessionId和history, 优先使用调用者管理的对话上下文
        history=chat_history,
        # 设置模型参数topK
        top_k=50,
        # 设置模型参数seed
        seed=2222,
        # 设置模型参数temperature
        temperature=0.3,
        # 设置模型参数max tokens
        max_tokens=20,
        # 是否使用原始prompt
        use_raw_prompt=True,
        # 设置文档标签tagId,设置后,文档检索召回时,仅从tagIds对应的文档范围进行召回
        doc_tag_ids=[101, 102],
        # 返回文档检索的文档引用数据, 传入为simple或indexed
        doc_reference_type="simple",
        # 自然语言转sql调用示例
        biz_params=json.loads(sql_schema),
        # 超时设置, 单位秒
        timeout=30,
    )

    if not resp.get("Success"):
        print("failed to create completion, request_id: %s, code: %s, message: %s" %
              (resp.get("RequestId"), resp.get("Code"), resp.get("Message")))
    else:
        print("request_id: %s, text: %s" % (resp.get("RequestId"), resp.get("Data", "").get("Text")))


test_completions_with_params()

注:您可以在百炼控制台测试窗使用“表模式”来编辑数据库Schema信息,然后点击“Code模式”生成JSON格式数据,然后将内容替换到sqlInput中。

image.png

流式响应代码示例

import os
import broadscope_bailian


def test_stream_completions():
    access_key_id = os.environ.get("ACCESS_KEY_ID")
    access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
    agent_key = os.environ.get("AGENT_KEY")
    app_id = os.environ.get("APP_ID")

    client = broadscope_bailian.AccessTokenClient(access_key_id=access_key_id, access_key_secret=access_key_secret,
                                                  agent_key=agent_key)
    token = client.get_token()

    prompt = "帮我生成一篇200字的文章,描述一下春秋战国的政治、军事和经济"
    resp = broadscope_bailian.Completions(token=token).call(app_id=app_id, prompt=prompt, stream=True)
    for result in resp:
        if not result.get("Success"):
            print("failed to create completion, request_id: %s, code: %s, message: %s" %
                  (result.get("RequestId"), result.get("Code"), result.get("Message")))
        else:
            print("request_id: %s, text: %s" % (result.get("RequestId"), result.get("Data", '').get("Text")),
                  end="\n", flush=True)


test_stream_completions()

创建文本向量

通过阿里云百炼,将文本内容转换为向量数据。

请求参数说明

文本生成请求参数。

参数

类型

必填

描述

input

List[str]

文本内容数组

text_type

str

向量化类型,包括query和document。

query: 用来检索召回

document: 用来聚类、分类

响应结果说明

文本生成响应参数。

参数

类型

描述

success

bool

请求是否成功, true: 是, false: 否

code

int

失败错误码,0表示成功,其他值则表示调用出错

message

str

失败错误消息,仅当失败是有错误消息

request_id

str

请求的唯一标识

data

Dict

文本生成结果

Data

embeddings

List[Embeddings]

embeddings列表

Embeddings

embedding

List[float]

向量数据

text_index

int

向量数据的索引

代码示例

from alibabacloud_bailian20230601.client import Client
from alibabacloud_bailian20230601.models import CreateTextEmbeddingsRequest
from alibabacloud_tea_openapi.models import Config

import broadscope_bailian
import os


def test_create_embeddings():
    access_key_id = os.environ.get("ACCESS_KEY_ID")
    access_key_secret = os.environ.get("ACCESS_KEY_SECRET")
    agent_key = os.environ.get("AGENT_KEY")

    config = Config(access_key_id=access_key_id,
                    access_key_secret=access_key_secret,
                    endpoint=broadscope_bailian.pop_endpoint)

    client = Client(config=config)

    request = CreateTextEmbeddingsRequest(agent_key=agent_key,
                                          input=["今天天气怎么样", "我想去北京"],
                                          text_type="query")
    response = client.create_text_embeddings(request=request)
    if response.status_code != 200 or response.body is None:
        raise RuntimeError("create token error, code=%d" % response.status_code)

    body = response.body
    if not body.success:
        raise RuntimeError("create token error, code=%s, message=%s" % (body.code, body.message))

    for embedding in body.data.embeddings:
        print("index: %s, embeddings: %s\n" % (embedding.text_index, embedding.embedding))
       

  • 本页导读 (1)
文档反馈