responses_tool_search_discoveries.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. package apicompat
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "strings"
  6. )
  7. type responsesDiscoveredToolIdentity struct {
  8. typ string
  9. name string
  10. namespace string
  11. encoded string
  12. ambiguous bool
  13. }
  14. // promoteResponsesToolSearchDiscoveries makes successfully discovered client
  15. // tools callable for function-only upstreams. The original tool_search_output
  16. // remains request history and is normalized separately; declarations are
  17. // appended after static tools so the client's declaration order stays stable.
  18. func promoteResponsesToolSearchDiscoveries(req map[string]any) (bool, error) {
  19. tools, ok := req["tools"].([]any)
  20. if !ok || len(tools) == 0 || !hasResponsesToolSearchDeclaration(tools) {
  21. return false, nil
  22. }
  23. input, ok := req["input"].([]any)
  24. if !ok || len(input) == 0 {
  25. return false, nil
  26. }
  27. promoted, err := promotedResponsesToolSearchDiscoveries(tools, input)
  28. if err != nil {
  29. return false, err
  30. }
  31. if len(promoted) == 0 {
  32. return false, nil
  33. }
  34. req["tools"] = append(tools, promoted...)
  35. return true, nil
  36. }
  37. func promotedResponsesToolSearchDiscoveries(tools, input []any) ([]any, error) {
  38. if len(tools) == 0 || !hasResponsesToolSearchDeclaration(tools) || len(input) == 0 {
  39. return nil, nil
  40. }
  41. known := make(map[string]responsesDiscoveredToolIdentity)
  42. for _, raw := range tools {
  43. registerExistingResponsesToolIdentity(known, raw)
  44. }
  45. promoted := make([]any, 0)
  46. for _, rawItem := range input {
  47. item, ok := rawItem.(map[string]any)
  48. if !ok || strings.TrimSpace(stringValue(item["type"])) != "tool_search_output" || !usableResponsesToolSearchOutput(item) {
  49. continue
  50. }
  51. discoveries, ok := item["tools"].([]any)
  52. if !ok || len(discoveries) == 0 {
  53. continue
  54. }
  55. if _, err := json.Marshal(discoveries); err != nil {
  56. continue
  57. }
  58. for _, rawDiscovery := range discoveries {
  59. discovery, ok := rawDiscovery.(map[string]any)
  60. if !ok {
  61. continue
  62. }
  63. typ := strings.TrimSpace(stringValue(discovery["type"]))
  64. switch typ {
  65. case "function", "custom":
  66. copy, identity, ok := responsesDirectToolDiscovery(discovery, typ)
  67. if !ok {
  68. continue
  69. }
  70. appendTool, err := admitResponsesDiscoveredTool(known, identity.name, identity)
  71. if err != nil {
  72. return nil, err
  73. }
  74. if appendTool {
  75. promoted = append(promoted, copy)
  76. }
  77. case "namespace":
  78. copy, identities, ok := responsesNamespaceToolDiscovery(discovery)
  79. if !ok {
  80. continue
  81. }
  82. children := make([]any, 0, len(identities))
  83. for _, candidate := range identities {
  84. appendTool, err := admitResponsesDiscoveredTool(known, candidate.flat, candidate.identity)
  85. if err != nil {
  86. return nil, err
  87. }
  88. if appendTool {
  89. children = append(children, candidate.child)
  90. }
  91. }
  92. if len(children) > 0 {
  93. copy["tools"] = children
  94. delete(copy, "children")
  95. promoted = append(promoted, copy)
  96. }
  97. }
  98. }
  99. }
  100. return promoted, nil
  101. }
  102. func hasResponsesToolSearchDeclaration(tools []any) bool {
  103. for _, raw := range tools {
  104. tool, ok := raw.(map[string]any)
  105. if ok && strings.TrimSpace(stringValue(tool["type"])) == "tool_search" {
  106. return true
  107. }
  108. }
  109. return false
  110. }
  111. func usableResponsesToolSearchOutput(item map[string]any) bool {
  112. status, present := item["status"]
  113. if !present {
  114. return true
  115. }
  116. text, ok := status.(string)
  117. return ok && strings.TrimSpace(text) == "completed"
  118. }
  119. func registerExistingResponsesToolIdentity(known map[string]responsesDiscoveredToolIdentity, raw any) {
  120. tool, ok := raw.(map[string]any)
  121. if !ok {
  122. return
  123. }
  124. typ := strings.TrimSpace(stringValue(tool["type"]))
  125. switch typ {
  126. case "function", "custom":
  127. _, identity, ok := responsesDirectToolDiscovery(tool, typ)
  128. if ok {
  129. registerExistingResponsesIdentity(known, identity.name, identity)
  130. }
  131. case "namespace":
  132. _, identities, ok := responsesNamespaceToolDiscovery(tool)
  133. if !ok {
  134. return
  135. }
  136. for _, candidate := range identities {
  137. registerExistingResponsesIdentity(known, candidate.flat, candidate.identity)
  138. }
  139. }
  140. }
  141. func registerExistingResponsesIdentity(known map[string]responsesDiscoveredToolIdentity, key string, identity responsesDiscoveredToolIdentity) {
  142. previous, exists := known[key]
  143. if !exists {
  144. known[key] = identity
  145. return
  146. }
  147. if !sameResponsesDiscoveredTool(previous, identity) {
  148. previous.ambiguous = true
  149. known[key] = previous
  150. }
  151. }
  152. func admitResponsesDiscoveredTool(known map[string]responsesDiscoveredToolIdentity, key string, identity responsesDiscoveredToolIdentity) (bool, error) {
  153. previous, exists := known[key]
  154. if !exists {
  155. known[key] = identity
  156. return true, nil
  157. }
  158. if !previous.ambiguous && sameResponsesDiscoveredTool(previous, identity) {
  159. return false, nil
  160. }
  161. return false, fmt.Errorf("discovered tool %q conflicts with an existing declaration; this upstream cannot safely disambiguate different names, namespaces, or schemas", key)
  162. }
  163. func sameResponsesDiscoveredTool(left, right responsesDiscoveredToolIdentity) bool {
  164. return left.typ == right.typ && left.name == right.name && left.namespace == right.namespace && left.encoded == right.encoded
  165. }
  166. func responsesDirectToolDiscovery(tool map[string]any, typ string) (map[string]any, responsesDiscoveredToolIdentity, bool) {
  167. name := strings.TrimSpace(stringValue(tool["name"]))
  168. if name == "" {
  169. return nil, responsesDiscoveredToolIdentity{}, false
  170. }
  171. copy := copyClientTool(tool)
  172. copy["type"] = typ
  173. copy["name"] = name
  174. identityCopy := copy
  175. if typ == "custom" {
  176. identityCopy = copyClientTool(copy)
  177. identityCopy["type"] = "function"
  178. identityCopy["parameters"] = json.RawMessage(customToolInputSchema)
  179. delete(identityCopy, "format")
  180. }
  181. encoded, err := json.Marshal(identityCopy)
  182. if err != nil {
  183. return nil, responsesDiscoveredToolIdentity{}, false
  184. }
  185. return copy, responsesDiscoveredToolIdentity{typ: typ, name: name, encoded: string(encoded)}, true
  186. }
  187. // restoreInheritedResponsesClientToolDeclarations reverses only the declaration
  188. // identities recorded by ResponsesClientToolMapping. It is used when a WS
  189. // continuation omits tools but the HTTP function upstream still needs the
  190. // effective session declarations on every request.
  191. func restoreInheritedResponsesClientToolDeclarations(lowered []any, mapping ResponsesClientToolMapping) []any {
  192. restored := make([]any, 0, len(lowered))
  193. for _, raw := range lowered {
  194. tool, ok := raw.(map[string]any)
  195. if !ok {
  196. restored = append(restored, raw)
  197. continue
  198. }
  199. name := strings.TrimSpace(stringValue(tool["name"]))
  200. switch {
  201. case mapping.ToolSearch && name == toolSearchProxyName:
  202. restored = append(restored, map[string]any{"type": "tool_search"})
  203. case mapping.CustomTools[name]:
  204. copy := copyClientTool(tool)
  205. copy["type"] = "custom"
  206. restored = append(restored, copy)
  207. case mapping.NamespaceTools[name].Namespace != "":
  208. identity := mapping.NamespaceTools[name]
  209. child := copyClientTool(tool)
  210. child["type"] = "function"
  211. child["name"] = identity.Name
  212. restored = append(restored, map[string]any{
  213. "type": "namespace", "name": identity.Namespace, "tools": []any{child},
  214. })
  215. default:
  216. restored = append(restored, copyClientTool(tool))
  217. }
  218. }
  219. return restored
  220. }
  221. type responsesNamespaceToolCandidate struct {
  222. flat string
  223. child map[string]any
  224. identity responsesDiscoveredToolIdentity
  225. }
  226. func responsesNamespaceToolDiscovery(tool map[string]any) (map[string]any, []responsesNamespaceToolCandidate, bool) {
  227. namespace := strings.TrimSpace(stringValue(tool["name"]))
  228. children := namespaceChildren(tool)
  229. if namespace == "" || len(children) == 0 {
  230. return nil, nil, false
  231. }
  232. copy := copyClientTool(tool)
  233. copy["type"] = "namespace"
  234. copy["name"] = namespace
  235. identities := make([]responsesNamespaceToolCandidate, 0, len(children))
  236. for _, rawChild := range children {
  237. child, ok := rawChild.(map[string]any)
  238. if !ok || strings.TrimSpace(stringValue(child["type"])) != "function" {
  239. continue
  240. }
  241. childCopy, direct, ok := responsesDirectToolDiscovery(child, "function")
  242. if !ok {
  243. continue
  244. }
  245. flat := flattenNamespaceToolName(namespace, direct.name)
  246. identities = append(identities, responsesNamespaceToolCandidate{
  247. flat: flat,
  248. child: childCopy,
  249. identity: responsesDiscoveredToolIdentity{
  250. typ: "namespace", name: direct.name, namespace: namespace, encoded: direct.encoded,
  251. },
  252. })
  253. }
  254. if len(identities) == 0 {
  255. return nil, nil, false
  256. }
  257. return copy, identities, true
  258. }