HarmonyOS NEXT鸿蒙开发 ArkTS:openai 调用阿里云大模型 作者:马育民 • 2025-12-17 17:54 • 阅读:10001 # 介绍 OpenAI 请求工具库,基本保留原 npm 库 TypeScript 定义。 ### 官方API ``` https://ohpm.openharmony.cn/#/cn/detail/@iuroc%2Fopenai/v/1.0.0 ``` # 安装使用 ``` ohpm install @iuroc/openai ``` # 使用示例 ``` import { OpenAI } from '@iuroc/openai' const openai = new OpenAI({ apiKey: 'sk-xxxx', baseURL: 'https://api.openai.com/v1' }) const result = openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [ { role: 'user', content: 'hello' } ] }) const response = result.response const session = result.session ``` ### 等待请求完成 ``` // Promise 方式 await response // Callback 方式 response.then(() => { }) ``` ### 终止请求 ``` session.cancel() ``` # 流式输出 ``` const onData: OnDataCallback = chunks => { const newContent = chunks.map(chunk => chunk.choices[0].delta.content).join('') console.log(newContent) } const result = openai.chat.completions.create({ model: 'gpt-4o-mini', messages: [ { role: 'user', content: 'hello' } ], stream: true }, onData) ``` # 案例 ### 安装 markdown 本例子使用第三方 **markdown** 组件,可以正常显示大模型返回的 markdown内容 安装: ``` ohpm install @luvi/lv-markdown-in ``` ### 阿里百炼 api网址如下: https://bailian.console.aliyun.com/?tab=api#/api/?type=model&url=2712576 需要注册、申请api key ### 代码 **提示:**将阿里百炼API Key填到下面 `apiKey` 中 ``` import { OpenAI } from '@iuroc/openai' import { Markdown } from '@luvi/lv-markdown-in' const openai = new OpenAI( { // 若没有配置环境变量,请用百炼API Key将下行替换为:apiKey: "sk-xxx", apiKey: "", baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1" } ); const TAG = "HealthPage-------" @Entry @Component struct HealthPage { @State message: string = ''; @State inputContent: string = '冬季如何补气血'; @State btnEnabled:boolean = true; build() { Column(){ Text("我是您的健康小助手,有什么问题:") .width("100%") .margin({ top:20 }) TextArea({ text:this.inputContent }) .height(100) .margin({ top:5 }) Row() { Blank() Button("发送") .onClick(async () => { this.send() }) .enabled(this.btnEnabled) } .width("100%") .margin({ top:10 }) Scroll() { Markdown({ text: this.message }) } .margin({ top: 10 }) } .height("70%") .padding({ left:10, right:10, }) } async send(){ console.log(TAG,"send 开始----------") this.btnEnabled = false const completion = openai.chat.completions.create({ model: "qwen-plus", //此处以qwen-plus为例,可按需更换模型名称。模型列表:https://help.aliyun.com/zh/model-studio/getting-started/models messages: [ { role: "system", content: "你是养生专家" }, { role: "user", content: this.inputContent } ], }); const resp = await completion.response const session = completion.session console.log(TAG,"send 结束----------") this.btnEnabled = true // console.log(TAG,JSON.stringify(resp)) const json = resp.toJSON() if(json!=null) { // console.log(TAG, "json---------",json['choices'][0].message.content) this.message = json['choices'][0].message.content // console.log(TAG,"message--",this.message) } } } export default HealthPage ``` 原文出处:http://www.malaoshi.top/show_1GW2QL9E6nnf.html