package com.lanyuanxiaoyao.digtal.market.ai

import com.zhipu.oapi.ClientV4
import com.zhipu.oapi.Constants
import com.zhipu.oapi.service.v4.model.ChatCompletionRequest
import com.zhipu.oapi.service.v4.model.ChatMessage
import java.util.concurrent.TimeUnit

class ZhipuChat(apiSecretKey: String = "d1e97306540d12bb2f834be961fcacb1.SNBShlCxWYJCx0qZ") : Chat {
    private val client = ClientV4.Builder(apiSecretKey)
        .networkConfig(5, 5, 5, 5, TimeUnit.MINUTES)
        .build()

    override fun ask(vararg messages: Chat.Companion.Message): String? {
        val request = ChatCompletionRequest.builder()
            .model("glm-4-flash")
            .stream(false)
            .messages(messages.map {
                val type = when (it.type) {
                    Chat.Companion.Message.Companion.Type.SYSTEM -> "system"
                    Chat.Companion.Message.Companion.Type.USER -> "user"
                }
                ChatMessage(type, it.content)
            })
            .invokeMethod(Constants.invokeMethod)
            // .tools(listOf(ChatTool().apply { type = "web_search";web_search = WebSearch().apply { enable = true } }))
            .build()
        val response = client.invokeModelApi(request)
        return if (response.isSuccess) response.data.choices.firstOrNull()?.message?.content.toString()
        else null
    }
}