官网链接
coze智能体创建、设置
点击创建–选着智能体,随便起一个名字,就可以了
添加令牌
把随便起一个名字,设置时间,把所有选项都勾选上,一定要勾选所有团队空间,否则无法点击确定。
点击确定后,会有一个对话框。里面有key,这个key需要做好备份,对话框关闭后,就无法找到这个key了,没有key就无法进行对话
API
API链接
每个API里面都有示例,可以按照示例,在代码中调用对应的API
核心代码
class Coze {private string apiToken = "备份的key";private string botId = "智能体的bot";private string conversationId ;private string chatId;//AI智能体回复消息的回调public Action<string> receiveCallBack;public Action processEndCallBack;//进度结束后的回调public Action<int> processCallBack;//进度回调public IEnumerator SendChatRequest(string userMessage){Debug.Log("创建对话");// Step 1: 发起对话请求string chatUrl = "https://api.coze.cn/v3/chat";string jsonBody = $@"{{""bot_id"": ""{botId}"",""user_id"": ""123456789"",""stream"": true,""auto_save_history"": true,""additional_messages"": [{{""role"": ""user"",""content"": ""{userMessage}"",""content_type"": ""text""}}]}}";UnityWebRequest chatRequest = new UnityWebRequest(chatUrl, "POST");byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);chatRequest.uploadHandler = new UploadHandlerRaw(bodyRaw);chatRequest.downloadHandler = new DownloadHandlerBuffer();chatRequest.SetRequestHeader("Authorization", "Bearer " + apiToken);chatRequest.SetRequestHeader("Content-Type", "application/json");yield return chatRequest.SendWebRequest();Debug.Log("创建对话完成");if (chatRequest.result == UnityWebRequest.Result.Success){string response = chatRequest.downloadHandler.text;// 解析SSE格式string[] lines = response.Split('\n');string jsonData = "";foreach (string line in lines){if (line.StartsWith("data:")){jsonData = line.Substring(5); // 去掉"data:"前缀break;}}Debug.Log("对话Json:" + jsonData);if (!string.IsNullOrEmpty(jsonData)){SSEChatResponse sseResponse = JsonUtility.FromJson<SSEChatResponse>(jsonData);chatId = sseResponse.id;conversationId=sseResponse.conversation_id;Debug.Log($"Chat ID: {chatId}");// 继续执行后续代码yield return MonoInstanceTool.Instance.StartCoroutine(CheckChatStatus());yield return MonoInstanceTool.Instance.StartCoroutine(GetChatMessages());}else{Debug.LogError("Failed to parse SSE response");}}else{Debug.LogError("Error: " + chatRequest.error);}}IEnumerator CheckChatStatus(){bool isCompleted = false;while (!isCompleted){string statusUrl = $"https://api.coze.cn/v3/chat/retrieve?chat_id={chatId}&conversation_id={conversationId}";UnityWebRequest statusRequest = UnityWebRequest.Get(statusUrl);statusRequest.SetRequestHeader("Authorization", "Bearer " + apiToken);statusRequest.SetRequestHeader("Content-Type", "application/json");yield return statusRequest.SendWebRequest();if (statusRequest.result == UnityWebRequest.Result.Success){string response = statusRequest.downloadHandler.text;Debug.Log("检查:" + response);ChatResponse statusResponse = JsonUtility.FromJson<ChatResponse>(response);// 检查status是否为completedif (statusResponse.data.status == "completed"){isCompleted = true;Debug.Log("Chat completed!");}else{Debug.Log("Chat still in progress...");}}else{Debug.LogError("Status check failed: " + statusRequest.error);}yield return new WaitForSeconds(1);}}//创建对话IEnumerator GetChatMessages(){string messageUrl = $"https://api.coze.cn/v3/chat/message/list?chat_id={chatId}&conversation_id={conversationId}";UnityWebRequest messageRequest = UnityWebRequest.Get(messageUrl);messageRequest.SetRequestHeader("Authorization", "Bearer " + apiToken);messageRequest.SetRequestHeader("Content-Type", "application/json");yield return messageRequest.SendWebRequest();if (messageRequest.result == UnityWebRequest.Result.Success){string response = messageRequest.downloadHandler.text;MessageResponse messageResponse = JsonUtility.FromJson<MessageResponse>(response);// 查找类型为"answer"的消息string content = "";foreach (MessageData message in messageResponse.data){if (message.type == "answer"){content = message.content;break;}}// 显示到UI上receiveCallBack?.Invoke(content);}else{Debug.LogError("Failed to get messages: " + messageRequest.error);}}string dataset_id ="知识库的id";string documentId;//文件上传知识库public IEnumerator UploadFile(string fileName,string base64File){string fileExtension = Path.GetExtension(fileName);var requestBody = new{dataset_id = dataset_id,document_bases = new[]{new{name =fileName,source_info = new{file_base64 = base64File,file_type = fileExtension}}},chunk_strategy = new{separator = "\n\n",max_tokens = 800,remove_extra_spaces = false,remove_urls_emails = false,chunk_type = 0},format_type = 0};string json = JsonConvert.SerializeObject(requestBody);Debug.Log(json);byte[] jsonToSend = new UTF8Encoding().GetBytes(json);UnityWebRequest request = new UnityWebRequest("https://api.coze.cn/open_api/knowledge/document/create", "POST");request.uploadHandler = new UploadHandlerRaw(jsonToSend);request.downloadHandler = new DownloadHandlerBuffer();request.SetRequestHeader("Authorization", $"Bearer {apiToken}");request.SetRequestHeader("Content-Type", "application/json");request.SetRequestHeader("Agw-Js-Conv", "str");yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError){Debug.LogError("Error uploading file: " + request.error);}else{Debug.Log("Response: " + request.downloadHandler.text);// 解析 JSON 字符串为 JsonData 对象JsonData jsonObject = JsonMapper.ToObject(request.downloadHandler.text);// 获取 document_iddocumentId = jsonObject["document_infos"][0]["document_id"].ToString();MonoInstanceTool.Instance.StartCoroutine(FileProcess());}}//上传进度public IEnumerator FileProcess(){// 生成要发送的JSON数据var requestBody = new{document_ids = new string[]{dataset_id, // 知识库IDdocumentId // 上传进度的文件ID}};string jsonBody = JsonConvert.SerializeObject(requestBody);string postUrl = $"https://api.coze.cn/v1/datasets/{dataset_id}/process";// 初始化请求对象UnityWebRequest request = new UnityWebRequest(postUrl, "POST");while (true){byte[] bodyRaw = Encoding.UTF8.GetBytes(jsonBody);request.uploadHandler = new UploadHandlerRaw(bodyRaw);request.downloadHandler = new DownloadHandlerBuffer();request.SetRequestHeader("Authorization", $"Bearer {apiToken}"); // 设置Authorization headerrequest.SetRequestHeader("Content-Type", "application/json"); // 设置Content-Type为JSON// 发送请求并等待返回yield return request.SendWebRequest();if (request.result == UnityWebRequest.Result.ConnectionError || request.result == UnityWebRequest.Result.ProtocolError){Debug.LogError("进度POST 请求失败,错误信息: " + request.error);yield break; // 如果请求失败则退出}string response = request.downloadHandler.text;Debug.Log("ProcessResponse: " + response);JsonData jsonObject = JsonMapper.ToObject(response);// 获取 status 和 progressint status = (int)jsonObject["data"]["data"][0]["status"];int progress = (int)jsonObject["data"]["data"][0]["progress"];// 如果文件正在处理中,则循环等待并检查进度if (status == 0) // 处理中,status 为 0{processCallBack?.Invoke(progress);// 等待一段时间后再次请求yield return new WaitForSeconds(2f); // 每1秒查询一次状态// 重新初始化请求对象request = new UnityWebRequest(postUrl, "POST");}else{// 当 status 为 1 时,表示处理完毕if (status == 1){Debug.Log("文件处理完毕,执行后续操作...");// 在这里执行文件处理完毕后的操作// 例如调用回调函数processEndCallBack?.Invoke();}else if (status == 9){Debug.LogWarning("文件处理失败,建议重新上传");// 在这里可以添加处理文件失败的逻辑}// 跳出循环,避免重复请求break;}}}}// 添加这些数据结构类在CozeTest类外部
[System.Serializable]
public class ChatResponse
{public ChatData data;public int code;public string msg;
}[System.Serializable]
public class ChatData
{public string id;public string conversation_id;public string bot_id;public long created_at;public long completed_at;public string last_error;public object meta_data;public string status;public UsageData usage;
}[System.Serializable]
public class UsageData
{public int token_count;public int output_count;public int input_count;
}[System.Serializable]
public class MessageResponse
{public int code;public MessageData[] data;public string msg;
}[System.Serializable]
public class MessageData
{public string bot_id;public string content;public string content_type;public string conversation_id;public string id;public string role;public string type;
}[System.Serializable]
public class SSEChatResponse
{public string id;public string conversation_id;public string bot_id;public long created_at;public LastError last_error;public string status;public UsageData usage;public string section_id;
}[System.Serializable]
public class LastError
{public int code;public string msg;
}