http.go 11 KB

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