运行环境(后面附有api9版本,可修改后在harmonyos4设备上运行)
dayu200:4.0.10.16
sdk:4.0.10.15
ide:4.0.600
在dayu200:4.0.10.16上运行一、创建应用1.点击file->new file->create progect
2.选择模版
【openharmony】empty ability
3.填写项目名,wenxintalk,应用包名com.wenxintalk,应用存储位置xxx(不要有中文,特殊字符,空格)
compile sdk10,model :stage
device type 默认就可以。
node,建议16.20.1
完成以上配置以后点击finish
4.选择在新窗口打开,等待依赖加载完毕。如图所示。
如果大家加载依赖报错的话,检查自己的网络。
二、运行helloword1.给开发板供电,并连接开发板到电脑,如图所示
2.签名
签名的步骤:
点击file->project struct
点击apply或者ok就可以,。
现在点击按钮运行项目。
控制台打印信息
01/12 16:13:40: launching com.myapplication$ hdc uninstall com.myapplication$ hdc shell mkdir data/local/tmp/39ca9a16978647c98d8ac8bdf4a45279$ hdc file send e:studyharmonyosprojectwenxintalkentrybuilddefaultoutputsdefaultentry-default-signed.hap data/local/tmp/39ca9a16978647c98d8ac8bdf4a45279$ hdc shell bm install -p data/local/tmp/39ca9a16978647c98d8ac8bdf4a45279 $ hdc shell rm -rf data/local/tmp/39ca9a16978647c98d8ac8bdf4a45279$ hdc shell aa start -a entryability -b com.myapplication证明项目已经成功运行在开发板上。
如果报错
01/09 14:38:39: install failed: error: failed to install bundle.code:9568320error: no signature file.open signing configserror while deploy hap则需要去签名
三、修改图标和名称修改应用图标和名称:目录在appscope/app.json5
{ app: { bundlename: com.myapplication, vendor: example, versioncode: 1000000, versionname: 1.0.1, icon: $media:iconai, label: $string:app_name }}修改完毕之后如图所示
修改成功之后,如图所示
打开方式,在设置-应用管理一栏。
修改桌面图标和名称修改src/main/module.json5中如图所示的label和icon。
我们修改label的时候,修改中文目录下的就可以
{ module: { requestpermissions: [ { name: ohos.permission.internet } ], name: entry, type: entry, description: $string:module_desc, mainelement: entryability, devicetypes: [ default, tablet ], deliverywithinstall: true, installationfree: false, pages: $profile:main_pages, abilities: [ { name: entryability, srcentry: ./ets/entryability/entryability.ets, description: $string:entryability_desc, icon: $media:iconai, label: $string:entryability_label, startwindowicon: $media:starticon, startwindowbackground: $color:start_window_background, exported: true, skills: [ { entities: [ entity.system.home ], actions: [ action.system.home ] } ] } ] }}
修改中文目录的即可
修改结果如下
四、添加相关权限因为需要用到网络数据,所以添加initent权限。
在src/main/module.json5中modele中添加配置,然后按sync就可以。
requestpermissions: [{ name: ohos.permission.internet }],
五、定义数据模型1.在ets目录下新建model文件夹
2.新建ts file
export class wenxinreturn { id: string = object: string = created: string = result: string = is_truncated: boolean = false need_clear_history: boolean = false finish_reason: string = usage: usage = new usage()}export class usage { prompt_tokens: number = 0 completion_tokens: number = 0 total_tokens: number = 0}export class msgoutput { content: string = }export class msginput { id: string = role: string = content: string = }六、加载网络数据接口说明准备好数据,
接口地址:[ https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro]
请求方法:post
请求参数:
header参数名称值
content-type application/json
query参数名称类型必填描述
access_token string 是 通过api key和secret key获取的access_token,参考access token获取
body参数名称类型必填描述
messages list(message) 是 聊天上下文信息。说明: (1)messages成员不能为空,1个成员表示单轮对话,多个成员表示多轮对话 (2)最后一个message为当前请求的信息,前面的message为历史对话信息 (3)必须为奇数个成员,成员中message的role必须依次为user(or function)、assistant (4)最后一个message的content长度(即此轮对话的问题)不能超过2400 token;如果messages中content总长度大于2400 token,系统会依次遗忘最早的历史会话,直到content的总长度不超过2400 token
temperature float 否 说明: (1)较高的数值会使输出更加随机,而较低的数值会使其更加集中和确定 (2)默认0.95,范围 (0, 1.0],不能为0 (3)建议该参数和top_p只设置1个 (4)建议top_p和temperature不要同时更改
top_p float 否 说明: (1)影响输出文本的多样性,取值越大,生成文本的多样性越强 (2)默认0.8,取值范围 [0, 1.0] (3)建议该参数和temperature只设置1个 (4)建议top_p和temperature不要同时更改
penalty_score float 否 通过对已生成的token增加惩罚,减少重复生成的现象。说明: (1)值越大表示惩罚越大 (2)默认1.0,取值范围:[1.0, 2.0]
stream bool 否 是否以流式接口的形式返回数据,默认false
system string 否 模型人设,主要用于人设设定,例如,你是xxx公司制作的ai助手,说明: (1)长度限制1024个字符 (2)如果使用functions参数,不支持设定人设system
user_id string 否 表示最终用户的唯一标识符,可以监视和检测滥用行为,防止接口恶意调用
在这个wenxintalk app中我们主要使用参数messages
测试接口测试如图所示
返回数据
{ id: as-7gxj35bftb, object: chat.completion, created: 1705068746, result: 您好,我是文心一言,英文名是ernie bot。我能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。, is_truncated: false, need_clear_history: false, finish_reason: normal, usage: { prompt_tokens: 3, completion_tokens: 33, total_tokens: 36 }}创建http请求1.导入http模块
import http from '@ohos.net.http';import { businesserror } from '@ohos.base';2.创建createhttp
let httprequest = http.createhttp();3.填写http地址
httprequest.request( `https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=${access_token}`, { method: http.requestmethod.post, header: [{ 'content-type': 'application/json' }], extradata: { messages: msgarray } }4.对网络数据的处理
if (!err) { let msgreturn: wenxinreturn = json.parse(data.result.tostring()) this.msgresult.content = msgreturn.result let msgin: msginput = new msginput() msgin.role = assistant //文心一言返回的结果中令role为assistant msgin.content = this.msgresult.content msgin.id = this.msgarray.length.tostring() //id作为msgarray中的标识,用以后续循环渲染 this.msgarray.push(msgin) //将文心一言返回的结果同样作为参数加入到msgarray的末尾 httprequest.destroy(); } else { this.message = json.stringify(err) console.error('error:' + json.stringify(err)); httprequest.off('headersreceive'); // 当该请求使用完毕时,调用destroy方法主动销毁 httprequest.destroy(); }完成以上配置以后
5.在应用程序里测试网络请求
build() { column() { button(测试网络请求).onclick(() = > { this.httpdata() }) }.width(100%).height(100%).justifycontent(flexalign.center) }}如图所示
测试成功
如果2300006错误码,请检查网络
如果201错误码,请检查module.json中网络权限是否配置!
七、ui数据获取到之后,我们就剩在页面上显示了。
首页u i布局如图所示。
build() { column() { column() { scroll() { column() { foreach(this.msgarray, (item: msginput, index: number) = > { if (item.role == user) { row() { text(item.content) .width(50%) .padding(15.5) .backgroundcolor(#95ec69) .borderradius(4) image($r(app.media.user)) .backgroundcolor(color.white) .objectfit(imagefit.fill) .width(50) .height(50) .borderradius(4) .margin({ left: 8, right: 8 }) } .margin({ top: index === 0 ? 0 : 12 }) .width(100%) .alignitems(verticalalign.top) .justifycontent(flexalign.end) } else if (item.role == assistant) { row() { image($r(app.media.iconai)) .backgroundcolor(color.white) .objectfit(imagefit.fill) .width(50) .height(50) .borderradius(4) .margin({ left: 8, right: 8 }) text(item.content) .width(50%) .padding(15.5) .backgroundcolor(color.white) .borderradius(4) .margin({ right: 0 }) } .margin({ top: index === 0 ? 0 : 12 }) .width(100%) .alignitems(verticalalign.top) .justifycontent(flexalign.start) } }, (item: msginput) = > item.id) //循环渲染时,键值匹配规则使用item.id } .padding({ top: 12, bottom: 12 }) } .width(100%) } .backgroundcolor(#ededed) .layoutweight(1) row() { textinput({ placeholder: 来和文心一言聊天吧, text: this.message }) .backgroundcolor(color.white) .layoutweight(8) .height(60) .onchange((msg: string) = > { this.message = msg }) .margin({ top: 10, bottom: 10, left: 4, right: 4 }) button(提交) .margin(4) .layoutweight(2) .onclick(() = > { let msgin: msginput = new msginput() msgin.id = this.msgarray.length.tostring() msgin.role = user msgin.content = this.message this.msgarray.push(msgin) this.httpdata(this.msgarray) this.message = }) } .backgroundcolor(#f7f7f7) } .width(100%) .height(100%) .justifycontent(flexalign.spacebetween) }}
八、完整源码import { msginput, msgoutput, wenxinreturn } from '../model/wexxinclass';import http from '@ohos.net.http';import { businesserror } from '@ohos.base';@entry@componentstruct index { @state message: string = 'hello world'; @state wxreturn: wenxinreturn = new wenxinreturn() @state msgresult: msgoutput = new msgoutput() @state msginputsample: msginput = new msginput() @state msgarray: array = [] abouttoappear() { this.message = 请介绍一下你自己 } httpdata(msgarray: array) { let httprequest = http.createhttp(); httprequest.request( https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token=24.c8909e4016b8a223464e02f463f1d1ac.2592000.1707464478.282335-46746495, { method: http.requestmethod.post, header: [{ 'content-type': 'application/json' }], extradata: { messages: msgarray } }, (err: businesserror, data: http.httpresponse) = > { if (!err) { let msgreturn: wenxinreturn = json.parse(data.result.tostring()) this.msgresult.content = msgreturn.result let msgin: msginput = new msginput() msgin.role = assistant msgin.content = this.msgresult.content msgin.id = this.msgarray.length.tostring() this.msgarray.push(msgin) httprequest.destroy(); } else { this.message = json.stringify(err) console.error('error:' + json.stringify(err)); httprequest.off('headersreceive'); // 当该请求使用完毕时,调用destroy方法主动销毁 httprequest.destroy(); } } ) } build() { column() { column() { scroll() { column() { foreach(this.msgarray, (item: msginput, index: number) = > { if (item.role == user) { row() { text(item.content) .width(50%) .padding(15.5) .backgroundcolor(#95ec69) .borderradius(4) image($r(app.media.user)) .backgroundcolor(color.white) .objectfit(imagefit.fill) .width(50) .height(50) .borderradius(4) .margin({ left: 8, right: 8 }) } .margin({ top: index === 0 ? 0 : 12 }) .width(100%) .alignitems(verticalalign.top) .justifycontent(flexalign.end) } else if (item.role == assistant) { row() { image($r(app.media.iconai)) .backgroundcolor(color.white) .objectfit(imagefit.fill) .width(50) .height(50) .borderradius(4) .margin({ left: 8, right: 8 }) text(item.content) .width(50%) .padding(15.5) .backgroundcolor(color.white) .borderradius(4) .margin({ right: 0 }) } .margin({ top: index === 0 ? 0 : 12 }) .width(100%) .alignitems(verticalalign.top) .justifycontent(flexalign.start) } }, (item: msginput) = > item.id) } .padding({ top: 12, bottom: 12 }) } .width(100%) } .backgroundcolor(#ededed) .layoutweight(1) row() { textinput({ placeholder: 来和文心一言聊天吧, text: this.message }) .backgroundcolor(color.white) .layoutweight(8) .height(60) .onchange((msg: string) = > { this.message = msg }) .margin({ top: 10, bottom: 10, left: 4, right: 4 }) button(提交) .margin(4) .layoutweight(2) .onclick(() = > { let msgin: msginput = new msginput() msgin.id = this.msgarray.length.tostring() msgin.role = user msgin.content = this.message this.msgarray.push(msgin) this.httpdata(this.msgarray) this.message = }) } .backgroundcolor(#f7f7f7) } .width(100%) .height(100%) .justifycontent(flexalign.spacebetween) }}在harmonyos 4.0设备上运行(主要介绍与在openharmony中开发时的不同,相同点不在赘述)
运行环境huawei mate 40 : harmonyos 4.0.0
sdk:3.1.0(api 9)
ide:4.0.600
一、在创建应用时选择第一个如图
二、签名签名时选择support harmonyos
需要登录华为账号后继续签名
三、注释掉源码中不支持api 9的部分
网络声明时直接使用即可
其余部分与在开发板上运行都相同,直接运行即可
九、总结本文我们学习使用了基本组件的使用,网络请求以及状态管理,使用了foreach循环渲染来构建对话界面。并且在harmonyos设备上成功运行, 更多的鸿蒙开发实战学习,可以前往我的主页学习更多,下面分享鸿蒙的开发知识体系曲线图 :
鸿蒙openharmony技术进阶包看主页
十、faq2300006 域名解析失败错误信息
couldn’t resolve host name.
错误描述
服务器的域名无法解析。
可能原因
1.传入的服务器的url不正确。
2.网络不通畅。
处理步骤
1.请检查输入的服务器的url是否合理。
2.请检查网络连接情况
201错误码检查moudle.json5的网络权限是否添加
5G与VR的组合将为我们的生活带来什么影响
5G迎来黄金十年,接下来应该如何发展?
“中科丰元研究院”将以研发与产业化先进锂离子电池正极材料为目的
LED显示屏具备哪一些优势
传欧普有意收购TRILUX 估值约39亿
鸿蒙开发实战-手写文心一言AI对话APP
今日头条5G手机用户数据显示 华为Mate系列成为最受关注的5G手机
简单介绍SMT工艺中常用的两种贴片胶类型
施工升降机减速器齿轮链条的常见故障分析与解决
荣耀9什么时候上市?荣耀9最新消息:双手难敌四拳?6月中旬揭晓,荣耀9将直接对飙小米6!
盖范推出首款硬件智能绘画机器人
良好的PCB设计要点
咸鱼理财与易保全联手,让数据安全全面升级
华为畅享系列新品蓄势待发 新全面屏形态+旗舰配色海报吸睛
定制锂电池组的好处?18650锂电池组和21700锂电池组有什么不一样?
工业智能网关数据采集有什么需要注意的
商用笔记本Air Book, 职场必备
基于solidity的智能合约在tron网络异步调用怎样来实现
稳定币市场将是一个价值千亿美金的市场
区块链游戏“DreamGame”到底是凭借什么如此火爆的呢?