session.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. // GetLLMSessions returns LLM sessions with optional filtering
  16. func GetLLMSessions(c *gin.Context) {
  17. g := query.LLMSession
  18. query := g.Order(g.UpdatedAt.Desc())
  19. // Filter by path if provided
  20. if path := c.Query("path"); path != "" {
  21. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  22. c.JSON(http.StatusForbidden, gin.H{
  23. "message": "path is not under the nginx conf path",
  24. })
  25. return
  26. }
  27. query = query.Where(g.Path.Eq(path))
  28. }
  29. sessions, err := query.Find()
  30. if err != nil {
  31. cosy.ErrHandler(c, err)
  32. return
  33. }
  34. c.JSON(http.StatusOK, sessions)
  35. }
  36. // GetLLMSession returns a single session by session_id
  37. func GetLLMSession(c *gin.Context) {
  38. sessionID := c.Param("session_id")
  39. g := query.LLMSession
  40. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  41. if err != nil {
  42. cosy.ErrHandler(c, err)
  43. return
  44. }
  45. c.JSON(http.StatusOK, session)
  46. }
  47. // CreateLLMSession creates a new LLM session
  48. func CreateLLMSession(c *gin.Context) {
  49. var json struct {
  50. Title string `json:"title" binding:"required"`
  51. Path string `json:"path"`
  52. }
  53. if !cosy.BindAndValid(c, &json) {
  54. return
  55. }
  56. // Validate path if provided
  57. if json.Path != "" && !helper.IsUnderDirectory(json.Path, nginx.GetConfPath()) {
  58. c.JSON(http.StatusForbidden, gin.H{
  59. "message": "path is not under the nginx conf path",
  60. })
  61. return
  62. }
  63. session := &model.LLMSession{
  64. Title: json.Title,
  65. Path: json.Path,
  66. Messages: []openai.ChatCompletionMessage{},
  67. MessageCount: 0,
  68. IsActive: true,
  69. }
  70. g := query.LLMSession
  71. err := g.Create(session)
  72. if err != nil {
  73. logger.Error(err)
  74. cosy.ErrHandler(c, err)
  75. return
  76. }
  77. c.JSON(http.StatusOK, session)
  78. }
  79. // UpdateLLMSession updates an existing session
  80. func UpdateLLMSession(c *gin.Context) {
  81. sessionID := c.Param("session_id")
  82. var json struct {
  83. Title string `json:"title,omitempty"`
  84. Messages []openai.ChatCompletionMessage `json:"messages,omitempty"`
  85. IsActive *bool `json:"is_active,omitempty"`
  86. }
  87. if !cosy.BindAndValid(c, &json) {
  88. return
  89. }
  90. g := query.LLMSession
  91. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  92. if err != nil {
  93. logger.Error(err)
  94. cosy.ErrHandler(c, err)
  95. return
  96. }
  97. // Update fields
  98. if json.Title != "" {
  99. session.Title = json.Title
  100. }
  101. if json.Messages != nil {
  102. session.Messages = json.Messages
  103. session.MessageCount = len(json.Messages)
  104. }
  105. if json.IsActive != nil {
  106. session.IsActive = *json.IsActive
  107. }
  108. // Save the updated session
  109. err = g.Save(session)
  110. if err != nil {
  111. logger.Error(err)
  112. cosy.ErrHandler(c, err)
  113. return
  114. }
  115. c.JSON(http.StatusOK, session)
  116. }
  117. // DeleteLLMSession deletes a session by session_id
  118. func DeleteLLMSession(c *gin.Context) {
  119. sessionID := c.Param("session_id")
  120. g := query.LLMSession
  121. result, err := g.Where(g.SessionID.Eq(sessionID)).Delete()
  122. if err != nil {
  123. logger.Error(err)
  124. cosy.ErrHandler(c, err)
  125. return
  126. }
  127. if result.RowsAffected == 0 {
  128. c.JSON(http.StatusNotFound, gin.H{
  129. "message": "Session not found",
  130. })
  131. return
  132. }
  133. c.JSON(http.StatusOK, gin.H{
  134. "message": "Session deleted successfully",
  135. })
  136. }
  137. // DuplicateLLMSession duplicates an existing session
  138. func DuplicateLLMSession(c *gin.Context) {
  139. sessionID := c.Param("session_id")
  140. g := query.LLMSession
  141. originalSession, err := g.Where(g.SessionID.Eq(sessionID)).First()
  142. if err != nil {
  143. logger.Error(err)
  144. cosy.ErrHandler(c, err)
  145. return
  146. }
  147. // Create a new session with the same content
  148. newSession := &model.LLMSession{
  149. Title: originalSession.Title + " (Copy)",
  150. Path: originalSession.Path,
  151. Messages: originalSession.Messages,
  152. MessageCount: originalSession.MessageCount,
  153. }
  154. err = g.Create(newSession)
  155. if err != nil {
  156. logger.Error(err)
  157. cosy.ErrHandler(c, err)
  158. return
  159. }
  160. c.JSON(http.StatusOK, newSession)
  161. }
  162. // GetLLMSessionByPath - 兼容性端点,基于路径获取或创建会话
  163. func GetLLMSessionByPath(c *gin.Context) {
  164. path := c.Query("path")
  165. if !helper.IsUnderDirectory(path, nginx.GetConfPath()) {
  166. c.JSON(http.StatusForbidden, gin.H{
  167. "message": "path is not under the nginx conf path",
  168. })
  169. return
  170. }
  171. g := query.LLMSession
  172. // 查找基于该路径的会话
  173. session, err := g.Where(g.Path.Eq(path)).First()
  174. if err != nil {
  175. // 如果没找到,创建一个新的会话
  176. title := "Chat for " + filepath.Base(path)
  177. session = &model.LLMSession{
  178. Title: title,
  179. Path: path,
  180. Messages: []openai.ChatCompletionMessage{},
  181. MessageCount: 0,
  182. IsActive: true,
  183. }
  184. err = g.Create(session)
  185. if err != nil {
  186. logger.Error(err)
  187. cosy.ErrHandler(c, err)
  188. return
  189. }
  190. }
  191. // 返回兼容格式
  192. response := struct {
  193. Name string `json:"name"`
  194. Content []openai.ChatCompletionMessage `json:"content"`
  195. }{
  196. Name: session.Path,
  197. Content: session.Messages,
  198. }
  199. c.JSON(http.StatusOK, response)
  200. }
  201. // CreateOrUpdateLLMSessionByPath - 兼容性端点,基于路径创建或更新会话
  202. func CreateOrUpdateLLMSessionByPath(c *gin.Context) {
  203. var json struct {
  204. FileName string `json:"file_name"`
  205. Messages []openai.ChatCompletionMessage `json:"messages"`
  206. }
  207. if !cosy.BindAndValid(c, &json) {
  208. return
  209. }
  210. if !helper.IsUnderDirectory(json.FileName, nginx.GetConfPath()) {
  211. c.JSON(http.StatusForbidden, gin.H{
  212. "message": "path is not under the nginx conf path",
  213. })
  214. return
  215. }
  216. g := query.LLMSession
  217. // 查找或创建基于该路径的会话
  218. session, err := g.Where(g.Path.Eq(json.FileName)).First()
  219. if err != nil {
  220. // 创建新会话
  221. title := "Chat for " + filepath.Base(json.FileName)
  222. session = &model.LLMSession{
  223. Title: title,
  224. Path: json.FileName,
  225. Messages: json.Messages,
  226. MessageCount: len(json.Messages),
  227. IsActive: true,
  228. }
  229. err = g.Create(session)
  230. if err != nil {
  231. logger.Error(err)
  232. cosy.ErrHandler(c, err)
  233. return
  234. }
  235. } else {
  236. // 更新现有会话
  237. session.Messages = json.Messages
  238. session.MessageCount = len(json.Messages)
  239. err = g.Save(session)
  240. if err != nil {
  241. logger.Error(err)
  242. cosy.ErrHandler(c, err)
  243. return
  244. }
  245. }
  246. c.JSON(http.StatusOK, gin.H{
  247. "message": "ok",
  248. })
  249. }
  250. // GenerateSessionTitle generates a title for a session based on its context
  251. func GenerateSessionTitle(c *gin.Context) {
  252. sessionID := c.Param("session_id")
  253. g := query.LLMSession
  254. session, err := g.Where(g.SessionID.Eq(sessionID)).First()
  255. if err != nil {
  256. cosy.ErrHandler(c, err)
  257. return
  258. }
  259. // Generate title based on session messages
  260. title, err := llm.GenerateSessionTitle(session.Messages)
  261. if err != nil {
  262. logger.Error("Failed to generate session title:", err)
  263. cosy.ErrHandler(c, err)
  264. return
  265. }
  266. // Update the session with the new title
  267. session.Title = title
  268. err = g.Save(session)
  269. if err != nil {
  270. logger.Error("Failed to save session with new title:", err)
  271. cosy.ErrHandler(c, err)
  272. return
  273. }
  274. c.JSON(http.StatusOK, gin.H{
  275. "title": title,
  276. "message": "Title generated successfully",
  277. })
  278. }