claude.go 15 KB

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