Python SDK

更新时间:

环境依赖

1.Python>=3.7

安装

pip install 直接通过git安装

pip install xingchen==1.1.5

快速开始

from xingchen import Configuration, ApiClient, ChatApiSub, ChatReqParams, CharacterKey, Message, UserProfile, \
    ModelParameters


def build_chat_param():
    return ChatReqParams(
        bot_profile=CharacterKey(
            character_id="c39797a35ad243f1a85baaa6e1ec37e0"
        ),
        model_parameters=ModelParameters(
            seed=1683806810,
            incrementalOutput=False
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='你叫什么名字?'
            ),
            Message(
                name='小婉',
                role='assistant',
                content='我叫小婉啊。'
            ),
            Message(
                name='小明',
                role='user',
                content='你今年多大?'
            ),
            Message(
                name='小婉',
                role='assistant',
                content='我今年17岁了。'
            ),
            Message(
                name='小明',
                role='user',
                content='可以详细介绍浙江有哪些好玩的地方吗?'
            )
        ],
        context=ChatContext(
            use_chat_history=False
        ),
        user_profile=UserProfile(
            user_id='123456789',
            user_name='小明'
        )
    )


def init_client():
    configuration = Configuration(
        host="https://nlp.aliyuncs.com"
    )
    configuration.access_token = "{API-KEY}"
    with ApiClient(configuration) as api_client:
        api_instance = ChatApiSub(api_client)
    return api_instance


# 非流式回复
def test_chat_sync():
    chat_param = build_chat_param()
    res = api.chat(chat_param)
    print(res.to_str())


# 流式回复
def test_chat_async():
    # 用户对话
    chat_param = build_chat_param()
    chat_param.streaming = True
    responses = api.chat(chat_param)
    for res in responses:
        print(res)

api = init_client()
test_chat_sync()
test_chat_async()

对话

准备

from xingchen import Configuration, ApiClient, ChatApiSub

def init_client():
    configuration = Configuration(
        host="https://nlp.aliyuncs.com"
    )
    configuration.access_token = "{YOUR-API-KEY}"
    with ApiClient(configuration) as api_client:
        api_instance = ChatApiSub(api_client)
    return api_instance

固定角色对话

流式输出

from xingchen import Configuration, ApiClient, ChatApiSub, ChatReqParams, CharacterKey, Message, UserProfile, \
    ModelParameters


def build_chat_param():
    return ChatReqParams(
        bot_profile=CharacterKey(
            character_id="c39797a35ad243f1a85baaa6e1ec37e0"
        ),
        model_parameters=ModelParameters(
            seed=1683806810,
            incrementalOutput=False
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='可以详细介绍浙江有哪些好玩的地方吗?'
            )
        ],
        context=ChatContext(
            use_chat_history=False
        ),
        user_profile=UserProfile(
            user_id='123456789',
            user_name='小明'
        )
    )



# 对话准备已省略

api = init_client()
chat_param = build_chat_param()
chat_param.streaming = True
responses = api.chat(chat_param)
for res in responses:
    print(res.to_dict())
非增量输出
我今年
我今年17岁了,很快就要
我今年17岁了,很快就要步入大学了。
我今年17岁了,很快就要步入大学了。
增量输出
我今年
17岁了,很快就要
步入大学了。

非流式输出

from xingchen import Configuration, ApiClient, ChatApiSub, ChatReqParams, CharacterKey, Message, UserProfile, \
    ModelParameters


def build_chat_param():
    return ChatReqParams(
        bot_profile=CharacterKey(
            character_id="c39797a35ad243f1a85baaa6e1ec37e0"
        ),
        model_parameters=ModelParameters(
            seed=1683806810
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='你叫什么名字?'
            )
        ],
        context=ChatContext(
            use_chat_history=False
        ),
        user_profile=UserProfile(
            user_id='123456789',
            user_name='小明'
        )
    )


# 对话准备部分已省略

api = init_client()
chat_param = build_chat_param()
res = api.chat(chat_param)
print(res.to_str())
{'code': 200,
 'data': {'choices': [{'messages': [{'content': '当然可以啦!浙江有很多好玩的地方哦!比如说西湖、千岛湖、普陀山等等。你可以去看看哦!',
                                     'finish_reason': 'stop',
                                     'role': 'assistant'}],
                       'stop_reason': 'stop'}],
          'context': {'is_save': False,
                      'model_request_id': 'e7cf3834-bdd8-9f00-8d31-093927c93dc8',
                      'request_id': 'e16b2f51aa30e458b22bd13454a670f2'},
          'usage': {'input_tokens': 796,
                    'output_tokens': 26,
                    'user_tokens': 18}},
 'request_id': 'e16b2f51aa30e458b22bd13454a670f2',
 'success': True}

角色管理

准备

from xingchen import Configuration, ApiClient, CharacterApiSub, CharacterCreateDTO, FileInfoVO, CharacterAdvancedConfig, \
    RepositoryInfo, Repository, CharacterPermissionConfig, CharacterQueryDTO, \
    CharacterQueryWhere, CharacterUpdateDTO
    

# 设置 host 和角色管理 api_instance
def init_client():
    configuration = Configuration(
        host="https://nlp.aliyuncs.com"
    )
    configuration.access_token = "{YOUR-API-KEY}"
    with ApiClient(configuration) as api_client:
        api_instance = CharacterApiSub(api_client)
    return api_instance

创建角色

# 角色管理准备部分已省略

