Python SDK

更新时间:

环境依赖

1.Python>=3.7

安装

pip install 直接通过git安装

pip install xingchen==1.1.5

工具调用请求示例

from xingchen import Configuration, ApiClient, AcACompletionApiSub, \
    AcACompletionReq, AcAReqMessage, AcAReqTool, AcAReqFunction


def build_chat_param_fc():
    return AcACompletionReq(
        messages=[
            AcAReqMessage(
                name="小义",
                role="system",
                content="你是一个对话Agent,你可以访问以下API,请自动规划当前最必要的API调用,尽你所能为用户提供帮助。"
            ),
            AcAReqMessage(
                name="小明",
                role="user",
                content="今天杭州天气怎么样"
            )
        ],
        model="xingchen-plus-v2",
        user="completion-tester01",
        temperature=0.9,
        max_tokens=1000,
        stream=True,
        tools=[
            AcAReqTool(
                id="001",
                type="function",
                function=AcAReqFunction(
                    name="weather",
                    description="通过调用天气预报API获取当地天气预报信息通过调用天气预报API获取当地天气预报信息",
                    parameters={
                        "type": "object",
                        "properties": {
                            "type": "object",
                            "properties":
                                {
                                    "location":
                                        {
                                            "type": "string",
                                            "description": "地点"
                                        },
                                    "format":
                                        {
                                            "type": "string",
                                            "enum":
                                                [
                                                    "celsius",
                                                    "fahrenheit"
                                                ],
                                            "description": "温度单位"
                                        }
                                },
                            "required":
                                [
                                    "location",
                                    "format"
                                ]
                        }
                    }
                )
            )
        ]
    )


class Test(unittest.TestCase):

    @staticmethod
    def init_client():
        configuration = Configuration(
            host="https://nlp.aliyuncs.com"  # 预发
        )
        configuration.access_token = "{YOUR_API_KEY}"  # 预发
        with ApiClient(configuration) as api_client:
            api_instance = AcACompletionApiSub(api_client)
        return api_instance

    def test_completion_sync(self):
        """
        获取函数调用参数
        :return:
        """
        api = self.init_client()

        chat_param = build_chat_param_fc()
        chat_param.stream = False
        res = api.completions(
            chat_req_params=chat_param
        )
        print(res.to_str())

    def test_completion_async(self):
        # 用户对话
        api = self.init_client()

        chat_param = build_chat_param_fc()

        _headers = {
            'X-AcA-DataInspection': 'enable'
        }

        responses = api.completions(
            chat_req_params=chat_param,
            _headers=_headers
        )
        for res in responses:
            print(res.to_dict())
            

工具调用返回示例

{'choices': [{'finish_reason': 'stop',
              'index': 1,
              'message': {'content': '',
                          'name': None,
                          'role': 'assistant',
                          'tool_calls': [{'function': {'arguments': '{"format":"celsius","location":"杭州"}',
                                                       'name': 'weather'},
                                          'id': '001',
                                          'type': 'function'}]}}],
 'created': 1715238326,
 'id': None,
 'model': 'xingchen-plus-v2',
 'usage': {'completion_tokens': 307, 'prompt_tokens': 0, 'total_tokens': 307}
}

工具生成结果对话请求示例

from xingchen import Configuration, ApiClient, AcACompletionApiSub, \
    AcACompletionReq, AcAReqMessage, AcAReqTool, AcAReqFunction


