claude.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. // AddTool 添加工具到请求中
  178. func (c *ClaudeRequest) AddTool(tool any) {
  179. if c.Tools == nil {
  180. c.Tools = make([]any, 0)
  181. }
  182. switch tools := c.Tools.(type) {
  183. case []any:
  184. c.Tools = append(tools, tool)
  185. default:
  186. // 如果Tools不是[]any类型,重新初始化为[]any
  187. c.Tools = []any{tool}
  188. }
  189. }
  190. // GetTools 获取工具列表
  191. func (c *ClaudeRequest) GetTools() []any {
  192. if c.Tools == nil {
  193. return nil
  194. }
  195. switch tools := c.Tools.(type) {
  196. case []any:
  197. return tools
  198. default:
  199. return nil
  200. }
  201. }
  202. // ProcessTools 处理工具列表,支持类型断言
  203. func ProcessTools(tools []any) ([]*Tool, []*ClaudeWebSearchTool) {
  204. var normalTools []*Tool
  205. var webSearchTools []*ClaudeWebSearchTool
  206. for _, tool := range tools {
  207. switch t := tool.(type) {
  208. case *Tool:
  209. normalTools = append(normalTools, t)
  210. case *ClaudeWebSearchTool:
  211. webSearchTools = append(webSearchTools, t)
  212. case Tool:
  213. normalTools = append(normalTools, &t)
  214. case ClaudeWebSearchTool:
  215. webSearchTools = append(webSearchTools, &t)
  216. default:
  217. // 未知类型,跳过
  218. continue
  219. }
  220. }
  221. return normalTools, webSearchTools
  222. }
  223. type Thinking struct {
  224. Type string `json:"type"`
  225. BudgetTokens *int `json:"budget_tokens,omitempty"`
  226. }
  227. func (c *Thinking) GetBudgetTokens() int {
  228. if c.BudgetTokens == nil {
  229. return 0
  230. }
  231. return *c.BudgetTokens
  232. }
  233. func (c *ClaudeRequest) IsStringSystem() bool {
  234. _, ok := c.System.(string)
  235. return ok
  236. }
  237. func (c *ClaudeRequest) GetStringSystem() string {
  238. if c.IsStringSystem() {
  239. return c.System.(string)
  240. }
  241. return ""
  242. }
  243. func (c *ClaudeRequest) SetStringSystem(system string) {
  244. c.System = system
  245. }
  246. func (c *ClaudeRequest) ParseSystem() []ClaudeMediaMessage {
  247. mediaContent, _ := common.Any2Type[[]ClaudeMediaMessage](c.System)
  248. return mediaContent
  249. }
  250. type ClaudeErrorWithStatusCode struct {
  251. Error types.ClaudeError `json:"error"`
  252. StatusCode int `json:"status_code"`
  253. LocalError bool
  254. }
  255. type ClaudeResponse struct {
  256. Id string `json:"id,omitempty"`
  257. Type string `json:"type"`
  258. Role string `json:"role,omitempty"`
  259. Content []ClaudeMediaMessage `json:"content,omitempty"`
  260. Completion string `json:"completion,omitempty"`
  261. StopReason string `json:"stop_reason,omitempty"`
  262. Model string `json:"model,omitempty"`
  263. Error any `json:"error,omitempty"`
  264. Usage *ClaudeUsage `json:"usage,omitempty"`
  265. Index *int `json:"index,omitempty"`
  266. ContentBlock *ClaudeMediaMessage `json:"content_block,omitempty"`
  267. Delta *ClaudeMediaMessage `json:"delta,omitempty"`
  268. Message *ClaudeMediaMessage `json:"message,omitempty"`
  269. }
  270. // set index
  271. func (c *ClaudeResponse) SetIndex(i int) {
  272. c.Index = &i
  273. }
  274. // get index
  275. func (c *ClaudeResponse) GetIndex() int {
  276. if c.Index == nil {
  277. return 0
  278. }
  279. return *c.Index
  280. }
  281. // GetClaudeError 从动态错误类型中提取ClaudeError结构
  282. func (c *ClaudeResponse) GetClaudeError() *types.ClaudeError {
  283. if c.Error == nil {
  284. return nil
  285. }
  286. switch err := c.Error.(type) {
  287. case types.ClaudeError:
  288. return &err
  289. case *types.ClaudeError:
  290. return err
  291. case map[string]interface{}:
  292. // 处理从JSON解析来的map结构
  293. claudeErr := &types.ClaudeError{}
  294. if errType, ok := err["type"].(string); ok {
  295. claudeErr.Type = errType
  296. }
  297. if errMsg, ok := err["message"].(string); ok {
  298. claudeErr.Message = errMsg
  299. }
  300. return claudeErr
  301. case string:
  302. // 处理简单字符串错误
  303. return &types.ClaudeError{
  304. Type: "error",
  305. Message: err,
  306. }
  307. default:
  308. // 未知类型,尝试转换为字符串
  309. return &types.ClaudeError{
  310. Type: "unknown_error",
  311. Message: fmt.Sprintf("%v", err),
  312. }
  313. }
  314. }
  315. type ClaudeUsage struct {
  316. InputTokens int `json:"input_tokens"`
  317. CacheCreationInputTokens int `json:"cache_creation_input_tokens"`
  318. CacheReadInputTokens int `json:"cache_read_input_tokens"`
  319. OutputTokens int `json:"output_tokens"`
  320. ServerToolUse *ClaudeServerToolUse `json:"server_tool_use"`
  321. }
  322. type ClaudeServerToolUse struct {
  323. WebSearchRequests int `json:"web_search_requests"`
  324. }