claude.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. "github.com/QuantumNous/new-api/common"
  7. "github.com/QuantumNous/new-api/types"
  8. "github.com/gin-gonic/gin"
  9. )
  10. type ClaudeMetadata struct {
  11. UserId string `json:"user_id"`
  12. }
  13. type ClaudeMediaMessage struct {
  14. Type string `json:"type,omitempty"`
  15. Text *string `json:"text,omitempty"`
  16. Model string `json:"model,omitempty"`
  17. Source *ClaudeMessageSource `json:"source,omitempty"`
  18. Usage *ClaudeUsage `json:"usage,omitempty"`
  19. StopReason *string `json:"stop_reason,omitempty"`
  20. PartialJson *string `json:"partial_json,omitempty"`
  21. Role string `json:"role,omitempty"`
  22. Thinking *string `json:"thinking,omitempty"`
  23. Signature string `json:"signature,omitempty"`
  24. Delta string `json:"delta,omitempty"`
  25. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  26. // tool_calls
  27. Id string `json:"id,omitempty"`
  28. Name string `json:"name,omitempty"`
  29. Input any `json:"input,omitempty"`
  30. Content any `json:"content,omitempty"`
  31. ToolUseId string `json:"tool_use_id,omitempty"`
  32. }
  33. func (c *ClaudeMediaMessage) SetText(s string) {
  34. c.Text = &s
  35. }
  36. func (c *ClaudeMediaMessage) GetText() string {
  37. if c.Text == nil {
  38. return ""
  39. }
  40. return *c.Text
  41. }
  42. func (c *ClaudeMediaMessage) IsStringContent() bool {
  43. if c.Content == nil {
  44. return false
  45. }
  46. _, ok := c.Content.(string)
  47. if ok {
  48. return true
  49. }
  50. return false
  51. }
  52. func (c *ClaudeMediaMessage) GetStringContent() string {
  53. if c.Content == nil {
  54. return ""
  55. }
  56. switch c.Content.(type) {
  57. case string:
  58. return c.Content.(string)
  59. case []any:
  60. var contentStr string
  61. for _, contentItem := range c.Content.([]any) {
  62. contentMap, ok := contentItem.(map[string]any)
  63. if !ok {
  64. continue
  65. }
  66. if contentMap["type"] == ContentTypeText {
  67. if subStr, ok := contentMap["text"].(string); ok {
  68. contentStr += subStr
  69. }
  70. }
  71. }
  72. return contentStr
  73. }
  74. return ""
  75. }
  76. func (c *ClaudeMediaMessage) GetJsonRowString() string {
  77. jsonContent, _ := common.Marshal(c)
  78. return string(jsonContent)
  79. }
  80. func (c *ClaudeMediaMessage) SetContent(content any) {
  81. c.Content = content
  82. }
  83. func (c *ClaudeMediaMessage) ParseMediaContent() []ClaudeMediaMessage {
  84. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.Content)
  85. return mediaContent
  86. }
  87. type ClaudeMessageSource struct {
  88. Type string `json:"type"`
  89. MediaType string `json:"media_type,omitempty"`
  90. Data any `json:"data,omitempty"`
  91. Url string `json:"url,omitempty"`
  92. }
  93. type ClaudeMessage struct {
  94. Role string `json:"role"`
  95. Content any `json:"content"`
  96. }
  97. func (c *ClaudeMessage) IsStringContent() bool {
  98. if c.Content == nil {
  99. return false
  100. }
  101. _, ok := c.Content.(string)
  102. return ok
  103. }
  104. func (c *ClaudeMessage) GetStringContent() string {
  105. if c.Content == nil {
  106. return ""
  107. }
  108. switch c.Content.(type) {
  109. case string:
  110. return c.Content.(string)
  111. case []any:
  112. var contentStr string
  113. for _, contentItem := range c.Content.([]any) {
  114. contentMap, ok := contentItem.(map[string]any)
  115. if !ok {
  116. continue
  117. }
  118. if contentMap["type"] == ContentTypeText {
  119. if subStr, ok := contentMap["text"].(string); ok {
  120. contentStr += subStr
  121. }
  122. }
  123. }
  124. return contentStr
  125. }
  126. return ""
  127. }
  128. func (c *ClaudeMessage) SetStringContent(content string) {
  129. c.Content = content
  130. }
  131. func (c *ClaudeMessage) SetContent(content any) {
  132. c.Content = content
  133. }
  134. func (c *ClaudeMessage) ParseContent() ([]ClaudeMediaMessage, error) {
  135. return common.Any2Type[[]ClaudeMediaMessage](c.Content)
  136. }
  137. type Tool struct {
  138. Name string `json:"name"`
  139. Description string `json:"description,omitempty"`
  140. InputSchema map[string]interface{} `json:"input_schema"`
  141. }
  142. type InputSchema struct {
  143. Type string `json:"type"`
  144. Properties any `json:"properties,omitempty"`
  145. Required any `json:"required,omitempty"`
  146. }
  147. type ClaudeWebSearchTool struct {
  148. Type string `json:"type"`
  149. Name string `json:"name"`
  150. MaxUses int `json:"max_uses,omitempty"`
  151. UserLocation *ClaudeWebSearchUserLocation `json:"user_location,omitempty"`
  152. }
  153. type ClaudeWebSearchUserLocation struct {
  154. Type string `json:"type"`
  155. Timezone string `json:"timezone,omitempty"`
  156. Country string `json:"country,omitempty"`
  157. Region string `json:"region,omitempty"`
  158. City string `json:"city,omitempty"`
  159. }
  160. type ClaudeToolChoice struct {
  161. Type string `json:"type"`
  162. Name string `json:"name,omitempty"`
  163. DisableParallelToolUse bool `json:"disable_parallel_tool_use,omitempty"`
  164. }
  165. type ClaudeRequest struct {
  166. Model string `json:"model"`
  167. Prompt string `json:"prompt,omitempty"`
  168. System any `json:"system,omitempty"`
  169. Messages []ClaudeMessage `json:"messages,omitempty"`
  170. MaxTokens uint `json:"max_tokens,omitempty"`
  171. MaxTokensToSample uint `json:"max_tokens_to_sample,omitempty"`
  172. StopSequences []string `json:"stop_sequences,omitempty"`
  173. Temperature *float64 `json:"temperature,omitempty"`
  174. TopP float64 `json:"top_p,omitempty"`
  175. TopK int `json:"top_k,omitempty"`
  176. Stream bool `json:"stream,omitempty"`
  177. Tools any `json:"tools,omitempty"`
  178. ContextManagement json.RawMessage `json:"context_management,omitempty"`
  179. OutputConfig json.RawMessage `json:"output_config,omitempty"`
  180. OutputFormat json.RawMessage `json:"output_format,omitempty"`
  181. Container json.RawMessage `json:"container,omitempty"`
  182. ToolChoice any `json:"tool_choice,omitempty"`
  183. Thinking *Thinking `json:"thinking,omitempty"`
  184. McpServers json.RawMessage `json:"mcp_servers,omitempty"`
  185. Metadata json.RawMessage `json:"metadata,omitempty"`
  186. // 服务层级字段,用于指定 API 服务等级。允许透传可能导致实际计费高于预期,默认应过滤
  187. ServiceTier string `json:"service_tier,omitempty"`
  188. }
  189. func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
  190. var tokenCountMeta = types.TokenCountMeta{
  191. TokenType: types.TokenTypeTokenizer,
  192. MaxTokens: int(c.MaxTokens),
  193. }
  194. var texts = make([]string, 0)
  195. var fileMeta = make([]*types.FileMeta, 0)
  196. // system
  197. if c.System != nil {
  198. if c.IsStringSystem() {
  199. sys := c.GetStringSystem()
  200. if sys != "" {
  201. texts = append(texts, sys)
  202. }
  203. } else {
  204. systemMedia := c.ParseSystem()
  205. for _, media := range systemMedia {
  206. switch media.Type {
  207. case "text":
  208. texts = append(texts, media.GetText())
  209. case "image":
  210. if media.Source != nil {
  211. data := media.Source.Url
  212. if data == "" {
  213. data = common.Interface2String(media.Source.Data)
  214. }
  215. if data != "" {
  216. fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
  217. }
  218. }
  219. }
  220. }
  221. }
  222. }
  223. // messages
  224. for _, message := range c.Messages {
  225. tokenCountMeta.MessagesCount++
  226. texts = append(texts, message.Role)
  227. if message.IsStringContent() {
  228. content := message.GetStringContent()
  229. if content != "" {
  230. texts = append(texts, content)
  231. }
  232. continue
  233. }
  234. content, _ := message.ParseContent()
  235. for _, media := range content {
  236. switch media.Type {
  237. case "text":
  238. texts = append(texts, media.GetText())
  239. case "image":
  240. if media.Source != nil {
  241. data := media.Source.Url
  242. if data == "" {
  243. data = common.Interface2String(media.Source.Data)
  244. }
  245. if data != "" {
  246. fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
  247. }
  248. }
  249. case "tool_use":
  250. if media.Name != "" {
  251. texts = append(texts, media.Name)
  252. }
  253. if media.Input != nil {
  254. b, _ := common.Marshal(media.Input)
  255. texts = append(texts, string(b))
  256. }
  257. case "tool_result":
  258. if media.Content != nil {
  259. b, _ := common.Marshal(media.Content)
  260. texts = append(texts, string(b))
  261. }
  262. }
  263. }
  264. }
  265. // tools
  266. if c.Tools != nil {
  267. tools := c.GetTools()
  268. normalTools, webSearchTools := ProcessTools(tools)
  269. if normalTools != nil {
  270. for _, t := range normalTools {
  271. tokenCountMeta.ToolsCount++
  272. if t.Name != "" {
  273. texts = append(texts, t.Name)
  274. }
  275. if t.Description != "" {
  276. texts = append(texts, t.Description)
  277. }
  278. if t.InputSchema != nil {
  279. b, _ := common.Marshal(t.InputSchema)
  280. texts = append(texts, string(b))
  281. }
  282. }
  283. }
  284. if webSearchTools != nil {
  285. for _, t := range webSearchTools {
  286. tokenCountMeta.ToolsCount++
  287. if t.Name != "" {
  288. texts = append(texts, t.Name)
  289. }
  290. if t.UserLocation != nil {
  291. b, _ := common.Marshal(t.UserLocation)
  292. texts = append(texts, string(b))
  293. }
  294. }
  295. }
  296. }
  297. tokenCountMeta.CombineText = strings.Join(texts, "\n")
  298. tokenCountMeta.Files = fileMeta
  299. return &tokenCountMeta
  300. }
  301. func (c *ClaudeRequest) IsStream(ctx *gin.Context) bool {
  302. return c.Stream
  303. }
  304. func (c *ClaudeRequest) SetModelName(modelName string) {
  305. if modelName != "" {
  306. c.Model = modelName
  307. }
  308. }
  309. func (c *ClaudeRequest) SearchToolNameByToolCallId(toolCallId string) string {
  310. for _, message := range c.Messages {
  311. content, _ := message.ParseContent()
  312. for _, mediaMessage := range content {
  313. if mediaMessage.Id == toolCallId {
  314. return mediaMessage.Name
  315. }
  316. }
  317. }
  318. return ""
  319. }
  320. // AddTool 添加工具到请求中
  321. func (c *ClaudeRequest) AddTool(tool any) {
  322. if c.Tools == nil {
  323. c.Tools = make([]any, 0)
  324. }
  325. switch tools := c.Tools.(type) {
  326. case []any:
  327. c.Tools = append(tools, tool)
  328. default:
  329. // 如果Tools不是[]any类型,重新初始化为[]any
  330. c.Tools = []any{tool}
  331. }
  332. }
  333. // GetTools 获取工具列表
  334. func (c *ClaudeRequest) GetTools() []any {
  335. if c.Tools == nil {
  336. return nil
  337. }
  338. switch tools := c.Tools.(type) {
  339. case []any:
  340. return tools
  341. default:
  342. return nil
  343. }
  344. }
  345. // ProcessTools 处理工具列表,支持类型断言
  346. func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
  347. var normalTools []*Tool
  348. var webSearchTools []*ClaudeWebSearchTool
  349. for _, tool := range tools {
  350. switch t := tool.(type) {
  351. case *Tool:
  352. normalTools = append(normalTools, t)
  353. case *ClaudeWebSearchTool:
  354. webSearchTools = append(webSearchTools, t)
  355. case Tool:
  356. normalTools = append(normalTools, &t)
  357. case ClaudeWebSearchTool:
  358. webSearchTools = append(webSearchTools, &t)
  359. default:
  360. // 未知类型,跳过
  361. continue
  362. }
  363. }
  364. return normalTools, webSearchTools
  365. }
  366. type Thinking struct {
  367. Type string `json:"type"`
  368. BudgetTokens *int `json:"budget_tokens,omitempty"`
  369. }
  370. func (c *Thinking) GetBudgetTokens() int {
  371. if c.BudgetTokens == nil {
  372. return 0
  373. }
  374. return *c.BudgetTokens
  375. }
  376. func (c *ClaudeRequest) IsStringSystem() bool {
  377. _, ok := c.System.(string)
  378. return ok
  379. }
  380. func (c *ClaudeRequest) GetStringSystem() string {
  381. if c.IsStringSystem() {
  382. return c.System.(string)
  383. }
  384. return ""
  385. }
  386. func (c *ClaudeRequest) SetStringSystem(system string) {
  387. c.System = system
  388. }
  389. func (c *ClaudeRequest) ParseSystem() []ClaudeMediaMessage {
  390. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.System)
  391. return mediaContent
  392. }
  393. type ClaudeErrorWithStatusCode struct {
  394. Error types.ClaudeError `json:"error"`
  395. StatusCode int `json:"status_code"`
  396. LocalError bool
  397. }
  398. type ClaudeResponse struct {
  399. Id string `json:"id,omitempty"`
  400. Type string `json:"type"`
  401. Role string `json:"role,omitempty"`
  402. Content []ClaudeMediaMessage `json:"content,omitempty"`
  403. Completion string `json:"completion,omitempty"`
  404. StopReason string `json:"stop_reason,omitempty"`
  405. Model string `json:"model,omitempty"`
  406. Error any `json:"error,omitempty"`
  407. Usage *ClaudeUsage `json:"usage,omitempty"`
  408. Index *int `json:"index,omitempty"`
  409. ContentBlock *ClaudeMediaMessage `json:"content_block,omitempty"`
  410. Delta *ClaudeMediaMessage `json:"delta,omitempty"`
  411. Message *ClaudeMediaMessage `json:"message,omitempty"`
  412. }
  413. // set index
  414. func (c *ClaudeResponse) SetIndex(i int) {
  415. c.Index = &i
  416. }
  417. // get index
  418. func (c *ClaudeResponse) GetIndex() int {
  419. if c.Index == nil {
  420. return 0
  421. }
  422. return *c.Index
  423. }
  424. // GetClaudeError 从动态错误类型中提取ClaudeError结构
  425. func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError {
  426. if c.Error == nil {
  427. return nil
  428. }
  429. switch err := c.Error.(type) {
  430. case types.ClaudeError:
  431. return &err
  432. case *types.ClaudeError:
  433. return err
  434. case map[string]interface{}:
  435. // 处理从JSON解析来的map结构
  436. claudeErr := &types.ClaudeError{}
  437. if errType, ok := err["type"].(string); ok {
  438. claudeErr.Type = errType
  439. }
  440. if errMsg, ok := err["message"].(string); ok {
  441. claudeErr.Message = errMsg
  442. }
  443. return claudeErr
  444. case string:
  445. // 处理简单字符串错误
  446. return &types.ClaudeError{
  447. Type: "upstream_error",
  448. Message: err,
  449. }
  450. default:
  451. // 未知类型,尝试转换为字符串
  452. return &types.ClaudeError{
  453. Type: "unknown_upstream_error",
  454. Message: fmt.Sprintf("unknown_error: %v", err),
  455. }
  456. }
  457. }
  458. type ClaudeUsage struct {
  459. InputTokens int `json:"input_tokens"`
  460. CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
  461. CacheReadInputTokens int `json:"cache_read_input_tokens"`
  462. OutputTokens int `json:"output_tokens"`
  463. CacheCreation *ClaudeCacheCreationUsage `json:"cache_creation,omitempty"`
  464. // claude cache 1h
  465. ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"`
  466. ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"`
  467. ServerToolUse *ClaudeServerToolUse `json:"server_tool_use,omitempty"`
  468. }
  469. type ClaudeCacheCreationUsage struct {
  470. Ephemeral5mInputTokens int `json:"ephemeral_5m_input_tokens,omitempty"`
  471. Ephemeral1hInputTokens int `json:"ephemeral_1h_input_tokens,omitempty"`
  472. }
  473. func (u *ClaudeUsage) GetCacheCreation5mTokens() int {
  474. if u == nil || u.CacheCreation == nil {
  475. return 0
  476. }
  477. return u.CacheCreation.Ephemeral5mInputTokens
  478. }
  479. func (u *ClaudeUsage) GetCacheCreation1hTokens() int {
  480. if u == nil || u.CacheCreation == nil {
  481. return 0
  482. }
  483. return u.CacheCreation.Ephemeral1hInputTokens
  484. }
  485. func (u *ClaudeUsage) GetCacheCreationTotalTokens() int {
  486. if u == nil {
  487. return 0
  488. }
  489. if u.CacheCreationInputTokens > 0 {
  490. return u.CacheCreationInputTokens
  491. }
  492. return u.GetCacheCreation5mTokens() + u.GetCacheCreation1hTokens()
  493. }
  494. type ClaudeServerToolUse struct {
  495. WebSearchRequests int `json:"web_search_requests"`
  496. }