api = init_client()
body = CharacterCreateDTO(
    name="美髯公关云长",
    avatar=FileInfoVO(
         filename="关云长.jpg",
         fileUrl="https://gw.alicdn.com/imgextra/i3/O1CN01iVuwX11jCXzNxM4v9_!!6000000004512-0-tps-3000-2920.jpg"
    ),
    introduction="满腔忠义的关云长",
    basicInformation="我们来玩一个角色扮演的游戏, 你是「满腔忠义的关云长」。",
    openingLine="我是「关云长」,很高心与你玩游戏",
    traits="请在对话时尽可能的展现你的性格、感情, 用文言文回答, 并使用古人的语气和用词。",
    chatExample="{{user}}:敢问阁下尊姓大名。\n{{char}}:吾姓关名羽,字长生,后改云长,河东解良人也。",
    type="virtual",
    chatObjective="我要关羽拜把子",
    roleTypes=["三国志"],
    advancedConfig=CharacterAdvancedConfig(
        isRealInfo=True,
        allowSendImage=True,
        realInfo="关云长",
        imageStyle="三国演义人物着装",
        allowSendAsr=True,
        asrStyle="关云长扮演者声音",
        isRealTime=True,
        shortTermMemoryRound=20,
        knowledge_bases=["fc80436eb092455fbfccd86bb51f1f80"], ##绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
    ),
    permConfig=CharacterPermissionConfig(
        allowApi=0,
        allowChat=0,
        isPublic=0,
    ),
)
result = api.create(character_create_dto=body)
print(result.data)

更新角色

# 角色管理准备部分已省略
    
api = init_client()
body = CharacterUpdateDTO(
    name="满腔忠义的关云长2",
    avatar=FileInfoVO(
        filename="关云长.jpg",
        fileUrl="https://gw.alicdn.com/imgextra/i3/O1CN01iVuwX11jCXzNxM4v9_!!6000000004512-0-tps-3000-2920.jpg"
    ),
    introduction="满腔忠义的关云长",
    basicInformation="我们来玩一个角色扮演的游戏, 你是「满腔忠义的关云长」",
    openingLine="我是「关云长」,很高心与你玩游戏1",
    traits="请在对话时尽可能的展现你的性格、感情, 用文言文回答, 并使用古人的语气和用词。",
    characterId="60fed853317f4c90a74c3776a4b071f7",
    roleTypes=["三国志"],
    permConfig=CharacterPermissionConfig(
        isPublic=1,
        allowChat=1,
        allowApi=1,
    ),
    advancedConfig=CharacterAdvancedConfig(
        isRealInfo=True,
        allowSendImage=True,
        realInfo="关云长",
        imageStyle="三国演义人物着装",
        allowSendAsr=True,
        asrStyle="关云长扮演者声音",
        isRealTime=True,
        shortTermMemoryRound=20,
        knowledge_bases=["fc80436eb092455fbfccd86bb51f1f80"], ##绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
    ),
)
result = api.update(character_update_dto=body)
print(result.data)

角色详情

# 角色管理准备部分已省略

    api = init_client()
    result = api.character_details(character_id="346a45cbb8674cbca0f6d155762e56fb")
    print(result)

角色查询

# 准备已省略
    
api = init_client()
body = CharacterQueryDTO(
    where=CharacterQueryWhere(
        # characterName="character_name_example",
        # roleTypes=["三国志"],
        scope="my"
    ),
    # orderBy=[
    #     "order_by_example"
    # ],
    pageNum=1,
    pageSize=4,
)
result = api.search(character_query_dto=body)
print(result.data)

删除角色

# 准备已省略

api = init_client()
character_id = "40c997c0520f459291c9b55cd6b1eb9c",
result = api.delete(character_id=character_id)
print(result.response.data)

对话历史

准备

from xingchen import Configuration, ApiClient, ChatMessageApiSub, ChatHistoryQueryDTO, ChatHistoryQueryWhere, \
    MessageRatingRequest, SysReminderRequest


def init_client():
    configuration = Configuration(
        host="https://nlp.aliyuncs.com"
    )
    configuration.access_token = "{YOUR-API-KEY}"
    with ApiClient(configuration) as api_client:
        api_instance = ChatMessageApiSub(api_client)
    return api_instance

对话历史查询

# 准备已省略
    
api = init_client()
body = ChatHistoryQueryDTO(
    where=ChatHistoryQueryWhere(
        characterId="40f70d5466e1429ba9aa755842b35d9f",
        bizUserId="123456789",
        sessionId="7ed48d9881b54ed49d6967be7be01743"
        # startTime="1970-01-01T00:00:00.00Z",
        # endTime="1970-01-01T00:00:00.00Z",
        # messageIds=[
        #     "e5bfc3c7809e47c5ac17181250adcf2b"
        # ],

    ),
    orderBy=[
        "gmtCreate desc"
    ],
    pageNum=1,
    pageSize=10
)

# 对话历史
result = api.chat_histories(chat_history_query_dto=body)
print(result.data)

对话历史评价

# 准备已省略

api = init_client()
body = MessageRatingRequest(
messageId="a4d8ae9dbcd54d9196cd20afeb7a3059",
rating=5,
)
result = api.rate_message(message_rating_request=body)
print(result.data)

系统推荐

# 准备已省略

api = init_client()
body = SysReminderRequest(
characterId="40f70d5466e1429ba9aa755842b35d9f",
content="最近为什么不理我啊?",
bizUserId="a8254bffd2a04d0c8ca29af4d7fc6bfc"
)
result = api.sys_reminder(sys_reminder_request=body)
print(result.data)