AI接口使用–阿里云百炼

AI接口使用–阿里云百炼

最近开发了一个抖音AI起名小程序,已经在抖音上线了,欢迎大家来使用。其中用到了 AI文本生成 功能,我用的是 阿里云百炼 提供的文本模型,分享一下使用方法。

打开抖音,扫二维码就可以打开。

第一步、获取API-Key

需要去阿里云百炼注册一个账号。

可以自行注册,网址:https://bailian.console.aliyun.com/?tab=app#/app-market/newTemplate

注册后,找到 API-Key 申请一个。之后和 阿里云百炼 平台通讯,就是通过这个 API-Key 标识的。

第二步、安装SDK

安装SDK。我使用python开发,安装了 DashScope 库就可以了,使用pip即可。

pip install -U dashscope

参考官方文档:https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=https%3A%2F%2Fhelp.aliyun.com%2Fdocument_detail%2F2712193.html

第三步、API调用

选定一个文本模型,按照接口格式开发即可。

参考官方文档:https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=https%3A%2F%2Fhelp.aliyun.com%2Fdocument_detail%2F2712576.html

代码如下:

# -*- coding: utf-8 -*-

import dashscope

#model="qwen-max"
#model="qwen-plus"
#model="deepseek-v3"
#model="qwen3-235b-a22b"
#model="qwen-plus-latest"
model="qwen-plus-2025-04-28"      # 这里的模型自己在平台选择
api_key="sk-xxxxxxxxxxxxxxxxxxxxxxxx"  # 这里替换你自己申请的API-Key

def tongyi_ask(sys_content, user_content, temperature=1.2) :

    messages = [
        {'role': 'system', 'content': sys_content},
        {'role': 'user', 'content': user_content}
        ]
    response = dashscope.Generation.call(
        api_key = api_key,
        model=model,
        messages=messages,
        result_format='message',
        enable_thinking=False,
        temperature=temperature
        )

    if 'output' in response :
        if 'choices' in response['output'] :
            if len(response['output']['choices']) >= 1:
                if 'message' in response['output']['choices'][0] :
                    if 'content' in response['output']['choices'][0]['message'] :
                        resp = response['output']['choices'][0]['message']['content']
                        # 去掉前缀
                        offset = resp.find("```json")
                        if offset > 0 :
                            resp = resp[offset+7:]
                            # 去掉后缀
                            offset = resp.find("```")
                            if offset > 0 :
                                resp = resp[:offset]
                        return resp

    return None


if __name__ == "__main__":
    
    resp = tongyi_ask("", "你是谁")
    print(resp)

第四步、测试

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注