def build_chat_param_fc_invoker():
    return AcACompletionReq(
        messages=[
            AcAReqMessage(
                name="小义",
                role="system",
                content="你是一个对话Agent,你可以访问以下API,请自动规划当前最必要的API调用,尽你所能为用户提供帮助。"
            ),
            AcAReqMessage(
                name="小明",
                role="user",
                content="今天杭州天气怎么样"
            ),
            AcAReqMessage(
                name="小义",
                role="assistant",
                content="好的,我先调用天气预报API获取当地天气预报信息。",
                tool_calls=[
                    {
                        "id": "001",
                        "type": "function",
                        "function": {
                            "name": "weather",
                            "arguments": "{\"location\": \"杭州\", \"format\": \"celsius\"}"
                        }
                    }
                ]
            ),
            AcAReqMessage(
                tool_call_id="001",
                role="tool",
                content="{\"location\": \"杭州\", \"temperature\": \"25\", \"unit\": \"celsius\", \"forecast\": \"sunny\"}"
            )
        ],
        model="xingchen-plus-v2",
        user="completion-tester01",
        temperature=0.9,
        max_tokens=1000,
        stream=True,
        tools=[
            AcAReqTool(
                id="001",
                type="function",
                function=AcAReqFunction(
                    name="weather",
                    description="通过调用天气预报API获取当地天气预报信息通过调用天气预报API获取当地天气预报信息",
                    parameters={
                        "type": "object",
                        "properties": {
                            "type": "object",
                            "properties":
                                {
                                    "location":
                                        {
                                            "type": "string",
                                            "description": "地点"
                                        },
                                    "format":
                                        {
                                            "type": "string",
                                            "enum":
                                                [
                                                    "celsius",
                                                    "fahrenheit"
                                                ],
                                            "description": "温度单位"
                                        }
                                },
                            "required":
                                [
                                    "location",
                                    "format"
                                ]
                        }
                    }
                )
            )
        ]
    )


class Test(unittest.TestCase):

    @staticmethod
    def init_client():
        configuration = Configuration(
            host="https://nlp.aliyuncs.com"  # 预发
        )
        configuration.access_token = "{YOUR_API_KEY}"  # 预发
        with ApiClient(configuration) as api_client:
            api_instance = AcACompletionApiSub(api_client)
        return api_instance


    def test_completion_invoke_sync(self):
        """
        对函数调用结果进行润色
        :return:
        """
        api = self.init_client()

        chat_param = build_chat_param_fc_invoker()
        chat_param.stream = False
        res = api.completions(
            chat_req_params=chat_param
        )
        print(res.to_str())

    def test_completion_invoke_async(self):
        # 用户对话
        api = self.init_client()

        chat_param = build_chat_param_fc_invoker()

        _headers = {
            'X-AcA-DataInspection': 'enable'
        }

        responses = api.completions(
            chat_req_params=chat_param,
            _headers=_headers
        )
        for res in responses:
            print(res.to_dict())

工具生成结果对话返回示例

{'id': 'c7e99607ef2e334d8fc4c301dbdedd31', 'created': 1715239522, 'model': 'xingchen-plus-v2', 'choices': [{'index': 1, 'finish_reason': 'null', 'message': {'role': 'assistant', 'content': '今天杭州', 'tool_calls': []}}], 'usage': {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}}
{'id': 'c7e99607ef2e334d8fc4c301dbdedd31', 'created': 1715239523, 'model': 'xingchen-plus-v2', 'choices': [{'index': 1, 'finish_reason': 'null', 'message': {'role': 'assistant', 'content': '今天杭州的', 'tool_calls': []}}], 'usage': {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}}
{'id': 'c7e99607ef2e334d8fc4c301dbdedd31', 'created': 1715239523, 'model': 'xingchen-plus-v2', 'choices': [{'index': 1, 'finish_reason': 'null', 'message': {'role': 'assistant', 'content': '今天杭州的天气预报是晴天', 'tool_calls': []}}], 'usage': {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}}
{'id': 'c7e99607ef2e334d8fc4c301dbdedd31', 'created': 1715239523, 'model': 'xingchen-plus-v2', 'choices': [{'index': 1, 'finish_reason': 'null', 'message': {'role': 'assistant', 'content': '今天杭州的天气预报是晴天,气温25摄氏度。', 'tool_calls': []}}], 'usage': {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}}
{'id': 'c7e99607ef2e334d8fc4c301dbdedd31', 'created': 1715239523, 'model': 'xingchen-plus-v2', 'choices': [{'index': 1, 'finish_reason': 'stop', 'message': {'role': 'assistant', 'content': '今天杭州的天气预报是晴天,气温25摄氏度。', 'tool_calls': []}}], 'usage': {'prompt_tokens': 178, 'completion_tokens': 16, 'total_tokens': 224}}