claude.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "one-api/common"
  6. "one-api/types"
  7. "strings"
  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) ParseContent() ([]ClaudeMediaMessage, error) {
  132. return common.Any2Type[[]ClaudeMediaMessage](c.Content)
  133. }
  134. type Tool struct {
  135. Name string `json:"name"`
  136. Description string `json:"description,omitempty"`
  137. InputSchema map[string]interface{} `json:"input_schema"`
  138. }
  139. type InputSchema struct {
  140. Type string `json:"type"`
  141. Properties any `json:"properties,omitempty"`
  142. Required any `json:"required,omitempty"`
  143. }
  144. type ClaudeWebSearchTool struct {
  145. Type string `json:"type"`
  146. Name string `json:"name"`
  147. MaxUses int `json:"max_uses,omitempty"`
  148. UserLocation *ClaudeWebSearchUserLocation `json:"user_location,omitempty"`
  149. }
  150. type ClaudeWebSearchUserLocation struct {
  151. Type string `json:"type"`
  152. Timezone string `json:"timezone,omitempty"`
  153. Country string `json:"country,omitempty"`
  154. Region string `json:"region,omitempty"`
  155. City string `json:"city,omitempty"`
  156. }
  157. type ClaudeToolChoice struct {
  158. Type string `json:"type"`
  159. Name string `json:"name,omitempty"`
  160. DisableParallelToolUse bool `json:"disable_parallel_tool_use,omitempty"`
  161. }
  162. type ClaudeRequest struct {
  163. Model string `json:"model"`
  164. Prompt string `json:"prompt,omitempty"`
  165. System any `json:"system,omitempty"`
  166. Messages []ClaudeMessage `json:"messages,omitempty"`
  167. MaxTokens uint `json:"max_tokens,omitempty"`
  168. MaxTokensToSample uint `json:"max_tokens_to_sample,omitempty"`
  169. StopSequences []string `json:"stop_sequences,omitempty"`
  170. Temperature *float64 `json:"temperature,omitempty"`
  171. TopP float64 `json:"top_p,omitempty"`
  172. TopK int `json:"top_k,omitempty"`
  173. //ClaudeMetadata `json:"metadata,omitempty"`
  174. Stream bool `json:"stream,omitempty"`
  175. Tools any `json:"tools,omitempty"`
  176. ContextManagement json.RawMessage `json:"context_management,omitempty"`
  177. ToolChoice any `json:"tool_choice,omitempty"`
  178. Thinking *Thinking `json:"thinking,omitempty"`
  179. }
  180. func (c *ClaudeRequest) GetTokenCountMeta() *types.TokenCountMeta {
  181. var tokenCountMeta = types.TokenCountMeta{
  182. TokenType: types.TokenTypeTokenizer,
  183. MaxTokens: int(c.MaxTokens),
  184. }
  185. var texts = make([]string, 0)
  186. var fileMeta = make([]*types.FileMeta, 0)
  187. // system
  188. if c.System != nil {
  189. if c.IsStringSystem() {
  190. sys := c.GetStringSystem()
  191. if sys != "" {
  192. texts = append(texts, sys)
  193. }
  194. } else {
  195. systemMedia := c.ParseSystem()
  196. for _, media := range systemMedia {
  197. switch media.Type {
  198. case "text":
  199. texts = append(texts, media.GetText())
  200. case "image":
  201. if media.Source != nil {
  202. data := media.Source.Url
  203. if data == "" {
  204. data = common.Interface2String(media.Source.Data)
  205. }
  206. if data != "" {
  207. fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
  208. }
  209. }
  210. }
  211. }
  212. }
  213. }
  214. // messages
  215. for _, message := range c.Messages {
  216. tokenCountMeta.MessagesCount++
  217. texts = append(texts, message.Role)
  218. if message.IsStringContent() {
  219. content := message.GetStringContent()
  220. if content != "" {
  221. texts = append(texts, content)
  222. }
  223. continue
  224. }
  225. content, _ := message.ParseContent()
  226. for _, media := range content {
  227. switch media.Type {
  228. case "text":
  229. texts = append(texts, media.GetText())
  230. case "image":
  231. if media.Source != nil {
  232. data := media.Source.Url
  233. if data == "" {
  234. data = common.Interface2String(media.Source.Data)
  235. }
  236. if data != "" {
  237. fileMeta = append(fileMeta, &types.FileMeta{FileType: types.FileTypeImage, OriginData: data})
  238. }
  239. }
  240. case "tool_use":
  241. if media.Name != "" {
  242. texts = append(texts, media.Name)
  243. }
  244. if media.Input != nil {
  245. b, _ := common.Marshal(media.Input)
  246. texts = append(texts, string(b))
  247. }
  248. case "tool_result":
  249. if media.Content != nil {
  250. b, _ := common.Marshal(media.Content)
  251. texts = append(texts, string(b))
  252. }
  253. }
  254. }
  255. }
  256. // tools
  257. if c.Tools != nil {
  258. tools := c.GetTools()
  259. normalTools, webSearchTools := ProcessTools(tools)
  260. if normalTools != nil {
  261. for _, t := range normalTools {
  262. tokenCountMeta.ToolsCount++
  263. if t.Name != "" {
  264. texts = append(texts, t.Name)
  265. }
  266. if t.Description != "" {
  267. texts = append(texts, t.Description)
  268. }
  269. if t.InputSchema != nil {
  270. b, _ := common.Marshal(t.InputSchema)
  271. texts = append(texts, string(b))
  272. }
  273. }
  274. }
  275. if webSearchTools != nil {
  276. for _, t := range webSearchTools {
  277. tokenCountMeta.ToolsCount++
  278. if t.Name != "" {
  279. texts = append(texts, t.Name)
  280. }
  281. if t.UserLocation != nil {
  282. b, _ := common.Marshal(t.UserLocation)
  283. texts = append(texts, string(b))
  284. }
  285. }
  286. }
  287. }
  288. tokenCountMeta.CombineText = strings.Join(texts, "\n")
  289. tokenCountMeta.Files = fileMeta
  290. return &tokenCountMeta
  291. }
  292. func (c *ClaudeRequest) IsStream(ctx *gin.Context) bool {
  293. return c.Stream
  294. }
  295. func (c *ClaudeRequest) SetModelName(modelName string) {
  296. if modelName != "" {
  297. c.Model = modelName
  298. }
  299. }
  300. func (c *ClaudeRequest) SearchToolNameByToolCallId(toolCallId string) string {
  301. for _, message := range c.Messages {
  302. content, _ := message.ParseContent()
  303. for _, mediaMessage := range content {
  304. if mediaMessage.Id == toolCallId {
  305. return mediaMessage.Name
  306. }
  307. }
  308. }
  309. return ""
  310. }
  311. // AddTool 添加工具到请求中
  312. func (c *ClaudeRequest) AddTool(tool any) {
  313. if c.Tools == nil {
  314. c.Tools = make([]any, 0)
  315. }
  316. switch tools := c.Tools.(type) {
  317. case []any:
  318. c.Tools = append(tools, tool)
  319. default:
  320. // 如果Tools不是[]any类型,重新初始化为[]any
  321. c.Tools = []any{tool}
  322. }
  323. }
  324. // GetTools 获取工具列表
  325. func (c *ClaudeRequest) GetTools() []any {
  326. if c.Tools == nil {
  327. return nil
  328. }
  329. switch tools := c.Tools.(type) {
  330. case []any:
  331. return tools
  332. default:
  333. return nil
  334. }
  335. }
  336. // ProcessTools 处理工具列表,支持类型断言
  337. func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
  338. var normalTools []*Tool
  339. var webSearchTools []*ClaudeWebSearchTool
  340. for _, tool := range tools {
  341. switch t := tool.(type) {
  342. case *Tool:
  343. normalTools = append(normalTools, t)
  344. case *ClaudeWebSearchTool:
  345. webSearchTools = append(webSearchTools, t)
  346. case Tool:
  347. normalTools = append(normalTools, &t)
  348. case ClaudeWebSearchTool:
  349. webSearchTools = append(webSearchTools, &t)
  350. default:
  351. // 未知类型,跳过
  352. continue
  353. }
  354. }
  355. return normalTools, webSearchTools
  356. }
  357. type Thinking struct {
  358. Type string `json:"type"`
  359. BudgetTokens *int `json:"budget_tokens,omitempty"`
  360. }
  361. func (c *Thinking) GetBudgetTokens() int {
  362. if c.BudgetTokens == nil {
  363. return 0
  364. }
  365. return *c.BudgetTokens
  366. }
  367. func (c *ClaudeRequest) IsStringSystem() bool {
  368. _, ok := c.System.(string)
  369. return ok
  370. }
  371. func (c *ClaudeRequest) GetStringSystem() string {
  372. if c.IsStringSystem() {
  373. return c.System.(string)
  374. }
  375. return ""
  376. }
  377. func (c *ClaudeRequest) SetStringSystem(system string) {
  378. c.System = system
  379. }
  380. func (c *ClaudeRequest) ParseSystem() []ClaudeMediaMessage {
  381. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.System)
  382. return mediaContent
  383. }
  384. type ClaudeErrorWithStatusCode struct {
  385. Error types.ClaudeError `json:"error"`
  386. StatusCode int `json:"status_code"`
  387. LocalError bool
  388. }
  389. type ClaudeResponse struct {
  390. Id string `json:"id,omitempty"`
  391. Type string `json:"type"`
  392. Role string `json:"role,omitempty"`
  393. Content []ClaudeMediaMessage `json:"content,omitempty"`
  394. Completion string `json:"completion,omitempty"`
  395. StopReason string `json:"stop_reason,omitempty"`
  396. Model string `json:"model,omitempty"`
  397. Error any `json:"error,omitempty"`
  398. Usage *ClaudeUsage `json:"usage,omitempty"`
  399. Index *int `json:"index,omitempty"`
  400. ContentBlock *ClaudeMediaMessage `json:"content_block,omitempty"`
  401. Delta *ClaudeMediaMessage `json:"delta,omitempty"`
  402. Message *ClaudeMediaMessage `json:"message,omitempty"`
  403. }
  404. // set index
  405. func (c *ClaudeResponse) SetIndex(i int) {
  406. c.Index = &i
  407. }
  408. // get index
  409. func (c *ClaudeResponse) GetIndex() int {
  410. if c.Index == nil {
  411. return 0
  412. }
  413. return *c.Index
  414. }
  415. // GetClaudeError 从动态错误类型中提取ClaudeError结构
  416. func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError {
  417. if c.Error == nil {
  418. return nil
  419. }
  420. switch err := c.Error.(type) {
  421. case types.ClaudeError:
  422. return &err
  423. case *types.ClaudeError:
  424. return err
  425. case map[string]interface{}:
  426. // 处理从JSON解析来的map结构
  427. claudeErr := &types.ClaudeError{}
  428. if errType, ok := err["type"].(string); ok {
  429. claudeErr.Type = errType
  430. }
  431. if errMsg, ok := err["message"].(string); ok {
  432. claudeErr.Message = errMsg
  433. }
  434. return claudeErr
  435. case string:
  436. // 处理简单字符串错误
  437. return &types.ClaudeError{
  438. Type: "upstream_error",
  439. Message: err,
  440. }
  441. default:
  442. // 未知类型,尝试转换为字符串
  443. return &types.ClaudeError{
  444. Type: "unknown_upstream_error",
  445. Message: fmt.Sprintf("unknown_error: %v", err),
  446. }
  447. }
  448. }
  449. type ClaudeUsage struct {
  450. InputTokens int `json:"input_tokens"`
  451. CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
  452. CacheReadInputTokens int `json:"cache_read_input_tokens"`
  453. OutputTokens int `json:"output_tokens"`
  454. ServerToolUse *ClaudeServerToolUse `json:"server_tool_use,omitempty"`
  455. }
  456. type ClaudeServerToolUse struct {
  457. WebSearchRequests int `json:"web_search_requests"`
  458. }