SpringBoot 接入阿里云百炼(通入千问) 并实现流式输出内容

一:引入Maven依赖

<dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>broadscope-bailian-sdk-java</artifactId>
            <version>1.2.0</version>
</dependency>

二:编写阿里云百炼Client类

配置文件加入如下配置

相关参数请从阿里云百炼官网获取

yun:
  bailian:
    accessKeyId:  **************************
    accessKeySecret:  **************************
    agentKey:   **************************
    appId: **************************
@Component
public class BaiLianClient {
    @Resource
    private AlbaiLianConfig baiLianConfig;
    private AccessTokenClient accessTokenClient;
    @Resource
    private ChatCustomerInfoMapper chatCustomerInfoMapper;
    @PostConstruct
    public void init(){
        String accessKeyId = baiLianConfig.getAccessKeyId();
        String agentKey = baiLianConfig.getAgentKey();
        String accessKeySecret = baiLianConfig.getAccessKeySecret();
        accessTokenClient = new AccessTokenClient(accessKeyId,accessKeySecret,agentKey);
    }
    public Flux<CompletionsResponse> createStreamCompletion(ChatCustomerInfo chatCustomerInfo) {
        String content = chatCustomerInfo.getInfoContent();
        String token = accessTokenClient.getToken();
        BaiLianConfig config = new BaiLianConfig()
                .setApiKey(token);
        CompletionsRequest request = new CompletionsRequest()
                .setAppId(baiLianConfig.getAppId())
                .setPrompt(content)
                .setStream(true);
        ApplicationClient client = new ApplicationClient(config);
        chatCustomerInfoMapper.sendInfo(chatCustomerInfo.getUserId(),chatCustomerInfo.getInfoContent(),false);
        Flux<CompletionsResponse> flux = client.streamCompletions(request);
        return client.streamCompletions(request);
    }
}

三:编写Controller层

为了更快实现功能,本人只是简单调用回复消息接口,并将历史消息保存到数据库表中,具体复杂API请参考阿里云百炼官网手册,后端流式输入采用FLux实现,<

### 阿里云 DeepSeek-R1 模型流式输出调用方法 #### 准备工作 为了实现阿里云DeepSeek-R1模型的流式输出功能,需先完成环境配置和依赖安装。确保已注册登录阿里云账号,了相应的API权限和服务。 #### 安装SDK 使用Python SDK来简化与阿里云服务之间的交互。可以过pip工具轻松安装官方提供的软件开发包: ```bash pip install aliyun-python-sdk-core pip install aliyun-python-sdk-nlp-automl ``` #### 初始化客户端 创建NLP自学习平台(NLP AutoML)实例对象用于后续请求发送。设置访密钥ID(AccessKeyId),以及对应的AccessKeySecret参数[^1]。 ```python from aliyunsdkcore.client import AcsClient client = AcsClient('<your-access-key-id>', '<your-access-key-secret>', 'cn-hangzhou') ``` #### 构建请求体 定义具体的服务名称、版本号等必要字段,特别注意指定`stream=true`以启用流模式处理输数据流逐片返回结果而不是一次性获取整个响应内容。 ```python request = { "ServiceCode": "nlp_automl", "Version": "2020-07-08", "Action": "CallTextCompletionStream", # 假设这是支持流式的接口名 "ModelId": "<model_id>", # 替换成实际使用的模型ID "InputData": {"text": "你好"}, "Stream": True # 开启流式传输标志位 } ``` #### 发送异步请求 采用事件驱动的方式监听服务器推送过来的数据片段直到全部接收完毕为止。这里推荐利用asyncio库配合aiohttp或其他第三方异步HTTP库来进行高效发编程。 ```python import asyncio import aiohttp async def fetch_stream(session, url, params): async with session.post(url, json=params) as response: while True: chunk = await response.content.readany() if not chunk: break yield chunk.decode('utf-8') url = f'https://nlp-automl.cn-hangzhou.aliyuncs.com/api/v1/services/{request["ServiceCode"]}/actions/{request["Action"]}' async def main(): async with aiohttp.ClientSession() as session: async for message in fetch_stream(session, url, request): print(message) if __name__ == '__main__': loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close() ``` 上述代码展示了如何过Python脚本发起针对特定自然语言处理任务(如文本补全)的实时查询请求,逐步展示由远程主机传回的信息单元。需要注意的是,在正式环境中应当妥善保管认证凭证信息,遵循安全最佳实践指南。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值