claude.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  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. // InferenceGeo controls Claude data residency region.
  171. // This field is filtered by default and can be enabled via channel setting allow_inference_geo.
  172. InferenceGeo string `json:"inference_geo,omitempty"`
  173. MaxTokens *uint `json:"max_tokens,omitempty"`
  174. MaxTokensToSample *uint `json:"max_tokens_to_sample,omitempty"`
  175. StopSequences []string `json:"stop_sequences,omitempty"`
  176. Temperature *float64 `json:"temperature,omitempty"`
  177. TopP *float64 `json:"top_p,omitempty"`
  178. TopK *int `json:"top_k,omitempty"`
  179. Stream *bool `json:"stream,omitempty"`
  180. Tools any `json:"tools,omitempty"`
  181. ContextManagement json.RawMessage `json:"context_management,omitempty"`
  182. OutputConfig json.RawMessage `json:"output_config,omitempty"`
  183. OutputFormat json.RawMessage `json:"output_format,omitempty"`
  184. Container json.RawMessage `json:"container,omitempty"`
  185. ToolChoice any `json:"tool_choice,omitempty"`
  186. Thinking *Thinking `json:"thinking,omitempty"`
  187. McpServers json.RawMessage `json:"mcp_servers,omitempty"`
  188. Metadata json.RawMessage `json:"metadata,omitempty"`
  189. // ServiceTier specifies upstream service level and may affect billing.
  190. // This field is filtered by default and can be enabled via channel setting allow_service_tier.
  191. ServiceTier string `json:"service_tier,omitempty"`
  192. }
  193. // createClaudeFileSource 根据数据内容创建正确类型的 FileSource
  194. func createClaudeFileSource(data string) *types.FileSource {
  195. if strings.HasPrefix(data, "http://") || strings.HasPrefix(data, "https://") {
  196. return types.NewURLFileSource(data)
  197. }
  198. return types.NewBase64FileSource(data, "")
  199. }
  200. func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
  201. maxTokens := 0
  202. if c.MaxTokens != nil {
  203. maxTokens = int(*c.MaxTokens)
  204. }
  205. var tokenCountMeta = types.TokenCountMeta{
  206. TokenType: types.TokenTypeTokenizer,
  207. MaxTokens: maxTokens,
  208. }
  209. var texts = make([]string, 0)
  210. var fileMeta = make([]*types.FileMeta, 0)
  211. // system
  212. if c.System != nil {
  213. if c.IsStringSystem() {
  214. sys := c.GetStringSystem()
  215. if sys != "" {
  216. texts = append(texts, sys)
  217. }
  218. } else {
  219. systemMedia := c.ParseSystem()
  220. for _, media := range systemMedia {
  221. switch media.Type {
  222. case "text":
  223. texts = append(texts, media.GetText())
  224. case "image":
  225. if media.Source != nil {
  226. data := media.Source.Url
  227. if data == "" {
  228. data = common.Interface2String(media.Source.Data)
  229. }
  230. if data != "" {
  231. fileMeta = append(fileMeta, &types.FileMeta{
  232. FileType: types.FileTypeImage,
  233. Source: createClaudeFileSource(data),
  234. })
  235. }
  236. }
  237. }
  238. }
  239. }
  240. }
  241. // messages
  242. for _, message := range c.Messages {
  243. tokenCountMeta.MessagesCount++
  244. texts = append(texts, message.Role)
  245. if message.IsStringContent() {
  246. content := message.GetStringContent()
  247. if content != "" {
  248. texts = append(texts, content)
  249. }
  250. continue
  251. }
  252. content, _ := message.ParseContent()
  253. for _, media := range content {
  254. switch media.Type {
  255. case "text":
  256. texts = append(texts, media.GetText())
  257. case "image":
  258. if media.Source != nil {
  259. data := media.Source.Url
  260. if data == "" {
  261. data = common.Interface2String(media.Source.Data)
  262. }
  263. if data != "" {
  264. fileMeta = append(fileMeta, &types.FileMeta{
  265. FileType: types.FileTypeImage,
  266. Source: createClaudeFileSource(data),
  267. })
  268. }
  269. }
  270. case "tool_use":
  271. if media.Name != "" {
  272. texts = append(texts, media.Name)
  273. }
  274. if media.Input != nil {
  275. b, _ := common.Marshal(media.Input)
  276. texts = append(texts, string(b))
  277. }
  278. case "tool_result":
  279. if media.Content != nil {
  280. b, _ := common.Marshal(media.Content)
  281. texts = append(texts, string(b))
  282. }
  283. }
  284. }
  285. }
  286. // tools
  287. if c.Tools != nil {
  288. tools := c.GetTools()
  289. normalTools, webSearchTools := ProcessTools(tools)
  290. if normalTools != nil {
  291. for _, t := range normalTools {
  292. tokenCountMeta.ToolsCount++
  293. if t.Name != "" {
  294. texts = append(texts, t.Name)
  295. }
  296. if t.Description != "" {
  297. texts = append(texts, t.Description)
  298. }
  299. if t.InputSchema != nil {
  300. b, _ := common.Marshal(t.InputSchema)
  301. texts = append(texts, string(b))
  302. }
  303. }
  304. }
  305. if webSearchTools != nil {
  306. for _, t := range webSearchTools {
  307. tokenCountMeta.ToolsCount++
  308. if t.Name != "" {
  309. texts = append(texts, t.Name)
  310. }
  311. if t.UserLocation != nil {
  312. b, _ := common.Marshal(t.UserLocation)
  313. texts = append(texts, string(b))
  314. }
  315. }
  316. }
  317. }
  318. tokenCountMeta.CombineText = strings.Join(texts, "\n")
  319. tokenCountMeta.Files = fileMeta
  320. return &tokenCountMeta
  321. }
  322. func (c *ClaudeRequest) IsStream(ctx *gin.Context) bool {
  323. if c.Stream == nil {
  324. return false
  325. }
  326. return *c.Stream
  327. }
  328. func (c *ClaudeRequest) SetModelName(modelName string) {
  329. if modelName != "" {
  330. c.Model = modelName
  331. }
  332. }
  333. func (c *ClaudeRequest) SearchToolNameByToolCallId(toolCallId string) string {
  334. for _, message := range c.Messages {
  335. content, _ := message.ParseContent()
  336. for _, mediaMessage := range content {
  337. if mediaMessage.Id == toolCallId {
  338. return mediaMessage.Name
  339. }
  340. }
  341. }
  342. return ""
  343. }
  344. // AddTool 添加工具到请求中
  345. func (c *ClaudeRequest) AddTool(tool any) {
  346. if c.Tools == nil {
  347. c.Tools = make([]any, 0)
  348. }
  349. switch tools := c.Tools.(type) {
  350. case []any:
  351. c.Tools = append(tools, tool)
  352. default:
  353. // 如果Tools不是[]any类型,重新初始化为[]any
  354. c.Tools = []any{tool}
  355. }
  356. }
  357. // GetTools 获取工具列表
  358. func (c *ClaudeRequest) GetTools() []any {
  359. if c.Tools == nil {
  360. return nil
  361. }
  362. switch tools := c.Tools.(type) {
  363. case []any:
  364. return tools
  365. default:
  366. return nil
  367. }
  368. }
  369. // ProcessTools 处理工具列表,支持类型断言
  370. func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
  371. var normalTools []*Tool
  372. var webSearchTools []*ClaudeWebSearchTool
  373. for _, tool := range tools {
  374. switch t := tool.(type) {
  375. case *Tool:
  376. normalTools = append(normalTools, t)
  377. case *ClaudeWebSearchTool:
  378. webSearchTools = append(webSearchTools, t)
  379. case Tool:
  380. normalTools = append(normalTools, &t)
  381. case ClaudeWebSearchTool:
  382. webSearchTools = append(webSearchTools, &t)
  383. default:
  384. // 未知类型,跳过
  385. continue
  386. }
  387. }
  388. return normalTools, webSearchTools
  389. }
  390. type Thinking struct {
  391. Type string `json:"type"`
  392. BudgetTokens *int `json:"budget_tokens,omitempty"`
  393. }
  394. func (c *Thinking) GetBudgetTokens() int {
  395. if c.BudgetTokens == nil {
  396. return 0
  397. }
  398. return *c.BudgetTokens
  399. }
  400. func (c *ClaudeRequest) IsStringSystem() bool {
  401. _, ok := c.System.(string)
  402. return ok
  403. }
  404. func (c *ClaudeRequest) GetStringSystem() string {
  405. if c.IsStringSystem() {
  406. return c.System.(string)
  407. }
  408. return ""
  409. }
  410. func (c *ClaudeRequest) SetStringSystem(system string) {
  411. c.System = system
  412. }
  413. func (c *ClaudeRequest) ParseSystem() []ClaudeMediaMessage {
  414. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.System)
  415. return mediaContent
  416. }
  417. type ClaudeErrorWithStatusCode struct {
  418. Error types.ClaudeError `json:"error"`
  419. StatusCode int `json:"status_code"`
  420. LocalError bool
  421. }
  422. type ClaudeResponse struct {
  423. Id string `json:"id,omitempty"`
  424. Type string `json:"type"`
  425. Role string `json:"role,omitempty"`
  426. Content []ClaudeMediaMessage `json:"content,omitempty"`
  427. Completion string `json:"completion,omitempty"`
  428. StopReason string `json:"stop_reason,omitempty"`
  429. Model string `json:"model,omitempty"`
  430. Error any `json:"error,omitempty"`
  431. Usage *ClaudeUsage `json:"usage,omitempty"`
  432. Index *int `json:"index,omitempty"`
  433. ContentBlock *ClaudeMediaMessage `json:"content_block,omitempty"`
  434. Delta *ClaudeMediaMessage `json:"delta,omitempty"`
  435. Message *ClaudeMediaMessage `json:"message,omitempty"`
  436. }
  437. // set index
  438. func (c *ClaudeResponse) SetIndex(i int) {
  439. c.Index = &i
  440. }
  441. // get index
  442. func (c *ClaudeResponse) GetIndex() int {
  443. if c.Index == nil {
  444. return 0
  445. }
  446. return *c.Index
  447. }
  448. // GetClaudeError 从动态错误类型中提取ClaudeError结构
  449. func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError {
  450. if c.Error == nil {
  451. return nil
  452. }
  453. switch err := c.Error.(type) {
  454. case types.ClaudeError:
  455. return &err
  456. case *types.ClaudeError:
  457. return err
  458. case map[string]interface{}:
  459. // 处理从JSON解析来的map结构
  460. claudeErr := &types.ClaudeError{}
  461. if errType, ok := err["type"].(string); ok {
  462. claudeErr.Type = errType
  463. }
  464. if errMsg, ok := err["message"].(string); ok {
  465. claudeErr.Message = errMsg
  466. }
  467. return claudeErr
  468. case string:
  469. // 处理简单字符串错误
  470. return &types.ClaudeError{
  471. Type: "upstream_error",
  472. Message: err,
  473. }
  474. default:
  475. // 未知类型,尝试转换为字符串
  476. return &types.ClaudeError{
  477. Type: "unknown_upstream_error",
  478. Message: fmt.Sprintf("unknown_error: %v", err),
  479. }
  480. }
  481. }
  482. type ClaudeUsage struct {
  483. InputTokens int `json:"input_tokens"`
  484. CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
  485. CacheReadInputTokens int `json:"cache_read_input_tokens"`
  486. OutputTokens int `json:"output_tokens"`
  487. CacheCreation *ClaudeCacheCreationUsage `json:"cache_creation,omitempty"`
  488. // claude cache 1h
  489. ClaudeCacheCreation5mTokens int `json:"claude_cache_creation_5_m_tokens"`
  490. ClaudeCacheCreation1hTokens int `json:"claude_cache_creation_1_h_tokens"`
  491. ServerToolUse *ClaudeServerToolUse `json:"server_tool_use,omitempty"`
  492. }
  493. type ClaudeCacheCreationUsage struct {
  494. Ephemeral5mInputTokens int `json:"ephemeral_5m_input_tokens,omitempty"`
  495. Ephemeral1hInputTokens int `json:"ephemeral_1h_input_tokens,omitempty"`
  496. }
  497. func (u *ClaudeUsage) GetCacheCreation5mTokens() int {
  498. if u == nil || u.CacheCreation == nil {
  499. return 0
  500. }
  501. return u.CacheCreation.Ephemeral5mInputTokens
  502. }
  503. func (u *ClaudeUsage) GetCacheCreation1hTokens() int {
  504. if u == nil || u.CacheCreation == nil {
  505. return 0
  506. }
  507. return u.CacheCreation.Ephemeral1hInputTokens
  508. }
  509. func (u *ClaudeUsage) GetCacheCreationTotalTokens() int {
  510. if u == nil {
  511. return 0
  512. }
  513. if u.CacheCreationInputTokens > 0 {
  514. return u.CacheCreationInputTokens
  515. }
  516. return u.GetCacheCreation5mTokens() + u.GetCacheCreation1hTokens()
  517. }
  518. type ClaudeServerToolUse struct {
  519. WebSearchRequests int `json:"web_search_requests"`
  520. }