http.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "html"
  6. "io"
  7. "net/http"
  8. "strings"
  9. "time"
  10. )
  11. const htmlPromptPrefix = "You are a helpful assistant. Use HTML formatting instead of markdown (no CSS or style attributes): "
  12. // isBrowserUA checks if the user agent appears to be from a web browser
  13. func isBrowserUA(ua string) bool {
  14. ua = strings.ToLower(ua)
  15. browserIndicators := []string{
  16. "mozilla", "msie", "trident", "edge", "chrome", "safari",
  17. "firefox", "opera", "webkit", "gecko", "khtml",
  18. }
  19. for _, indicator := range browserIndicators {
  20. if strings.Contains(ua, indicator) {
  21. return true
  22. }
  23. }
  24. return false
  25. }
  26. const htmlHeader = `<!DOCTYPE html>
  27. <html>
  28. <head>
  29. <title>ch.at</title>
  30. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  31. <style>
  32. body { text-align: center; margin: 2.5rem; }
  33. .chat { text-align: left; max-width: 600px; margin: 1.25rem auto; }
  34. .q { padding: 1.25rem; background: #EEE; font-style: italic; font-size: large; }
  35. .a { padding: 0.5rem 1.25rem; }
  36. form { max-width: 568px; margin: 0 auto 3rem; display: flex; gap: .5rem; }
  37. input[type="text"] { width: 100%; padding: .5rem; }
  38. input[type="submit"] { padding: .5rem; }
  39. </style>
  40. </head>
  41. <body>
  42. <h1>ch.at</h1>
  43. <p>Universal Basic Intelligence</p>
  44. <p><small><i>pronounced "ch-dot-at"</i></small></p>
  45. <div class="chat">`
  46. const htmlFooterTemplate = `</div>
  47. <form method="POST" action="/">
  48. <input type="text" name="q" placeholder="Type your message..." autofocus>
  49. <input type="submit" value="Send">
  50. <textarea name="h" style="display:none">%s</textarea>
  51. </form>
  52. <p><a href="/">New Chat</a></p>
  53. <p><small>
  54. Also available: ssh ch.at • curl ch.at/?q=hello • dig @ch.at "question" TXT<br>
  55. No logs • No accounts • Free software • <a href="https://github.com/Deep-ai-inc/ch.at">GitHub</a>
  56. </small></p>
  57. </body>
  58. </html>`
  59. func StartHTTPServer(port int) error {
  60. http.HandleFunc("/", handleRoot)
  61. http.HandleFunc("/v1/chat/completions", handleChatCompletions)
  62. addr := fmt.Sprintf(":%d", port)
  63. return http.ListenAndServe(addr, nil)
  64. }
  65. func StartHTTPSServer(port int, certFile, keyFile string) error {
  66. addr := fmt.Sprintf(":%d", port)
  67. return http.ListenAndServeTLS(addr, certFile, keyFile, nil)
  68. }
  69. func handleRoot(w http.ResponseWriter, r *http.Request) {
  70. w.Header().Set("Access-Control-Allow-Origin", "*")
  71. if !rateLimitAllow(r.RemoteAddr) {
  72. http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
  73. return
  74. }
  75. var query, history, prompt string
  76. content := ""
  77. jsonResponse := ""
  78. if r.Method == "POST" {
  79. if err := r.ParseForm(); err != nil {
  80. http.Error(w, "Failed to parse form", http.StatusBadRequest)
  81. return
  82. }
  83. query = r.FormValue("q")
  84. history = r.FormValue("h")
  85. // Limit history size to ensure compatibility
  86. if len(history) > 65536 {
  87. history = history[len(history)-65536:]
  88. }
  89. if query == "" {
  90. body, err := io.ReadAll(io.LimitReader(r.Body, 65536)) // Limit body size
  91. if err != nil {
  92. http.Error(w, "Failed to read request body", http.StatusBadRequest)
  93. return
  94. }
  95. query = string(body)
  96. }
  97. } else {
  98. query = r.URL.Query().Get("q")
  99. // Support path-based queries like /what-is-go
  100. if query == "" && r.URL.Path != "/" {
  101. query = strings.ReplaceAll(strings.TrimPrefix(r.URL.Path, "/"), "-", " ")
  102. }
  103. }
  104. accept := r.Header.Get("Accept")
  105. userAgent := strings.ToLower(r.Header.Get("User-Agent"))
  106. wantsJSON := strings.Contains(accept, "application/json")
  107. wantsHTML := isBrowserUA(userAgent) || strings.Contains(accept, "text/html")
  108. wantsStream := strings.Contains(accept, "text/event-stream")
  109. if query != "" {
  110. prompt = query
  111. if history != "" {
  112. prompt = history + "Q: " + query
  113. }
  114. if wantsHTML && r.Header.Get("Accept") != "application/json" {
  115. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  116. w.Header().Set("Transfer-Encoding", "chunked")
  117. w.Header().Set("X-Accel-Buffering", "no")
  118. w.Header().Set("Cache-Control", "no-cache")
  119. flusher := w.(http.Flusher)
  120. headerSize := len(htmlHeader)
  121. historySize := len(html.EscapeString(history))
  122. querySize := len(html.EscapeString(query))
  123. currentSize := headerSize + historySize + querySize + 10
  124. const minThreshold = 6144
  125. fmt.Fprint(w, htmlHeader)
  126. if currentSize < minThreshold {
  127. paddingNeeded := (minThreshold - currentSize) / 3
  128. if paddingNeeded > 0 {
  129. padding := strings.Repeat("\u200B", paddingNeeded)
  130. fmt.Fprint(w, padding)
  131. }
  132. }
  133. if history != "" {
  134. histParts := strings.Split("\n"+history, "\nQ: ")
  135. for _, part := range histParts[1:] {
  136. if i := strings.Index(part, "\nA: "); i >= 0 {
  137. question := part[:i]
  138. answer := part[i+4:]
  139. answer = strings.TrimRight(answer, "\n")
  140. fmt.Fprintf(w, "<div class=\"q\">%s</div>\n", html.EscapeString(question))
  141. fmt.Fprintf(w, "<div class=\"a\">%s</div>\n", answer)
  142. }
  143. }
  144. }
  145. fmt.Fprintf(w, "<div class=\"q\">%s</div>\n<div class=\"a\">", html.EscapeString(query))
  146. flusher.Flush()
  147. ch := make(chan string)
  148. go func() {
  149. htmlPrompt := htmlPromptPrefix + prompt
  150. if _, err := LLM(htmlPrompt, ch); err != nil {
  151. ch <- err.Error()
  152. close(ch)
  153. }
  154. }()
  155. response := ""
  156. for chunk := range ch {
  157. if _, err := fmt.Fprint(w, chunk); err != nil {
  158. return
  159. }
  160. response += chunk
  161. flusher.Flush()
  162. }
  163. fmt.Fprint(w, "</div>\n")
  164. finalHistory := history + fmt.Sprintf("Q: %s\nA: %s\n\n", query, response)
  165. fmt.Fprintf(w, htmlFooterTemplate, html.EscapeString(finalHistory))
  166. return
  167. }
  168. // More strict curl detection: only exact match or curl/ prefix
  169. isCurl := (userAgent == "curl" || strings.HasPrefix(userAgent, "curl/")) && !wantsHTML && !wantsJSON && !wantsStream
  170. if isCurl {
  171. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  172. w.Header().Set("Transfer-Encoding", "chunked")
  173. w.Header().Set("X-Accel-Buffering", "no")
  174. flusher := w.(http.Flusher)
  175. fmt.Fprintf(w, "Q: %s\nA: ", query)
  176. flusher.Flush()
  177. ch := make(chan string)
  178. go func() {
  179. if _, err := LLM(prompt, ch); err != nil {
  180. ch <- err.Error()
  181. close(ch)
  182. }
  183. }()
  184. response := ""
  185. for chunk := range ch {
  186. fmt.Fprint(w, chunk)
  187. response += chunk
  188. flusher.Flush()
  189. }
  190. fmt.Fprint(w, "\n")
  191. return
  192. }
  193. promptToUse := prompt
  194. if wantsHTML {
  195. promptToUse = htmlPromptPrefix + prompt
  196. }
  197. response, err := LLM(promptToUse, nil)
  198. if err != nil {
  199. content = err.Error()
  200. errJSON, _ := json.Marshal(map[string]string{"error": err.Error()})
  201. jsonResponse = string(errJSON)
  202. } else {
  203. respJSON, _ := json.Marshal(map[string]string{
  204. "question": query,
  205. "answer": response,
  206. })
  207. jsonResponse = string(respJSON)
  208. newExchange := fmt.Sprintf("Q: %s\nA: %s\n\n", query, response)
  209. if history != "" {
  210. content = history + newExchange
  211. } else {
  212. content = newExchange
  213. }
  214. if len(content) > 65536 {
  215. newExchangeLen := len(newExchange)
  216. if newExchangeLen > 65536 {
  217. content = newExchange[:65536]
  218. } else {
  219. maxHistory := 65536 - newExchangeLen
  220. if len(history) > maxHistory {
  221. content = history[len(history)-maxHistory:] + newExchange
  222. }
  223. }
  224. }
  225. }
  226. } else if history != "" {
  227. content = history
  228. }
  229. if wantsStream && query != "" {
  230. w.Header().Set("Content-Type", "text/event-stream")
  231. w.Header().Set("Cache-Control", "no-cache")
  232. w.Header().Set("Connection", "keep-alive")
  233. flusher, ok := w.(http.Flusher)
  234. if !ok {
  235. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  236. return
  237. }
  238. ch := make(chan string)
  239. go func() {
  240. if _, err := LLM(prompt, ch); err != nil {
  241. fmt.Fprintf(w, "data: Error: %s\n\n", err.Error())
  242. flusher.Flush()
  243. }
  244. }()
  245. for chunk := range ch {
  246. fmt.Fprintf(w, "data: %s\n\n", chunk)
  247. flusher.Flush()
  248. }
  249. fmt.Fprintf(w, "data: [DONE]\n\n")
  250. return
  251. }
  252. if wantsJSON && jsonResponse != "" {
  253. w.Header().Set("Content-Type", "application/json; charset=utf-8")
  254. fmt.Fprint(w, jsonResponse)
  255. } else if wantsHTML && query == "" {
  256. w.Header().Set("Content-Type", "text/html; charset=utf-8")
  257. fmt.Fprint(w, htmlHeader)
  258. parts := strings.Split("\n"+content, "\nQ: ")
  259. for _, part := range parts[1:] {
  260. if i := strings.Index(part, "\nA: "); i >= 0 {
  261. question := part[:i]
  262. answer := part[i+4:]
  263. answer = strings.TrimRight(answer, "\n")
  264. fmt.Fprintf(w, "<div class=\"q\">%s</div>\n", html.EscapeString(question))
  265. fmt.Fprintf(w, "<div class=\"a\">%s</div>\n", answer)
  266. }
  267. }
  268. fmt.Fprintf(w, htmlFooterTemplate, html.EscapeString(content))
  269. } else {
  270. w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  271. fmt.Fprint(w, content)
  272. }
  273. }
  274. type ChatRequest struct {
  275. Model string `json:"model"`
  276. Messages []Message `json:"messages"`
  277. Stream bool `json:"stream,omitempty"`
  278. }
  279. type Message struct {
  280. Role string `json:"role"`
  281. Content string `json:"content"`
  282. }
  283. type ChatResponse struct {
  284. ID string `json:"id"`
  285. Object string `json:"object"`
  286. Created int64 `json:"created"`
  287. Model string `json:"model"`
  288. Choices []Choice `json:"choices"`
  289. }
  290. type Choice struct {
  291. Index int `json:"index"`
  292. Message Message `json:"message"`
  293. }
  294. func handleChatCompletions(w http.ResponseWriter, r *http.Request) {
  295. w.Header().Set("Access-Control-Allow-Origin", "*")
  296. w.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS")
  297. w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
  298. w.Header().Set("Access-Control-Max-Age", "86400")
  299. if r.Method == "OPTIONS" {
  300. w.WriteHeader(http.StatusOK)
  301. return
  302. }
  303. if !rateLimitAllow(r.RemoteAddr) {
  304. http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
  305. return
  306. }
  307. if r.Method != "POST" {
  308. w.Header().Set("Allow", "POST, OPTIONS")
  309. http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
  310. return
  311. }
  312. var req ChatRequest
  313. if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
  314. http.Error(w, "Invalid JSON", http.StatusBadRequest)
  315. return
  316. }
  317. messages := make([]map[string]string, len(req.Messages))
  318. for i, msg := range req.Messages {
  319. messages[i] = map[string]string{
  320. "role": msg.Role,
  321. "content": msg.Content,
  322. }
  323. }
  324. if req.Stream {
  325. w.Header().Set("Content-Type", "text/event-stream")
  326. w.Header().Set("Cache-Control", "no-cache")
  327. w.Header().Set("Connection", "keep-alive")
  328. flusher, ok := w.(http.Flusher)
  329. if !ok {
  330. http.Error(w, "Streaming not supported", http.StatusInternalServerError)
  331. return
  332. }
  333. ch := make(chan string)
  334. go LLM(messages, ch)
  335. for chunk := range ch {
  336. resp := map[string]interface{}{
  337. "id": fmt.Sprintf("chatcmpl-%d", time.Now().Unix()),
  338. "object": "chat.completion.chunk",
  339. "created": time.Now().Unix(),
  340. "model": req.Model,
  341. "choices": []map[string]interface{}{{
  342. "index": 0,
  343. "delta": map[string]string{"content": chunk},
  344. }},
  345. }
  346. data, err := json.Marshal(resp)
  347. if err != nil {
  348. fmt.Fprintf(w, "data: Failed to marshal response\n\n")
  349. return
  350. }
  351. fmt.Fprintf(w, "data: %s\n\n", data)
  352. flusher.Flush()
  353. }
  354. fmt.Fprintf(w, "data: [DONE]\n\n")
  355. } else {
  356. response, err := LLM(messages, nil)
  357. if err != nil {
  358. http.Error(w, err.Error(), http.StatusInternalServerError)
  359. return
  360. }
  361. chatResp := ChatResponse{
  362. ID: fmt.Sprintf("chatcmpl-%d", time.Now().Unix()),
  363. Object: "chat.completion",
  364. Created: time.Now().Unix(),
  365. Model: req.Model,
  366. Choices: []Choice{{
  367. Index: 0,
  368. Message: Message{
  369. Role: "assistant",
  370. Content: response,
  371. },
  372. }},
  373. }
  374. w.Header().Set("Content-Type", "application/json")
  375. json.NewEncoder(w).Encode(chatResp)
  376. }
  377. }