handler.go 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. package service
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "net/http"
  7. "time"
  8. "yunion.io/x/jsonutils"
  9. api "yunion.io/x/onecloud/pkg/apis/llm"
  10. "yunion.io/x/onecloud/pkg/appsrv"
  11. "yunion.io/x/onecloud/pkg/appsrv/dispatcher"
  12. "yunion.io/x/onecloud/pkg/cloudcommon/db"
  13. "yunion.io/x/onecloud/pkg/cloudcommon/db/taskman"
  14. "yunion.io/x/onecloud/pkg/cloudcommon/policy"
  15. "yunion.io/x/onecloud/pkg/httperrors"
  16. "yunion.io/x/onecloud/pkg/llm/models"
  17. "yunion.io/x/onecloud/pkg/mcclient/auth"
  18. )
  19. func handleOllamaRegistryYAML(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  20. yamlContent := models.GetInstantModelManager().GetOllamaRegistryYAML()
  21. w.Header().Set("Content-Type", "application/x-yaml; charset=utf-8")
  22. appsrv.Send(w, yamlContent)
  23. }
  24. func AddAvailableNetworkHandler(prefix string, app *appsrv.Application) {
  25. app.AddHandler2("GET", fmt.Sprintf("%s/available-network", prefix), auth.Authenticate(handleLLMAvailableNetwork), nil, "get_llm_available_network", nil)
  26. }
  27. func handleLLMAvailableNetwork(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  28. userCred := auth.FetchUserCredential(ctx, policy.FilterPolicyCredential)
  29. if userCred == nil {
  30. httperrors.UnauthorizedError(ctx, w, "Unauthorized")
  31. return
  32. }
  33. query, err := jsonutils.ParseQueryString(r.URL.RawQuery)
  34. if err != nil {
  35. httperrors.InvalidInputError(ctx, w, "Parse query string %q: %v", r.URL.RawQuery, err)
  36. return
  37. }
  38. ret, err := models.GetLLMManager().GetAvailableNetwork(ctx, userCred, query)
  39. if err != nil {
  40. httperrors.GeneralServerError(ctx, w, err)
  41. return
  42. }
  43. wrapped := jsonutils.NewDict()
  44. if ret != nil {
  45. wrapped.Add(ret, "llm")
  46. }
  47. appsrv.SendJSON(w, wrapped)
  48. }
  49. func handleLLMProviderModels(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  50. userCred := auth.FetchUserCredential(ctx, policy.FilterPolicyCredential)
  51. if userCred == nil {
  52. httperrors.UnauthorizedError(ctx, w, "Unauthorized")
  53. return
  54. }
  55. query, err := jsonutils.ParseQueryString(r.URL.RawQuery)
  56. if err != nil {
  57. httperrors.InvalidInputError(ctx, w, "Parse query string %q: %v", r.URL.RawQuery, err)
  58. return
  59. }
  60. ret, err := models.GetLLMManager().GetProviderModels(ctx, userCred, query)
  61. if err != nil {
  62. httperrors.GeneralServerError(ctx, w, err)
  63. return
  64. }
  65. appsrv.SendStruct(w, ret)
  66. }
  67. func handleDefaultChatStream(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  68. userCred := auth.FetchUserCredential(ctx, policy.FilterPolicyCredential)
  69. if userCred == nil {
  70. httperrors.UnauthorizedError(ctx, w, "Unauthorized")
  71. return
  72. }
  73. bodyBytes, err := io.ReadAll(r.Body)
  74. if err != nil {
  75. httperrors.GeneralServerError(ctx, w, err)
  76. return
  77. }
  78. body, err := jsonutils.Parse(bodyBytes)
  79. if err != nil {
  80. httperrors.InvalidInputError(ctx, w, "invalid body: %v", err)
  81. return
  82. }
  83. var input api.LLMMCPAgentRequestInput
  84. if body.Contains(models.GetMCPAgentManager().Keyword()) {
  85. agentObj, _ := body.Get(models.GetMCPAgentManager().Keyword())
  86. if agentObj != nil {
  87. body = agentObj
  88. }
  89. }
  90. if err := body.Unmarshal(&input); err != nil {
  91. httperrors.InvalidInputError(ctx, w, "invalid input: %v", err)
  92. return
  93. }
  94. defaultAgent, err := models.GetMCPAgentManager().GetDefaultAgent(ctx, userCred)
  95. if err != nil {
  96. httperrors.GeneralServerError(ctx, w, err)
  97. return
  98. }
  99. if defaultAgent == nil {
  100. httperrors.NotFoundError(ctx, w, "no default MCP agent set (set one agent with default_agent=true)")
  101. return
  102. }
  103. query := jsonutils.NewDict()
  104. _, err = defaultAgent.PerformChatStream(ctx, userCred, query, input)
  105. if err != nil {
  106. httperrors.GeneralServerError(ctx, w, err)
  107. return
  108. }
  109. }
  110. func handleDefaultMcpTools(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  111. userCred := auth.FetchUserCredential(ctx, policy.FilterPolicyCredential)
  112. if userCred == nil {
  113. httperrors.UnauthorizedError(ctx, w, "Unauthorized")
  114. return
  115. }
  116. result, err := models.GetMCPAgentManager().GetDefaultMcpServerTools(ctx, userCred)
  117. if err != nil {
  118. httperrors.GeneralServerError(ctx, w, err)
  119. return
  120. }
  121. appsrv.SendJSON(w, result)
  122. }
  123. func InitHandlers(app *appsrv.Application, isSlave bool) {
  124. db.InitAllManagers()
  125. db.RegistUserCredCacheUpdater()
  126. taskman.AddTaskHandler("", app, isSlave)
  127. app.AddHandler("GET", "/ollama-registry.yaml", handleOllamaRegistryYAML)
  128. AddAvailableNetworkHandler(models.GetLLMManager().KeywordPlural(), app)
  129. // 默认 Agent 聊天流:优先于 dispatcher 注册,避免被 performClassAction 的 sendJSON 覆盖。
  130. // 注册两种路径:default-chat-stream(apigateway 转发用)与 default/chat-stream(climc 直连 region 时用,否则会被当作 resid=default 的 perform 导致 404)
  131. defaultChatStream := app.AddHandler2("POST", "/mcp_agents/default-chat-stream", auth.Authenticate(handleDefaultChatStream), nil, "default_chat_stream", nil)
  132. defaultChatStream.SetProcessTimeout(time.Hour * 4).SetWorkerManager(models.GetMCPAgentWorkerManager())
  133. defaultChatStreamSlash := app.AddHandler2("POST", "/mcp_agents/default/chat-stream", auth.Authenticate(handleDefaultChatStream), nil, "default_chat_stream_slash", nil)
  134. defaultChatStreamSlash.SetProcessTimeout(time.Hour * 4).SetWorkerManager(models.GetMCPAgentWorkerManager())
  135. // 默认 MCP 服务器 tools:仅使用 options.MCPServerURL,不依赖 mcp_agent 条目
  136. app.AddHandler2("GET", "/mcp_agents/default-mcp-tools", auth.Authenticate(handleDefaultMcpTools), nil, "default_mcp_tools", nil)
  137. for _, manager := range []db.IModelManager{
  138. taskman.TaskManager,
  139. taskman.SubTaskManager,
  140. taskman.TaskObjectManager,
  141. taskman.ArchivedTaskManager,
  142. db.SharedResourceManager,
  143. db.UserCacheManager,
  144. db.TenantCacheManager,
  145. } {
  146. db.RegisterModelManager(manager)
  147. }
  148. for _, manager := range []db.IModelManager{
  149. db.OpsLog,
  150. db.Metadata,
  151. models.GetLLMImageManager(),
  152. models.GetLLMSkuManager(),
  153. // models.GetDifySkuManager(),
  154. models.GetVolumeManager(),
  155. models.GetLLMBackupManager(),
  156. models.GetAccessInfoManager(),
  157. models.GetLLMContainerManager(),
  158. models.GetLLMManager(),
  159. // models.GetDifyManager(),
  160. models.GetInstantModelManager(),
  161. models.GetLLMInstantModelManager(),
  162. models.GetMCPAgentManager(),
  163. } {
  164. db.RegisterModelManager(manager)
  165. handler := db.NewModelHandler(manager)
  166. dispatcher.AddModelDispatcher("", app, handler, isSlave)
  167. }
  168. }