1
0

chat.sh 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. #!/usr/bin/env 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. cache_prompt: true,
  43. stop: ["\n### Human:"],
  44. stream: true
  45. }')"
  46. ANSWER=''
  47. while IFS= read -r LINE; do
  48. if [[ $LINE = data:* ]]; then
  49. CONTENT="$(echo "${LINE:5}" | jq -r '.content')"
  50. printf "%s" "${CONTENT}"
  51. ANSWER+="${CONTENT}"
  52. fi
  53. done < <(curl \
  54. --silent \
  55. --no-buffer \
  56. --request POST \
  57. --url "${API_URL}/completion" \
  58. --header "Content-Type: application/json" \
  59. --data-raw "${DATA}")
  60. printf "\n"
  61. CHAT+=("$1" "$(trim "$ANSWER")")
  62. }
  63. while true; do
  64. read -r -e -p "> " QUESTION
  65. chat_completion "${QUESTION}"
  66. done