官网

火山方舟管理控制台 (volcengine.com)

Bot API V2–火山方舟大模型服务平台-火山引擎 (volcengine.com)

代码接入

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
using Newtonsoft.Json;
using System;
using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// ____DESC: UITeach 逻辑界面
/// </summary>
public partial class UITeach : UIPanelBase
{
// 将你的API密钥替换到这里
private string apiKey = "eyJhbGciOiJSUzI1NiIsInR5cCxxxxxxxxxxx";
private string url = "https://ark.cn-beijing.volces.";

protected override void OnAwake()
{
btnSend.OnClick.AddListener(OnClickSend);
btnBack.OnClick.AddListener(btn =>
{
GameEngine.SceneModule.LoadSceneAsyncFromAB("scenes/GameHome.unity");
});
btnSetting.OnClick.AddListener(btn =>
{
GameEngine.UIModule.GetUIPanel<UISetting>().Show();
});
}

//发送
private void OnClickSend(ButtonPlus btn)
{
if (InputField_Msg.text.IsNotNullOrEmpty())
{
string msg = InputField_Msg.text;
InputField_Msg.text = string.Empty;
btn.Interactable = false;
CreateChatText(msg, true);
GameEngine.Startcoroutine(PostRequest(msg, msg =>
{
CreateChatText(msg, false);
btn.Interactable = true;
}));
}
}

private void CreateChatText(string info, bool isReverse)
{
var chatgo = GameObject.Instantiate(chatPrefab.gameObject, scrollView.content);
chatgo.gameObject.SetActive(true);
var text = chatgo.GetComponentInChildren<TextMeshProUGUI>();
text.text = info;
if (isReverse)
{
chatgo.transform.localScale = new Vector3(-1f, 1f, 1f);
text.transform.localScale = new Vector3(-1f, 1f, 1f);
text.color = Color.blue;
}
Timer.WaitOneFrameEnd(() =>
{
scrollView.verticalNormalizedPosition = 0f;
});
}

IEnumerator PostRequest(string msg, Action<string> callback)
{
// 创建JSON数据
var send = new SendToMessage();
send.messages = new SendToMessage.Messages[1];
send.messages[0] = new SendToMessage.Messages { role = "user", content = msg };
send.parameters = new SendToMessage.Parameters() { max_tokens = 100 };
// 创建一个新的UnityWebRequest,指向指定的URL,并设置方法为POST
UnityWebRequest request = new UnityWebRequest(url, "POST");

// 将JSON数据转换为字节数组,并设置为请求体
byte[] bodyRaw = new System.Text.UTF8Encoding().GetBytes(send.ToString());
request.uploadHandler = new UploadHandlerRaw(bodyRaw);

// 设置请求头
request.SetRequestHeader("Content-Type", "application/json");
request.SetRequestHeader("Authorization", "Bearer " + apiKey);

// 设置下载处理器
request.downloadHandler = new DownloadHandlerBuffer();

// 发送请求并等待响应
yield return request.SendWebRequest();

// 检查请求的结果
if (request.result != UnityWebRequest.Result.Success)
{
Debug.LogError(request.error);
callback?.Invoke("啊哦~,出现了一点问题,请在试试!");
}
else
{
// 请求成功,处理响应数据
Debug.Log("Response: " + request.downloadHandler.text);
ParseResponse(request.downloadHandler.text, callback);
}
}

void ParseResponse(string jsonResponse, Action<string> callback)
{
// 定义与JSON结构匹配的C#类
RootObject responseObject = JsonConvert.DeserializeObject<RootObject>(jsonResponse);

// 访问并处理解析后的数据
//Debug.Log("Request ID: " + responseObject.req_id);
//Debug.Log("Message Content: " + responseObject.choices[0].message.content);
//Debug.Log("Prompt Tokens: " + responseObject.usage.model_usage[0].prompt_tokens);
//Debug.Log("Completion Tokens: " + responseObject.usage.model_usage[0].completion_tokens);
//Debug.Log("Total Tokens: " + responseObject.usage.model_usage[0].total_tokens);
callback?.Invoke(responseObject.choices[0].message.content);
}

#region 定义与JSON结构匹配的C#类
[System.Serializable]
public class SendToMessage
{
public Messages[] messages;
//public bool stream;
public Parameters parameters;

[System.Serializable]
public class Messages
{
public string role;
public string content;
}

[System.Serializable]
public class Parameters
{
public int max_tokens;
}
public override string ToString()
{
string str = JsonUtility.ToJson(this);
return str;
}
}

[Serializable]
public class RootObject
{
public string req_id;
public Choice[] choices;
public Usage usage;
}

[Serializable]
public class Choice
{
public int index;
public Message message;
public string finish_reason;
}

[Serializable]
public class Message
{
public string role;
public string content;
}

[Serializable]
public class Usage
{
public ModelUsage[] model_usage;
}

[Serializable]
public class ModelUsage
{
public int prompt_tokens;
public int completion_tokens;
public int total_tokens;
}
#endregion
}