http.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. const htmlHeader = `<!DOCTYPE html>
  12. <html>
  13. <head>
  14. <title>ch.at</title>
  15. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  16. <style>
  17. body { text-align: center; margin: 40px; }
  18. pre { text-align: left; max-width: 600px; margin: 20px auto; padding: 20px;
  19. white-space: pre-wrap; word-wrap: break-word; }
  20. input[type="text"] { width: 300px; }
  21. </style>
  22. </head>
  23. <body>
  24. <h1>ch.at</h1>
  25. <p>Universal Basic Chat</p>
  26. <p><small><i>pronounced "ch-dot-at"</i></small></p>
  27. <pre>`
  28. const htmlFooterTemplate = `</pre>
  29. <form method="POST" action="/">
  30. <input type="text" name="q" placeholder="Type your message..." autofocus>
  31. <input type="submit" value="Send">
  32. <textarea name="h" style="display:none">%s</textarea>
  33. </form>
  34. <p><a href="/">New Chat</a></p>
  35. <p><small>
  36. Also available: ssh ch.at • curl ch.at/?q=hello • dig @ch.at "question" TXT<br>
  37. No logs • No accounts • Free software • <a href="https://github.com/Deep-ai-inc/ch.at">GitHub</a>
  38. </small></p>
  39. </body>
  40. </html>`
  41. func StartHTTPServer(port int) error {
  42. http.HandleFunc("/", handleRoot)
  43. http.HandleFunc("/v1/chat/completions", handleChatCompletions)
  44. addr := fmt.Sprintf(":%d", port)
  45. return http.ListenAndServe(addr, nil)
  46. }
  47. func StartHTTPSServer(port int, certFile, keyFile string) error {
  48. addr := fmt.Sprintf(":%d", port)
  49. return http.ListenAndServeTLS(addr, certFile, keyFile, nil)
  50. }
  51. func handleRoot(w http.ResponseWriter, r *http.Request) {
  52. if !rateLimitAllow(r.RemoteAddr) {
  53. http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
  54. return
  55. }
  56. var query, history, prompt string
  57. content := ""
  58. jsonResponse := ""
  59. if r.Method == "POST" {
  60. if err := r.ParseForm(); err != nil {
  61. http.Error(w, "Failed to parse form", http.StatusBadRequest)
  62. return
  63. }
  64. query = r.FormValue("q")
  65. history = r.FormValue("h")
  66. // Limit history size to ensure compatibility
  67. if len(history) > 65536 {
  68. history = history[len(history)-65536:]
  69. }
  70. if query == "" {
  71. body, err := io.ReadAll(io.LimitReader(r.Body, 65536)) // Limit body size
  72. if err != nil {
  73. http.Error(w, "Failed to read request body", http.StatusBadRequest)
  74. return
  75. }
  76. query = string(body)
  77. }
  78. } else {
  79. query = r.URL.Query().Get("q")
  80. // Support path-based queries like /what-is-go
  81. if query == "" && r.URL.Path != "/" {
  82. query = strings.ReplaceAll(strings.TrimPrefix(r.URL.Path, "/"), "-", " ")
  83. }
  84. }
  85. accept := r.Header.Get("Accept")
  86. wantsJSON := strings.Contains(accept, "application/json")
  87. wantsHTML := strings.Contains(accept, "text/html")
  88. wantsStream := strings.Contains(accept, "text/event-stream")
  89. if query != "" {
  90. prompt = query
  91. if history != "" {
  92. prompt = history + "Q: " + query
  93. }
  94. if wantsHTML && r.Header.Get("Accept") != "application/json" {
  95. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  96. w.Header().Set("Transfer-Encoding", "chunked")
  97. w.Header().Set("X-Accel-Buffering", "no")
  98. w.Header().Set("Cache-Control", "no-cache")
  99. flusher := w.(http.Flusher)
  100. displayHistory := history
  101. headerSize := len(htmlHeader)
  102. historySize := len(html.EscapeString(history))
  103. querySize := len(html.EscapeString(query))
  104. currentSize := headerSize + historySize + querySize + 10
  105. // Browser streaming needs significant content - working version used 6KB
  106. const minThreshold = 6144 // 6KB threshold (matching what worked before)
  107. if currentSize < minThreshold {
  108. // Each zero-width space is 3 bytes in UTF-8
  109. paddingNeeded := (minThreshold - currentSize) / 3
  110. if paddingNeeded > 0 {
  111. padding := strings.Repeat("\u200B", paddingNeeded)
  112. displayHistory = padding + history
  113. }
  114. }
  115. fmt.Fprint(w, htmlHeader)
  116. fmt.Fprintf(w, "%sQ: %s\nA: ", html.EscapeString(displayHistory), html.EscapeString(query))
  117. flusher.Flush()
  118. ch := make(chan string)
  119. go func() {
  120. if _, err := LLM(prompt, ch); err != nil {
  121. ch <- err.Error()
  122. close(ch)
  123. }
  124. }()
  125. response := ""
  126. for chunk := range ch {
  127. if _, err := fmt.Fprint(w, html.EscapeString(chunk)); err != nil {
  128. return
  129. }
  130. response += chunk
  131. flusher.Flush()
  132. }
  133. finalHistory := history + fmt.Sprintf("Q: %s\nA: %s\n\n", query, response)
  134. fmt.Fprintf(w, htmlFooterTemplate, html.EscapeString(finalHistory))
  135. return
  136. }
  137. // Plain text streaming for curl
  138. userAgent := r.Header.Get("User-Agent")
  139. isCurl := strings.Contains(userAgent, "curl") && !wantsHTML && !wantsJSON && !wantsStream
  140. if isCurl {
  141. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  142. w.Header().Set("Transfer-Encoding", "chunked")
  143. w.Header().Set("X-Accel-Buffering", "no")
  144. flusher := w.(http.Flusher)
  145. fmt.Fprintf(w, "Q: %s\nA: ", query)
  146. flusher.Flush()
  147. ch := make(chan string)
  148. go func() {
  149. if _, err := LLM(prompt, ch); err != nil {
  150. ch <- err.Error()
  151. close(ch)
  152. }
  153. }()
  154. response := ""
  155. for chunk := range ch {
  156. fmt.Fprint(w, chunk)
  157. response += chunk
  158. flusher.Flush()
  159. }
  160. fmt.Fprint(w, "\n")
  161. return
  162. }
  163. response, err := LLM(prompt, nil)
  164. if err != nil {
  165. content = err.Error()
  166. errJSON, _ := json.Marshal(map[string]string{"error": err.Error()})
  167. jsonResponse = string(errJSON)
  168. } else {
  169. respJSON, _ := json.Marshal(map[string]string{
  170. "question": query,
  171. "answer": response,
  172. })
  173. jsonResponse = string(respJSON)
  174. newExchange := fmt.Sprintf("Q: %s\nA: %s\n\n", query, response)
  175. if history != "" {
  176. content = history + newExchange
  177. } else {
  178. content = newExchange
  179. }
  180. if len(content) > 65536 {
  181. newExchangeLen := len(newExchange)
  182. if newExchangeLen > 65536 {
  183. content = newExchange[:65536]
  184. } else {
  185. maxHistory := 65536 - newExchangeLen
  186. if len(history) > maxHistory {
  187. content = history[len(history)-maxHistory:] + newExchange
  188. }
  189. }
  190. }
  191. }
  192. } else if history != "" {
  193. content = history
  194. }
  195. if wantsStream && query != "" {
  196. w.Header().Set("Content-Type", "text/event-stream")
  197. w.Header().Set("Cache-Control", "no-cache")
  198. w.Header().Set("Connection", "keep-alive")
  199. flusher, ok := w.(http.Flusher)
  200. if !ok {
  201. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  202. return
  203. }
  204. ch := make(chan string)
  205. go func() {
  206. if _, err := LLM(prompt, ch); err != nil {
  207. fmt.Fprintf(w, "data: Error: %s\n\n", err.Error())
  208. flusher.Flush()
  209. }
  210. }()
  211. for chunk := range ch {
  212. fmt.Fprintf(w, "data: %s\n\n", chunk)
  213. flusher.Flush()
  214. }
  215. fmt.Fprintf(w, "data: [DONE]\n\n")
  216. return
  217. }
  218. if wantsJSON && jsonResponse != "" {
  219. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  220. fmt.Fprint(w, jsonResponse)
  221. } else if wantsHTML && query == "" {
  222. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  223. fmt.Fprint(w, htmlHeader)
  224. fmt.Fprint(w, html.EscapeString(content))
  225. fmt.Fprintf(w, htmlFooterTemplate, html.EscapeString(content))
  226. } else {
  227. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  228. fmt.Fprint(w, content)
  229. }
  230. }
  231. type ChatRequest struct {
  232. Model string `json:"model"`
  233. Messages []Message `json:"messages"`
  234. Stream bool `json:"stream,omitempty"`
  235. }
  236. type Message struct {
  237. Role string `json:"role"`
  238. Content string `json:"content"`
  239. }
  240. type ChatResponse struct {
  241. ID string `json:"id"`
  242. Object string `json:"object"`
  243. Created int64 `json:"created"`
  244. Model string `json:"model"`
  245. Choices []Choice `json:"choices"`
  246. }
  247. type Choice struct {
  248. Index int `json:"index"`
  249. Message Message `json:"message"`
  250. }
  251. func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
  252. if !rateLimitAllow(r.RemoteAddr) {
  253. http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
  254. return
  255. }
  256. if r.Method != "POST" {
  257. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  258. return
  259. }
  260. var req ChatRequest
  261. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  262. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  263. return
  264. }
  265. messages := make([]map[string]string, len(req.Messages))
  266. for i, msg := range req.Messages {
  267. messages[i] = map[string]string{
  268. "role": msg.Role,
  269. "content": msg.Content,
  270. }
  271. }
  272. if req.Stream {
  273. w.Header().Set("Content-Type", "text/event-stream")
  274. w.Header().Set("Cache-Control", "no-cache")
  275. w.Header().Set("Connection", "keep-alive")
  276. flusher, ok := w.(http.Flusher)
  277. if !ok {
  278. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  279. return
  280. }
  281. ch := make(chan string)
  282. go LLM(messages, ch)
  283. for chunk := range ch {
  284. resp := map[string]interface{}{
  285. "id": fmt.Sprintf("chatcmpl-%d", time.Now().Unix()),
  286. "object": "chat.completion.chunk",
  287. "created": time.Now().Unix(),
  288. "model": req.Model,
  289. "choices": []map[string]interface{}{{
  290. "index": 0,
  291. "delta": map[string]string{"content": chunk},
  292. }},
  293. }
  294. data, err := json.Marshal(resp)
  295. if err != nil {
  296. fmt.Fprintf(w, "data: Failed to marshal response\n\n")
  297. return
  298. }
  299. fmt.Fprintf(w, "data: %s\n\n", data)
  300. flusher.Flush()
  301. }
  302. fmt.Fprintf(w, "data: [DONE]\n\n")
  303. } else {
  304. response, err := LLM(messages, nil)
  305. if err != nil {
  306. http.Error(w, err.Error(), http.StatusInternalServerError)
  307. return
  308. }
  309. chatResp := ChatResponse{
  310. ID: fmt.Sprintf("chatcmpl-%d", time.Now().Unix()),
  311. Object: "chat.completion",
  312. Created: time.Now().Unix(),
  313. Model: req.Model,
  314. Choices: []Choice{{
  315. Index: 0,
  316. Message: Message{
  317. Role: "assistant",
  318. Content: response,
  319. },
  320. }},
  321. }
  322. w.Header().Set("Content-Type", "application/json")
  323. json.NewEncoder(w).Encode(chatResp)
  324. }
  325. }