adaptor.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. package kling
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "math"
  7. "net/http"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/QuantumNous/new-api/common"
  12. "github.com/QuantumNous/new-api/model"
  13. "github.com/samber/lo"
  14. "github.com/gin-gonic/gin"
  15. "github.com/golang-jwt/jwt/v5"
  16. "github.com/pkg/errors"
  17. "github.com/QuantumNous/new-api/constant"
  18. "github.com/QuantumNous/new-api/dto"
  19. "github.com/QuantumNous/new-api/relay/channel"
  20. taskcommon "github.com/QuantumNous/new-api/relay/channel/task/taskcommon"
  21. relaycommon "github.com/QuantumNous/new-api/relay/common"
  22. "github.com/QuantumNous/new-api/service"
  23. )
  24. // ============================
  25. // Request / Response structures
  26. // ============================
  27. type TrajectoryPoint struct {
  28. X int `json:"x"`
  29. Y int `json:"y"`
  30. }
  31. type DynamicMask struct {
  32. Mask string `json:"mask,omitempty"`
  33. Trajectories []TrajectoryPoint `json:"trajectories,omitempty"`
  34. }
  35. type CameraConfig struct {
  36. Horizontal float64 `json:"horizontal,omitempty"`
  37. Vertical float64 `json:"vertical,omitempty"`
  38. Pan float64 `json:"pan,omitempty"`
  39. Tilt float64 `json:"tilt,omitempty"`
  40. Roll float64 `json:"roll,omitempty"`
  41. Zoom float64 `json:"zoom,omitempty"`
  42. }
  43. type CameraControl struct {
  44. Type string `json:"type,omitempty"`
  45. Config *CameraConfig `json:"config,omitempty"`
  46. }
  47. type requestPayload struct {
  48. Prompt string `json:"prompt,omitempty"`
  49. Image string `json:"image,omitempty"`
  50. ImageTail string `json:"image_tail,omitempty"`
  51. NegativePrompt string `json:"negative_prompt,omitempty"`
  52. Mode string `json:"mode,omitempty"`
  53. Duration string `json:"duration,omitempty"`
  54. AspectRatio string `json:"aspect_ratio,omitempty"`
  55. ModelName string `json:"model_name,omitempty"`
  56. Model string `json:"model,omitempty"` // Compatible with upstreams that only recognize "model"
  57. CfgScale float64 `json:"cfg_scale,omitempty"`
  58. StaticMask string `json:"static_mask,omitempty"`
  59. DynamicMasks []DynamicMask `json:"dynamic_masks,omitempty"`
  60. CameraControl *CameraControl `json:"camera_control,omitempty"`
  61. CallbackUrl string `json:"callback_url,omitempty"`
  62. ExternalTaskId string `json:"external_task_id,omitempty"`
  63. }
  64. type responsePayload struct {
  65. Code int `json:"code"`
  66. Message string `json:"message"`
  67. TaskId string `json:"task_id"`
  68. RequestId string `json:"request_id"`
  69. Data struct {
  70. TaskId string `json:"task_id"`
  71. TaskStatus string `json:"task_status"`
  72. TaskStatusMsg string `json:"task_status_msg"`
  73. TaskInfo struct {
  74. ExternalTaskId string `json:"external_task_id"`
  75. } `json:"task_info"`
  76. WatermarkInfo struct {
  77. Enabled bool `json:"enabled"`
  78. } `json:"watermark_info"`
  79. TaskResult struct {
  80. Videos []struct {
  81. Id string `json:"id"`
  82. Url string `json:"url"`
  83. WatermarkUrl string `json:"watermark_url"`
  84. Duration string `json:"duration"`
  85. } `json:"videos"`
  86. Images []struct {
  87. Index int `json:"index"`
  88. Url string `json:"url"`
  89. WatermarkUrl string `json:"watermark_url"`
  90. } `json:"images"`
  91. } `json:"task_result"`
  92. CreatedAt int64 `json:"created_at"`
  93. UpdatedAt int64 `json:"updated_at"`
  94. FinalUnitDeduction string `json:"final_unit_deduction"`
  95. } `json:"data"`
  96. }
  97. // ============================
  98. // Adaptor implementation
  99. // ============================
  100. type TaskAdaptor struct {
  101. taskcommon.BaseBilling
  102. ChannelType int
  103. apiKey string
  104. baseURL string
  105. }
  106. func (a *TaskAdaptor) Init(info *relaycommon.RelayInfo) {
  107. a.ChannelType = info.ChannelType
  108. a.baseURL = info.ChannelBaseUrl
  109. a.apiKey = info.ApiKey
  110. // apiKey format: "access_key|secret_key"
  111. }
  112. // ValidateRequestAndSetAction parses body, validates fields and sets default action.
  113. func (a *TaskAdaptor) ValidateRequestAndSetAction(c *gin.Context, info *relaycommon.RelayInfo) (taskErr *dto.TaskError) {
  114. // Use the standard validation method for TaskSubmitReq
  115. return relaycommon.ValidateBasicTaskRequest(c, info, constant.TaskActionGenerate)
  116. }
  117. // BuildRequestURL constructs the upstream URL.
  118. func (a *TaskAdaptor) BuildRequestURL(info *relaycommon.RelayInfo) (string, error) {
  119. path := lo.Ternary(info.Action == constant.TaskActionGenerate, "/v1/videos/image2video", "/v1/videos/text2video")
  120. if isNewAPIRelay(info.ApiKey) {
  121. return fmt.Sprintf("%s/kling%s", a.baseURL, path), nil
  122. }
  123. return fmt.Sprintf("%s%s", a.baseURL, path), nil
  124. }
  125. // BuildRequestHeader sets required headers.
  126. func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, info *relaycommon.RelayInfo) error {
  127. token, err := a.createJWTToken()
  128. if err != nil {
  129. return fmt.Errorf("failed to create JWT token: %w", err)
  130. }
  131. req.Header.Set("Content-Type", "application/json")
  132. req.Header.Set("Accept", "application/json")
  133. req.Header.Set("Authorization", "Bearer "+token)
  134. req.Header.Set("User-Agent", "kling-sdk/1.0")
  135. return nil
  136. }
  137. // BuildRequestBody converts request into Kling specific format.
  138. func (a *TaskAdaptor) BuildRequestBody(c *gin.Context, info *relaycommon.RelayInfo) (io.Reader, error) {
  139. v, exists := c.Get("task_request")
  140. if !exists {
  141. return nil, fmt.Errorf("request not found in context")
  142. }
  143. req := v.(relaycommon.TaskSubmitReq)
  144. body, err := a.convertToRequestPayload(&req, info)
  145. if err != nil {
  146. return nil, err
  147. }
  148. if body.Image == "" && body.ImageTail == "" {
  149. c.Set("action", constant.TaskActionTextGenerate)
  150. }
  151. data, err := common.Marshal(body)
  152. if err != nil {
  153. return nil, err
  154. }
  155. return bytes.NewReader(data), nil
  156. }
  157. // DoRequest delegates to common helper.
  158. func (a *TaskAdaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (*http.Response, error) {
  159. if action := c.GetString("action"); action != "" {
  160. info.Action = action
  161. }
  162. return channel.DoTaskApiRequest(a, c, info, requestBody)
  163. }
  164. // DoResponse handles upstream response, returns taskID etc.
  165. func (a *TaskAdaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (taskID string, taskData []byte, taskErr *dto.TaskError) {
  166. responseBody, err := io.ReadAll(resp.Body)
  167. if err != nil {
  168. taskErr = service.TaskErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError)
  169. return
  170. }
  171. var kResp responsePayload
  172. err = common.Unmarshal(responseBody, &kResp)
  173. if err != nil {
  174. taskErr = service.TaskErrorWrapper(err, "unmarshal_response_failed", http.StatusInternalServerError)
  175. return
  176. }
  177. if kResp.Code != 0 {
  178. taskErr = service.TaskErrorWrapperLocal(fmt.Errorf("%s", kResp.Message), "task_failed", http.StatusBadRequest)
  179. return
  180. }
  181. ov := dto.NewOpenAIVideo()
  182. ov.ID = info.PublicTaskID
  183. ov.TaskID = info.PublicTaskID
  184. ov.CreatedAt = time.Now().Unix()
  185. ov.Model = info.OriginModelName
  186. c.JSON(http.StatusOK, ov)
  187. return kResp.Data.TaskId, responseBody, nil
  188. }
  189. // FetchTask fetch task status
  190. func (a *TaskAdaptor) FetchTask(baseUrl, key string, body map[string]any, proxy string) (*http.Response, error) {
  191. taskID, ok := body["task_id"].(string)
  192. if !ok {
  193. return nil, fmt.Errorf("invalid task_id")
  194. }
  195. action, ok := body["action"].(string)
  196. if !ok {
  197. return nil, fmt.Errorf("invalid action")
  198. }
  199. path := lo.Ternary(action == constant.TaskActionGenerate, "/v1/videos/image2video", "/v1/videos/text2video")
  200. url := fmt.Sprintf("%s%s/%s", baseUrl, path, taskID)
  201. if isNewAPIRelay(key) {
  202. url = fmt.Sprintf("%s/kling%s/%s", baseUrl, path, taskID)
  203. }
  204. req, err := http.NewRequest(http.MethodGet, url, nil)
  205. if err != nil {
  206. return nil, err
  207. }
  208. token, err := a.createJWTTokenWithKey(key)
  209. if err != nil {
  210. token = key
  211. }
  212. req.Header.Set("Accept", "application/json")
  213. req.Header.Set("Authorization", "Bearer "+token)
  214. req.Header.Set("User-Agent", "kling-sdk/1.0")
  215. client, err := service.GetHttpClientWithProxy(proxy)
  216. if err != nil {
  217. return nil, fmt.Errorf("new proxy http client failed: %w", err)
  218. }
  219. return client.Do(req)
  220. }
  221. func (a *TaskAdaptor) GetModelList() []string {
  222. return []string{"kling-v1", "kling-v1-6", "kling-v2-master"}
  223. }
  224. func (a *TaskAdaptor) GetChannelName() string {
  225. return "kling"
  226. }
  227. // ============================
  228. // helpers
  229. // ============================
  230. func (a *TaskAdaptor) convertToRequestPayload(req *relaycommon.TaskSubmitReq, info *relaycommon.RelayInfo) (*requestPayload, error) {
  231. r := requestPayload{
  232. Prompt: req.Prompt,
  233. Image: req.Image,
  234. Mode: taskcommon.DefaultString(req.Mode, "std"),
  235. Duration: fmt.Sprintf("%d", taskcommon.DefaultInt(req.Duration, 5)),
  236. AspectRatio: a.getAspectRatio(req.Size),
  237. ModelName: info.UpstreamModelName,
  238. Model: info.UpstreamModelName,
  239. CfgScale: 0.5,
  240. StaticMask: "",
  241. DynamicMasks: []DynamicMask{},
  242. CameraControl: nil,
  243. CallbackUrl: "",
  244. ExternalTaskId: "",
  245. }
  246. if r.ModelName == "" {
  247. r.ModelName = "kling-v1"
  248. r.Model = "kling-v1"
  249. }
  250. if err := taskcommon.UnmarshalMetadata(req.Metadata, &r); err != nil {
  251. return nil, errors.Wrap(err, "unmarshal metadata failed")
  252. }
  253. return &r, nil
  254. }
  255. func (a *TaskAdaptor) getAspectRatio(size string) string {
  256. switch size {
  257. case "1024x1024", "512x512":
  258. return "1:1"
  259. case "1280x720", "1920x1080":
  260. return "16:9"
  261. case "720x1280", "1080x1920":
  262. return "9:16"
  263. default:
  264. return "1:1"
  265. }
  266. }
  267. // ============================
  268. // JWT helpers
  269. // ============================
  270. func (a *TaskAdaptor) createJWTToken() (string, error) {
  271. return a.createJWTTokenWithKey(a.apiKey)
  272. }
  273. func (a *TaskAdaptor) createJWTTokenWithKey(apiKey string) (string, error) {
  274. if isNewAPIRelay(apiKey) {
  275. return apiKey, nil // new api relay
  276. }
  277. keyParts := strings.Split(apiKey, "|")
  278. if len(keyParts) != 2 {
  279. return "", errors.New("invalid api_key, required format is accessKey|secretKey")
  280. }
  281. accessKey := strings.TrimSpace(keyParts[0])
  282. if len(keyParts) == 1 {
  283. return accessKey, nil
  284. }
  285. secretKey := strings.TrimSpace(keyParts[1])
  286. now := time.Now().Unix()
  287. claims := jwt.MapClaims{
  288. "iss": accessKey,
  289. "exp": now + 1800, // 30 minutes
  290. "nbf": now - 5,
  291. }
  292. token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
  293. token.Header["typ"] = "JWT"
  294. return token.SignedString([]byte(secretKey))
  295. }
  296. func (a *TaskAdaptor) ParseTaskResult(respBody []byte) (*relaycommon.TaskInfo, error) {
  297. taskInfo := &relaycommon.TaskInfo{}
  298. resPayload := responsePayload{}
  299. err := common.Unmarshal(respBody, &resPayload)
  300. if err != nil {
  301. return nil, errors.Wrap(err, "failed to unmarshal response body")
  302. }
  303. taskInfo.Code = resPayload.Code
  304. taskInfo.TaskID = resPayload.Data.TaskId
  305. taskInfo.Reason = resPayload.Data.TaskStatusMsg
  306. //任务状态,枚举值:submitted(已提交)、processing(处理中)、succeed(成功)、failed(失败)
  307. status := resPayload.Data.TaskStatus
  308. switch status {
  309. case "submitted":
  310. taskInfo.Status = model.TaskStatusSubmitted
  311. case "processing":
  312. taskInfo.Status = model.TaskStatusInProgress
  313. case "succeed":
  314. taskInfo.Status = model.TaskStatusSuccess
  315. if videos := resPayload.Data.TaskResult.Videos; len(videos) > 0 {
  316. video := videos[0]
  317. taskInfo.Url = video.Url
  318. }
  319. if tokens, err := strconv.ParseFloat(resPayload.Data.FinalUnitDeduction, 64); err == nil {
  320. rounded := int(math.Ceil(tokens))
  321. if rounded > 0 {
  322. taskInfo.CompletionTokens = rounded
  323. taskInfo.TotalTokens = rounded
  324. }
  325. }
  326. case "failed":
  327. taskInfo.Status = model.TaskStatusFailure
  328. default:
  329. return nil, fmt.Errorf("unknown task status: %s", status)
  330. }
  331. return taskInfo, nil
  332. }
  333. func isNewAPIRelay(apiKey string) bool {
  334. return strings.HasPrefix(apiKey, "sk-")
  335. }
  336. func (a *TaskAdaptor) ConvertToOpenAIVideo(originTask *model.Task) ([]byte, error) {
  337. var klingResp responsePayload
  338. if err := common.Unmarshal(originTask.Data, &klingResp); err != nil {
  339. return nil, errors.Wrap(err, "unmarshal kling task data failed")
  340. }
  341. openAIVideo := dto.NewOpenAIVideo()
  342. openAIVideo.ID = originTask.TaskID
  343. openAIVideo.Status = originTask.Status.ToVideoStatus()
  344. openAIVideo.SetProgressStr(originTask.Progress)
  345. openAIVideo.CreatedAt = klingResp.Data.CreatedAt
  346. openAIVideo.CompletedAt = klingResp.Data.UpdatedAt
  347. if len(klingResp.Data.TaskResult.Videos) > 0 {
  348. video := klingResp.Data.TaskResult.Videos[0]
  349. if video.Url != "" {
  350. openAIVideo.SetMetadata("url", video.Url)
  351. }
  352. if video.Duration != "" {
  353. openAIVideo.Seconds = video.Duration
  354. }
  355. }
  356. if klingResp.Code != 0 && klingResp.Message != "" {
  357. openAIVideo.Error = &dto.OpenAIVideoError{
  358. Message: klingResp.Message,
  359. Code: fmt.Sprintf("%d", klingResp.Code),
  360. }
  361. }
  362. // https://app.klingai.com/cn/dev/document-api/apiReference/model/textToVideo
  363. if data := klingResp.Data; data.TaskStatus == "failed" {
  364. openAIVideo.Error = &dto.OpenAIVideoError{
  365. Message: data.TaskStatusMsg,
  366. }
  367. }
  368. return common.Marshal(openAIVideo)
  369. }