claude.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. package dto
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "one-api/common"
  6. "one-api/types"
  7. )
  8. type ClaudeMetadata struct {
  9. UserId string `json:"user_id"`
  10. }
  11. type ClaudeMediaMessage struct {
  12. Type string `json:"type,omitempty"`
  13. Text *string `json:"text,omitempty"`
  14. Model string `json:"model,omitempty"`
  15. Source *ClaudeMessageSource `json:"source,omitempty"`
  16. Usage *ClaudeUsage `json:"usage,omitempty"`
  17. StopReason *string `json:"stop_reason,omitempty"`
  18. PartialJson *string `json:"partial_json,omitempty"`
  19. Role string `json:"role,omitempty"`
  20. Thinking string `json:"thinking,omitempty"`
  21. Signature string `json:"signature,omitempty"`
  22. Delta string `json:"delta,omitempty"`
  23. CacheControl json.RawMessage `json:"cache_control,omitempty"`
  24. // tool_calls
  25. Id string `json:"id,omitempty"`
  26. Name string `json:"name,omitempty"`
  27. Input any `json:"input,omitempty"`
  28. Content any `json:"content,omitempty"`
  29. ToolUseId string `json:"tool_use_id,omitempty"`
  30. }
  31. func (c *ClaudeMediaMessage) SetText(s string) {
  32. c.Text = &s
  33. }
  34. func (c *ClaudeMediaMessage) GetText() string {
  35. if c.Text == nil {
  36. return ""
  37. }
  38. return *c.Text
  39. }
  40. func (c *ClaudeMediaMessage) IsStringContent() bool {
  41. if c.Content == nil {
  42. return false
  43. }
  44. _, ok := c.Content.(string)
  45. if ok {
  46. return true
  47. }
  48. return false
  49. }
  50. func (c *ClaudeMediaMessage) GetStringContent() string {
  51. if c.Content == nil {
  52. return ""
  53. }
  54. switch c.Content.(type) {
  55. case string:
  56. return c.Content.(string)
  57. case []any:
  58. var contentStr string
  59. for _, contentItem := range c.Content.([]any) {
  60. contentMap, ok := contentItem.(map[string]any)
  61. if !ok {
  62. continue
  63. }
  64. if contentMap["type"] == ContentTypeText {
  65. if subStr, ok := contentMap["text"].(string); ok {
  66. contentStr += subStr
  67. }
  68. }
  69. }
  70. return contentStr
  71. }
  72. return ""
  73. }
  74. func (c *ClaudeMediaMessage) GetJsonRowString() string {
  75. jsonContent, _ := json.Marshal(c)
  76. return string(jsonContent)
  77. }
  78. func (c *ClaudeMediaMessage) SetContent(content any) {
  79. c.Content = content
  80. }
  81. func (c *ClaudeMediaMessage) ParseMediaContent() []ClaudeMediaMessage {
  82. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.Content)
  83. return mediaContent
  84. }
  85. type ClaudeMessageSource struct {
  86. Type string `json:"type"`
  87. MediaType string `json:"media_type,omitempty"`
  88. Data any `json:"data,omitempty"`
  89. Url string `json:"url,omitempty"`
  90. }
  91. type ClaudeMessage struct {
  92. Role string `json:"role"`
  93. Content any `json:"content"`
  94. }
  95. func (c *ClaudeMessage) IsStringContent() bool {
  96. if c.Content == nil {
  97. return false
  98. }
  99. _, ok := c.Content.(string)
  100. return ok
  101. }
  102. func (c *ClaudeMessage) GetStringContent() string {
  103. if c.Content == nil {
  104. return ""
  105. }
  106. switch c.Content.(type) {
  107. case string:
  108. return c.Content.(string)
  109. case []any:
  110. var contentStr string
  111. for _, contentItem := range c.Content.([]any) {
  112. contentMap, ok := contentItem.(map[string]any)
  113. if !ok {
  114. continue
  115. }
  116. if contentMap["type"] == ContentTypeText {
  117. if subStr, ok := contentMap["text"].(string); ok {
  118. contentStr += subStr
  119. }
  120. }
  121. }
  122. return contentStr
  123. }
  124. return ""
  125. }
  126. func (c *ClaudeMessage) SetStringContent(content string) {
  127. c.Content = content
  128. }
  129. func (c *ClaudeMessage) ParseContent() ([]ClaudeMediaMessage, error) {
  130. return common.Any2Type[[]ClaudeMediaMessage](c.Content)
  131. }
  132. type Tool struct {
  133. Name string `json:"name"`
  134. Description string `json:"description,omitempty"`
  135. InputSchema map[string]interface{} `json:"input_schema"`
  136. }
  137. type InputSchema struct {
  138. Type string `json:"type"`
  139. Properties any `json:"properties,omitempty"`
  140. Required any `json:"required,omitempty"`
  141. }
  142. type ClaudeWebSearchTool struct {
  143. Type string `json:"type"`
  144. Name string `json:"name"`
  145. MaxUses int `json:"max_uses,omitempty"`
  146. UserLocation *ClaudeWebSearchUserLocation `json:"user_location,omitempty"`
  147. }
  148. type ClaudeWebSearchUserLocation struct {
  149. Type string `json:"type"`
  150. Timezone string `json:"timezone,omitempty"`
  151. Country string `json:"country,omitempty"`
  152. Region string `json:"region,omitempty"`
  153. City string `json:"city,omitempty"`
  154. }
  155. type ClaudeToolChoice struct {
  156. Type string `json:"type"`
  157. Name string `json:"name,omitempty"`
  158. DisableParallelToolUse bool `json:"disable_parallel_tool_use,omitempty"`
  159. }
  160. type ClaudeRequest struct {
  161. Model string `json:"model"`
  162. Prompt string `json:"prompt,omitempty"`
  163. System any `json:"system,omitempty"`
  164. Messages []ClaudeMessage `json:"messages,omitempty"`
  165. MaxTokens uint `json:"max_tokens,omitempty"`
  166. MaxTokensToSample uint `json:"max_tokens_to_sample,omitempty"`
  167. StopSequences []string `json:"stop_sequences,omitempty"`
  168. Temperature *float64 `json:"temperature,omitempty"`
  169. TopP float64 `json:"top_p,omitempty"`
  170. TopK int `json:"top_k,omitempty"`
  171. //ClaudeMetadata `json:"metadata,omitempty"`
  172. Stream bool `json:"stream,omitempty"`
  173. Tools any `json:"tools,omitempty"`
  174. ToolChoice any `json:"tool_choice,omitempty"`
  175. Thinking *Thinking `json:"thinking,omitempty"`
  176. }
  177. func (c *ClaudeRequest) SearchToolNameByToolCallId(toolCallId string) string {
  178. for _, message := range c.Messages {
  179. content, _ := message.ParseContent()
  180. for _, mediaMessage := range content {
  181. if mediaMessage.Id == toolCallId {
  182. return mediaMessage.Name
  183. }
  184. }
  185. }
  186. return ""
  187. }
  188. // AddTool 添加工具到请求中
  189. func (c *ClaudeRequest) AddTool(tool any) {
  190. if c.Tools == nil {
  191. c.Tools = make([]any, 0)
  192. }
  193. switch tools := c.Tools.(type) {
  194. case []any:
  195. c.Tools = append(tools, tool)
  196. default:
  197. // 如果Tools不是[]any类型,重新初始化为[]any
  198. c.Tools = []any{tool}
  199. }
  200. }
  201. // GetTools 获取工具列表
  202. func (c *ClaudeRequest) GetTools() []any {
  203. if c.Tools == nil {
  204. return nil
  205. }
  206. switch tools := c.Tools.(type) {
  207. case []any:
  208. return tools
  209. default:
  210. return nil
  211. }
  212. }
  213. // ProcessTools 处理工具列表,支持类型断言
  214. func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
  215. var normalTools []*Tool
  216. var webSearchTools []*ClaudeWebSearchTool
  217. for _, tool := range tools {
  218. switch t := tool.(type) {
  219. case *Tool:
  220. normalTools = append(normalTools, t)
  221. case *ClaudeWebSearchTool:
  222. webSearchTools = append(webSearchTools, t)
  223. case Tool:
  224. normalTools = append(normalTools, &t)
  225. case ClaudeWebSearchTool:
  226. webSearchTools = append(webSearchTools, &t)
  227. default:
  228. // 未知类型,跳过
  229. continue
  230. }
  231. }
  232. return normalTools, webSearchTools
  233. }
  234. type Thinking struct {
  235. Type string `json:"type"`
  236. BudgetTokens *int `json:"budget_tokens,omitempty"`
  237. }
  238. func (c *Thinking) GetBudgetTokens() int {
  239. if c.BudgetTokens == nil {
  240. return 0
  241. }
  242. return *c.BudgetTokens
  243. }
  244. func (c *ClaudeRequest) IsStringSystem() bool {
  245. _, ok := c.System.(string)
  246. return ok
  247. }
  248. func (c *ClaudeRequest) GetStringSystem() string {
  249. if c.IsStringSystem() {
  250. return c.System.(string)
  251. }
  252. return ""
  253. }
  254. func (c *ClaudeRequest) SetStringSystem(system string) {
  255. c.System = system
  256. }
  257. func (c *ClaudeRequest) ParseSystem() []ClaudeMediaMessage {
  258. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.System)
  259. return mediaContent
  260. }
  261. type ClaudeErrorWithStatusCode struct {
  262. Error types.ClaudeError `json:"error"`
  263. StatusCode int `json:"status_code"`
  264. LocalError bool
  265. }
  266. type ClaudeResponse struct {
  267. Id string `json:"id,omitempty"`
  268. Type string `json:"type"`
  269. Role string `json:"role,omitempty"`
  270. Content []ClaudeMediaMessage `json:"content,omitempty"`
  271. Completion string `json:"completion,omitempty"`
  272. StopReason string `json:"stop_reason,omitempty"`
  273. Model string `json:"model,omitempty"`
  274. Error any `json:"error,omitempty"`
  275. Usage *ClaudeUsage `json:"usage,omitempty"`
  276. Index *int `json:"index,omitempty"`
  277. ContentBlock *ClaudeMediaMessage `json:"content_block,omitempty"`
  278. Delta *ClaudeMediaMessage `json:"delta,omitempty"`
  279. Message *ClaudeMediaMessage `json:"message,omitempty"`
  280. }
  281. // set index
  282. func (c *ClaudeResponse) SetIndex(i int) {
  283. c.Index = &i
  284. }
  285. // get index
  286. func (c *ClaudeResponse) GetIndex() int {
  287. if c.Index == nil {
  288. return 0
  289. }
  290. return *c.Index
  291. }
  292. // GetClaudeError 从动态错误类型中提取ClaudeError结构
  293. func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError {
  294. if c.Error == nil {
  295. return nil
  296. }
  297. switch err := c.Error.(type) {
  298. case types.ClaudeError:
  299. return &err
  300. case *types.ClaudeError:
  301. return err
  302. case map[string]interface{}:
  303. // 处理从JSON解析来的map结构
  304. claudeErr := &types.ClaudeError{}
  305. if errType, ok := err["type"].(string); ok {
  306. claudeErr.Type = errType
  307. }
  308. if errMsg, ok := err["message"].(string); ok {
  309. claudeErr.Message = errMsg
  310. }
  311. return claudeErr
  312. case string:
  313. // 处理简单字符串错误
  314. return &types.ClaudeError{
  315. Type: "error",
  316. Message: err,
  317. }
  318. default:
  319. // 未知类型,尝试转换为字符串
  320. return &types.ClaudeError{
  321. Type: "unknown_error",
  322. Message: fmt.Sprintf("%v", err),
  323. }
  324. }
  325. }
  326. type ClaudeUsage struct {
  327. InputTokens int `json:"input_tokens"`
  328. CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
  329. CacheReadInputTokens int `json:"cache_read_input_tokens"`
  330. OutputTokens int `json:"output_tokens"`
  331. ServerToolUse *ClaudeServerToolUse `json:"server_tool_use,omitempty"`
  332. }
  333. type ClaudeServerToolUse struct {
  334. WebSearchRequests int `json:"web_search_requests"`
  335. }