1
0

session.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  1. package llm
  2. import (
  3. "net/http"
  4. "path/filepath"
  5. "github.com/0xJacky/Nginx-UI/internal/helper"
  6. "github.com/0xJacky/Nginx-UI/internal/llm"
  7. "github.com/0xJacky/Nginx-UI/internal/nginx"
  8. "github.com/0xJacky/Nginx-UI/model"
  9. "github.com/0xJacky/Nginx-UI/query"
  10. "github.com/gin-gonic/gin"
  11. "github.com/sashabaranov/go-openai"
  12. "github.com/uozi-tech/cosy"
  13. "github.com/uozi-tech/cosy/logger"
  14. )
  15. const TerminalAssistantPath = "__terminal_assistant__"
  16. // GetLLMSessions returns LLM sessions with optional filtering
  17. func GetLLMSessions(c *gin.Context) {
  18. g := query.LLMSession
  19. query := g.Order(g.UpdatedAt.Desc())
  20. // Filter by type if provided
  21. if assistantType := c.Query("type"); assistantType != "" {
  22. if assistantType == "terminal" {
  23. // For terminal type, filter by terminal assistant path
  24. query = query.Where(g.Path.Eq(TerminalAssistantPath))
  25. } else if assistantType == "nginx" {
  26. // For nginx type, exclude terminal assistant path
  27. query = query.Where(g.Path.Neq(TerminalAssistantPath))
  28. }
  29. } else if path := c.Query("path"); path != "" {
  30. // Filter by path if provided (legacy support)
  31. // Skip path validation for terminal assistant
  32. if path != TerminalAssistantPath && !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  33. c.JSON(http.StatusForbidden, gin.H{
  34. "message": "path is not under the nginx conf path",
  35. })
  36. return
  37. }
  38. query = query.Where(g.Path.Eq(path))
  39. }
  40. sessions, err := query.Find()
  41. if err != nil {
  42. cosy.ErrHandler(c, err)
  43. return
  44. }
  45. c.JSON(http.StatusOK, sessions)
  46. }
  47. // GetLLMSession returns a single session by session_id
  48. func GetLLMSession(c *gin.Context) {
  49. sessionID := c.Param("session_id")
  50. g := query.LLMSession
  51. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  52. if err != nil {
  53. cosy.ErrHandler(c, err)
  54. return
  55. }
  56. c.JSON(http.StatusOK, session)
  57. }
  58. // CreateLLMSession creates a new LLM session
  59. func CreateLLMSession(c *gin.Context) {
  60. var json struct {
  61. Title string `json:"title" binding:"required"`
  62. Path string `json:"path"`
  63. Type string `json:"type"`
  64. }
  65. if !cosy.BindAndValid(c, &json) {
  66. return
  67. }
  68. // Determine path based on type
  69. var sessionPath string
  70. if json.Type == "terminal" {
  71. sessionPath = TerminalAssistantPath
  72. } else {
  73. sessionPath = json.Path
  74. // Validate path for non-terminal types
  75. if sessionPath != "" && !helper.IsUnderDirectory(sessionPath, nginx.GetConfPath()) {
  76. c.JSON(http.StatusForbidden, gin.H{
  77. "message": "path is not under the nginx conf path",
  78. })
  79. return
  80. }
  81. }
  82. session := &model.LLMSession{
  83. Title: json.Title,
  84. Path: sessionPath,
  85. Messages: []openai.ChatCompletionMessage{},
  86. MessageCount: 0,
  87. IsActive: true,
  88. }
  89. g := query.LLMSession
  90. // When creating a new active session, deactivate all other sessions with the same path
  91. if session.IsActive && sessionPath != "" {
  92. _, err := g.Where(g.Path.Eq(sessionPath)).UpdateSimple(g.IsActive.Value(false))
  93. if err != nil {
  94. logger.Error("Failed to deactivate other sessions:", err)
  95. // Continue anyway, this is not critical
  96. }
  97. }
  98. err := g.Create(session)
  99. if err != nil {
  100. logger.Error(err)
  101. cosy.ErrHandler(c, err)
  102. return
  103. }
  104. c.JSON(http.StatusOK, session)
  105. }
  106. // UpdateLLMSession updates an existing session
  107. func UpdateLLMSession(c *gin.Context) {
  108. sessionID := c.Param("session_id")
  109. var json struct {
  110. Title string `json:"title,omitempty"`
  111. Messages []openai.ChatCompletionMessage `json:"messages,omitempty"`
  112. IsActive *bool `json:"is_active,omitempty"`
  113. }
  114. if !cosy.BindAndValid(c, &json) {
  115. return
  116. }
  117. g := query.LLMSession
  118. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  119. if err != nil {
  120. logger.Error(err)
  121. cosy.ErrHandler(c, err)
  122. return
  123. }
  124. // Update fields
  125. if json.Title != "" {
  126. session.Title = json.Title
  127. }
  128. if json.Messages != nil {
  129. session.Messages = json.Messages
  130. session.MessageCount = len(json.Messages)
  131. }
  132. if json.IsActive != nil && *json.IsActive {
  133. session.IsActive = true
  134. // Deactivate all other sessions with the same path
  135. _, err = g.Where(
  136. g.Path.Eq(session.Path),
  137. g.SessionID.Neq(sessionID),
  138. ).UpdateSimple(g.IsActive.Value(false))
  139. if err != nil {
  140. logger.Error("Failed to deactivate other sessions:", err)
  141. // Continue anyway, this is not critical
  142. }
  143. } else if json.IsActive != nil {
  144. session.IsActive = *json.IsActive
  145. }
  146. // Save the updated session
  147. err = g.Save(session)
  148. if err != nil {
  149. logger.Error(err)
  150. cosy.ErrHandler(c, err)
  151. return
  152. }
  153. c.JSON(http.StatusOK, session)
  154. }
  155. // DeleteLLMSession deletes a session by session_id
  156. func DeleteLLMSession(c *gin.Context) {
  157. sessionID := c.Param("session_id")
  158. g := query.LLMSession
  159. result, err := g.Where(g.SessionID.Eq(sessionID)).Delete()
  160. if err != nil {
  161. logger.Error(err)
  162. cosy.ErrHandler(c, err)
  163. return
  164. }
  165. if result.RowsAffected == 0 {
  166. c.JSON(http.StatusNotFound, gin.H{
  167. "message": "Session not found",
  168. })
  169. return
  170. }
  171. c.JSON(http.StatusOK, gin.H{
  172. "message": "Session deleted successfully",
  173. })
  174. }
  175. // DuplicateLLMSession duplicates an existing session
  176. func DuplicateLLMSession(c *gin.Context) {
  177. sessionID := c.Param("session_id")
  178. g := query.LLMSession
  179. originalSession, err := g.Where(g.SessionID.Eq(sessionID)).First()
  180. if err != nil {
  181. logger.Error(err)
  182. cosy.ErrHandler(c, err)
  183. return
  184. }
  185. // Create a new session with the same content
  186. newSession := &model.LLMSession{
  187. Title: originalSession.Title + " (Copy)",
  188. Path: originalSession.Path,
  189. Messages: originalSession.Messages,
  190. MessageCount: originalSession.MessageCount,
  191. }
  192. err = g.Create(newSession)
  193. if err != nil {
  194. logger.Error(err)
  195. cosy.ErrHandler(c, err)
  196. return
  197. }
  198. c.JSON(http.StatusOK, newSession)
  199. }
  200. // GetLLMSessionByPath - 兼容性端点,基于路径获取或创建会话
  201. func GetLLMSessionByPath(c *gin.Context) {
  202. path := c.Query("path")
  203. // Skip path validation for terminal assistant
  204. if path != TerminalAssistantPath && !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  205. c.JSON(http.StatusForbidden, gin.H{
  206. "message": "path is not under the nginx conf path",
  207. })
  208. return
  209. }
  210. g := query.LLMSession
  211. // 查找基于该路径的会话
  212. session, err := g.Where(g.Path.Eq(path)).First()
  213. if err != nil {
  214. // 如果没找到,创建一个新的会话
  215. title := "Chat for " + filepath.Base(path)
  216. session = &model.LLMSession{
  217. Title: title,
  218. Path: path,
  219. Messages: []openai.ChatCompletionMessage{},
  220. MessageCount: 0,
  221. IsActive: true,
  222. }
  223. // Deactivate all other sessions with the same path before creating
  224. if path != "" {
  225. _, deactivateErr := g.Where(g.Path.Eq(path)).UpdateSimple(g.IsActive.Value(false))
  226. if deactivateErr != nil {
  227. logger.Error("Failed to deactivate other sessions:", deactivateErr)
  228. }
  229. }
  230. err = g.Create(session)
  231. if err != nil {
  232. logger.Error(err)
  233. cosy.ErrHandler(c, err)
  234. return
  235. }
  236. }
  237. // 返回兼容格式
  238. response := struct {
  239. Name string `json:"name"`
  240. Content []openai.ChatCompletionMessage `json:"content"`
  241. }{
  242. Name: session.Path,
  243. Content: session.Messages,
  244. }
  245. c.JSON(http.StatusOK, response)
  246. }
  247. // CreateOrUpdateLLMSessionByPath - 兼容性端点,基于路径创建或更新会话
  248. func CreateOrUpdateLLMSessionByPath(c *gin.Context) {
  249. var json struct {
  250. FileName string `json:"file_name"`
  251. Messages []openai.ChatCompletionMessage `json:"messages"`
  252. }
  253. if !cosy.BindAndValid(c, &json) {
  254. return
  255. }
  256. // Skip path validation for terminal assistant
  257. if json.FileName != TerminalAssistantPath && !helper.IsUnderDirectory(json.FileName, nginx.GetConfPath()) {
  258. c.JSON(http.StatusForbidden, gin.H{
  259. "message": "path is not under the nginx conf path",
  260. })
  261. return
  262. }
  263. g := query.LLMSession
  264. // 查找或创建基于该路径的会话
  265. session, err := g.Where(g.Path.Eq(json.FileName)).First()
  266. if err != nil {
  267. // 创建新会话
  268. title := "Chat for " + filepath.Base(json.FileName)
  269. session = &model.LLMSession{
  270. Title: title,
  271. Path: json.FileName,
  272. Messages: json.Messages,
  273. MessageCount: len(json.Messages),
  274. IsActive: true,
  275. }
  276. // Deactivate all other sessions with the same path before creating
  277. if json.FileName != "" {
  278. _, deactivateErr := g.Where(g.Path.Eq(json.FileName)).UpdateSimple(g.IsActive.Value(false))
  279. if deactivateErr != nil {
  280. logger.Error("Failed to deactivate other sessions:", deactivateErr)
  281. }
  282. }
  283. err = g.Create(session)
  284. if err != nil {
  285. logger.Error(err)
  286. cosy.ErrHandler(c, err)
  287. return
  288. }
  289. } else {
  290. // 更新现有会话
  291. session.Messages = json.Messages
  292. session.MessageCount = len(json.Messages)
  293. err = g.Save(session)
  294. if err != nil {
  295. logger.Error(err)
  296. cosy.ErrHandler(c, err)
  297. return
  298. }
  299. }
  300. c.JSON(http.StatusOK, gin.H{
  301. "message": "ok",
  302. })
  303. }
  304. // GenerateSessionTitle generates a title for a session based on its context
  305. func GenerateSessionTitle(c *gin.Context) {
  306. sessionID := c.Param("session_id")
  307. g := query.LLMSession
  308. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  309. if err != nil {
  310. cosy.ErrHandler(c, err)
  311. return
  312. }
  313. // Generate title based on session messages
  314. title, err := llm.GenerateSessionTitle(session.Messages)
  315. if err != nil {
  316. logger.Error("Failed to generate session title:", err)
  317. cosy.ErrHandler(c, err)
  318. return
  319. }
  320. // Update the session with the new title
  321. session.Title = title
  322. err = g.Save(session)
  323. if err != nil {
  324. logger.Error("Failed to save session with new title:", err)
  325. cosy.ErrHandler(c, err)
  326. return
  327. }
  328. c.JSON(http.StatusOK, gin.H{
  329. "title": title,
  330. "message": "Title generated successfully",
  331. })
  332. }