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="40f70d5466e1429ba9aa755842b35d9f"
        ),
        model_parameters=ModelParameters(
            seed=1683806810,
            incrementalOutput=False
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='可以详细介绍浙江有哪些好玩的地方吗?'
            )
        ],
        context=ChatContext(
            use_chat_history=True
        ),
        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_async()
test_chat_sync()

对话

准备

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="40f70d5466e1429ba9aa755842b35d9f"
        ),
        model_parameters=ModelParameters(
            seed=1683806810,
            incrementalOutput=False
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='可以详细介绍浙江有哪些好玩的地方吗?'
            )
        ],
        context=ChatContext(
            use_chat_history=True
        ),
        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)
非增量输出
我今年
我今年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="40f70d5466e1429ba9aa755842b35d9f"
        ),
        model_parameters=ModelParameters(
            seed=1683806810,
            incrementalOutput=False
        ),
        messages=[
            Message(
                name='小明',
                role='user',
                content='可以详细介绍浙江有哪些好玩的地方吗?'
            )
        ],
        context=ChatContext(
            use_chat_history=True
        ),
        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

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"], ##绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
        long_term_memories=[
                    LongTermMemory(
                        enabled=True,
                        memory_type="kv",
                        kv_memory_configs=[
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="爱好"
                            ),
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="特长"
                            ),
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="工作"
                            )
                        ]
                    )
                ],
                platform_plugins=[
                    TextToImagePlugin(
                        enabled=True,
                        image_style="auto",
                        positive_desc="二次元,彩色1",
                        negative_desc="多头多手指,多手多脚1"
                    ),
                    RejectAnswerPlugin(
                        reject_conditions=[
                            RejectCondition(
                                enabled=True,
                                condition_type="reject_rule",
                                keywords=[
                                    Keyword(
                                        value="test"
                                    )
                                ]
                            ),
                            RejectCondition(
                                enabled=True,
                                condition_type="passive_rule",
                                keywords=[
                                    Keyword(
                                        value="test"
                                    )
                                ]
                            ),
                            RejectCondition(
                                enabled=True,
                                condition_type="knowledge_domain_rule",
                                sub_reject_condition=RejectCondition(
                                    enabled=True,
                                    condition_type="ancient",
                                    keywords=[
                                        Keyword(
                                            value="明朝"
                                        )
                                    ]
                                )
                            )
                        ]
                    )
                ]
    ),
    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"], ##绑定知识库,需注意有权限校验,必须是调用者在星辰创建的知识库
        long_term_memories=[
                    LongTermMemory(
                        enabled=True,
                        memory_type="kv",
                        kv_memory_configs=[
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="爱好"
                            ),
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="特长"
                            ),
                            KVMemoryConfig(
                                enabled=True,
                                memory_text="工作"
                            )
                        ]
                    )
                ],
                platform_plugins=[
                    TextToImagePlugin(
                        enabled=True,
                        image_style="auto",
                        positive_desc="二次元,彩色1",
                        negative_desc="多头多手指,多手多脚1"
                    ),
                    RejectAnswerPlugin(
                        reject_conditions=[
                            RejectCondition(
                                enabled=True,
                                condition_type="reject_rule",
                                keywords=[
                                    Keyword(
                                        value="test"
                                    )
                                ]
                            ),
                            RejectCondition(
                                enabled=True,
                                condition_type="passive_rule",
                                keywords=[
                                    Keyword(
                                        value="test"
                                    )
                                ]
                            ),
                            RejectCondition(
                                enabled=True,
                                condition_type="knowledge_domain_rule",
                                sub_reject_condition=RejectCondition(
                                    enabled=True,
                                    condition_type="ancient",
                                    keywords=[
                                        Keyword(
                                            value="明朝"
                                        )
                                    ]
                                )
                            )
                        ]
                    )
                ]
    ),
)
result = api.update(character_update_dto=body)
print(result.data)

角色详情

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

api = init_client()
result = api.character_details(character_id="40f70d5466e1429ba9aa755842b35d9f")
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 = "40f70d5466e1429ba9aa755842b35d9f",
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_message1(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)

重置对话(清除上下文)

# 准备已省略

api = init_client()
body = ResetChatHistoryRequest(
    characterId="40f70d5466e1429ba9aa755842b35d9f",
    userId="123456789"
)
result = api.reset_chat_history(request=body)
print(result)

其他

角色描述自动生成

# 准备
from xingchen import Configuration, ApiClient, CharacterApiSub

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 = CharacterDescGeneratedRequest(
    type="file",
    file_url="https://lang.alicdn.com/xingchen/guanyu.txt",
    text="关云长",
    file_name="test.txt",
    model_parameter=ModelParameters(
        model_name="xingchen-base"
    )
)
result = api.auto_generate_desc(character_desc_generate_request=body)
print(result)

excel转docx文件上传

# 准备
from xingchen import Configuration, ApiClient, CommonApiSub

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

    
api_instance = self.init_client()
body = FileConvertRequest(
    type="excelToDocx",
    source_url="https://lang.alicdn.com/xingchen/%E6%B5%8B%E8%AF%95.xlsx"
)
result = api_instance.file_convert(body)
print(result)

excel转docx文件结果下载

# 准备
from xingchen import Configuration, ApiClient, CommonApiSub

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


api_instance = init_client()
result = api_instance.file_convert_result(task_id=66647)
print(result)

终止对话

# 准备
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


api = self.init_client()
body = StopChatRequest(
    request_id='123456789',
    content='测试终止保存历史数据'
)
result = api.stop_chat(stop_chat_request=body)
print(result)

轮询获取图片

# 准备
from xingchen import Configuration, ApiClient, ChatMessageApiSub, ChatHistoryQueryDTO, ChatHistoryQueryWhere, \
    MessageRatingRequest, SysReminderRequest, ResetChatHistoryRequest
    
def init_client():
    configuration = Configuration(
        host="https://nlp.aliyuncs.com",
        # host="https://pre-fastagi-gateway.alibaba-inc.com", # 预发
        # host="http://11.123.36.119:7001",
        api_version="v2"
    )
    configuration.access_token = "token"
    with ApiClient(configuration) as api_client:
        api_instance = ChatMessageApiSub(api_client)
    return api_instance

 def test_polling_image_detail(self):
    api = self.init_client()
    result = api.polling_image_detail(message_id="dd5a632b6ec748feafe14f0feafdd578", user_id=165739)
    print(result)