chat.sh 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #!/bin/bash
  2. API_URL="${API_URL:-http://127.0.0.1:8080}"
  3. CHAT=(
  4. "Hello, Assistant."
  5. "Hello. How may I help you today?"
  6. "Please tell me the largest city in Europe."
  7. "Sure. The largest city in Europe is Moscow, the capital of Russia."
  8. )
  9. INSTRUCTION="A chat between a curious human and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the human's questions."
  10. trim() {
  11. shopt -s extglob
  12. set -- "${1##+([[:space:]])}"
  13. printf "%s" "${1%%+([[:space:]])}"
  14. }
  15. trim_trailing() {
  16. shopt -s extglob
  17. printf "%s" "${1%%+([[:space:]])}"
  18. }
  19. format_prompt() {
  20. echo -n "${INSTRUCTION}"
  21. printf "\n### Human: %s\n### Assistant: %s" "${CHAT[@]}" "$1"
  22. }
  23. tokenize() {
  24. curl \
  25. --silent \
  26. --request POST \
  27. --url "${API_URL}/tokenize" \
  28. --header "Content-Type: application/json" \
  29. --data-raw "$(jq -ns --arg content "$1" '{content:$content}')" \
  30. | jq '.tokens[]'
  31. }
  32. N_KEEP=$(tokenize "${INSTRUCTION}" | wc -l)
  33. chat_completion() {
  34. PROMPT="$(trim_trailing "$(format_prompt "$1")")"
  35. DATA="$(echo -n "$PROMPT" | jq -Rs --argjson n_keep $N_KEEP '{
  36. prompt: .,
  37. temperature: 0.2,
  38. top_k: 40,
  39. top_p: 0.9,
  40. n_keep: $n_keep,
  41. n_predict: 256,
  42. stop: ["\n### Human:"],
  43. stream: true
  44. }')"
  45. ANSWER=''
  46. while IFS= read -r LINE; do
  47. if [[ $LINE = data:* ]]; then
  48. CONTENT="$(echo "${LINE:5}" | jq -r '.content')"
  49. printf "%s" "${CONTENT}"
  50. ANSWER+="${CONTENT}"
  51. fi
  52. done < <(curl \
  53. --silent \
  54. --no-buffer \
  55. --request POST \
  56. --url "${API_URL}/completion" \
  57. --header "Content-Type: application/json" \
  58. --data-raw "${DATA}")
  59. printf "\n"
  60. CHAT+=("$1" "$(trim "$ANSWER")")
  61. }
  62. while true; do
  63. read -r -e -p "> " QUESTION
  64. chat_completion "${QUESTION}"
  65. done