当前位置: 首页 > news >正文

Unity之使用火山引擎实现文字提问流式回复

文字提问

设置参数apiKey
调用Request方法,传入对话内容
注册事件,接收回复内容

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.Networking;/// <summary>/// 文本提问/// </summary>publicclassTextQuestions:MonoBehaviour{stringbaseUrl="https://ark.cn-beijing.volces.com/api/v3/chat/completions";stringapiKey="";[Header("模型")][SerializeField]stringmodel="doubao-seed-2-0-code-preview-260215";[Header("深度思考")][SerializeField]stringthinking="disabled";[Header("模型回答最大长度(单位token)")][SerializeField]intmaxTokens=4096;[Header("思考消耗")][SerializeField]stringreasoningEffort="minimal";publiceventAction<string,bool>onReceive;publiceventActiononCompleted;publiceventActionOnError;voidOnReceive(stringcontent){varrespone=JsonUtility.FromJson<ResponeChatMessage>(content);onReceive?.Invoke(respone.choices[0].delta.content,respone.choices[0].finish_reason=="stop");}voidOnCompleted(){onCompleted?.Invoke();}publicvoidRequest(List<Message>messages){RequestChatrequestMessages=newRequestChat{messages=messages,model=model,thinking=newThinkingType(){type=thinking,},max_tokens=maxTokens,reasoning_effort=reasoningEffort,};stringjsonData=JsonUtility.ToJson(requestMessages);StartCoroutine(PostChat(jsonData));}IEnumeratorPostChat(stringjsonData){using(UnityWebRequestrequest=newUnityWebRequest(baseUrl,UnityWebRequest.kHttpVerbPOST)){byte[]bodyRaw=System.Text.Encoding.UTF8.GetBytes(jsonData);request.uploadHandler=newUploadHandlerRaw(bodyRaw);vartTSDownload=newTTSDownload();tTSDownload.OnObjectReceived+=OnReceive;tTSDownload.OnComplete+=OnCompleted;request.downloadHandler=tTSDownload;request.SetRequestHeader("Content-Type","application/json");request.SetRequestHeader("Authorization","Bearer "+apiKey);yieldreturnrequest.SendWebRequest();if(request.result!=UnityWebRequest.Result.Success){Debug.LogError("请求失败:"+request.error);OnError?.Invoke();}tTSDownload.OnObjectReceived-=OnReceive;tTSDownload.OnComplete-=OnCompleted;}}}[Serializable]publicclassRequestChat{publicstringmodel;publicList<Message>messages;publicThinkingTypethinking;publicintmax_tokens;publicstringreasoning_effort;publicboolstream=true;}[Serializable]publicclassThinkingType{publicstringtype;}[Serializable]publicclassMessage{publicstringrole;publicstringcontent;publicstringthinking;}[Serializable]publicclassResponeChatMessage{publicChoices[]choices;}[Serializable]publicclassChoices{publicMessageDeltadelta;publicstringfinish_reason;publicintindex;}[Serializable]publicclassMessageDelta{publicstringcontent;publicstringrole;}

拓展DownloadHandler

usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Text;usingUnityEngine;usingUnityEngine.Networking;publicclassTTSDownload:DownloadHandlerScript{privateStringBuilderbuffer=newStringBuilder();publiceventAction<string>OnObjectReceived;publiceventActionOnComplete;publicTTSDownload():base(newbyte[4096]){}protectedoverrideboolReceiveData(byte[]data,intdataLength){stringchunk=Encoding.UTF8.GetString(data,0,dataLength);buffer.Append(chunk);ProcessBuffer();returntrue;}privatevoidProcessBuffer(){stringcontent=buffer.ToString();intsplitStartIndex=-1;intbraceCount=0;intlastProcessed=0;for(inti=0;i<content.Length;i++){if(content[i]=='{'){if(braceCount==0)splitStartIndex=i;braceCount++;}elseif(content[i]=='}'){braceCount--;if(braceCount==0&&splitStartIndex!=-1){stringobj=content.Substring(splitStartIndex,i-splitStartIndex+1);OnObjectReceived?.Invoke(obj);splitStartIndex=-1;lastProcessed=i+1;}}}if(lastProcessed>0)buffer.Remove(0,lastProcessed);}protectedoverridevoidCompleteContent(){OnComplete?.Invoke();}}
http://www.cnnetsun.cn/news/2776879.html

相关文章:

  • 滑模控制抖振抑制方案:模糊切换+自适应律的Simulink实现包
  • 移动端APP开发:MonkeyCode在 Flutter 中的应用
  • iOS背景移除终极方案:3大优势让你轻松实现专业级图像处理
  • 深入 Raft 共识协议:基于 Rust 的极简 Leader 选举与心跳维持机制实现
  • 实战避坑指南:FFmpeg处理YUV420 NV12/P010数据时,内存对齐与性能优化的那些事儿
  • Veo风格迁移部署踩坑清单:从A100到RTX 4090,6类硬件下显存溢出的5种精准定位法(含nvidia-smi实时诊断脚本)
  • 从零到交付:AI工具学习路径规划全链路拆解,含L1-L5能力跃迁评估表与动态校准机制
  • C语言开篇
  • 从502错误到丝滑pub get:一份Flutter镜像配置的防坑与自动化配置指南
  • 【课程设计/毕业设计】基于Django的本地健康宝微信小程序系统的设计与实现疫苗接种健康系统【附源码、数据库、万字文档】
  • 2000 字,讲透OGSM:从目的到方案,一套让战略真正落地的对齐框架
  • 基于高性能云原生 CNI 插件优化 K8s 调度器与节点间延迟
  • AI资本周期的转折点:从通用模型崇拜到垂直价值捕获
  • 3分钟搞定:Windows任务栏股票实时监控的完整解决方案
  • Java新手福音:描述需求即可获得带详解的入门代码示例
  • 正版ABAQUS代理商怎么选,仿真采购必看指南
  • 普托马尼联用贝达喹啉利奈唑胺治广泛耐药结核,肝毒性每月监测
  • 比亚迪微电子的IDM模式与垂直整合:中国半导体产业的破局启示
  • 用Python+TraCI玩转SUMO:从读取车辆位置到动态控制红绿灯的实战
  • 基于hal库的ETH外设完整指南
  • 2026镇江市权威认证贵金属回收 TOP5+黄金回收白银回收铂金回收门店地址电话推荐
  • 从‘内表行数’到‘数据库计数’:ABAP里SELECT COUNT(*)的5个实战避坑点
  • 红外体温计语音播报温度IC方案:WT588F02-8S-C 40ms快速上电播报
  • 质量管理和财务管理:品质管控与经营分析的AI痛点
  • 2026军校近视手术康复指南:顺利通关全流程解析
  • Teamcenter许可优化,4款工具成熟度对比
  • 面试潜规则⑪:Offer到手后,别急着签字:最容易踩的5个“隐形坑”
  • 别再死记硬背了!一张图+三个生活案例,帮你彻底搞懂运筹学对偶理论(弱对偶、强对偶、互补松弛)
  • Beyond Compare 5激活密钥生成器:3分钟解锁专业版完整功能
  • 沉浸式文旅新标杆,大体量黑暗乘骑重塑场馆核心价值