chat.sh 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. --data-raw "$(jq -ns --arg content "$1" '{content:$content}')" \
  29. | jq '.tokens[]'
  30. }
  31. N_KEEP=$(tokenize "${INSTRUCTION}" | wc -l)
  32. chat_completion() {
  33. PROMPT="$(trim_trailing "$(format_prompt "$1")")"
  34. DATA="$(echo -n "$PROMPT" | jq -Rs --argjson n_keep $N_KEEP '{
  35. prompt: .,
  36. temperature: 0.2,
  37. top_k: 40,
  38. top_p: 0.9,
  39. n_keep: $n_keep,
  40. n_predict: 256,
  41. stop: ["\n### Human:"],
  42. stream: true
  43. }')"
  44. ANSWER=''
  45. while IFS= read -r LINE; do
  46. if [[ $LINE = data:* ]]; then
  47. CONTENT="$(echo "${LINE:5}" | jq -r '.content')"
  48. printf "%s" "${CONTENT}"
  49. ANSWER+="${CONTENT}"
  50. fi
  51. done < <(curl \
  52. --silent \
  53. --no-buffer \
  54. --request POST \
  55. --url "${API_URL}/completion" \
  56. --data-raw "${DATA}")
  57. printf "\n"
  58. CHAT+=("$1" "$(trim "$ANSWER")")
  59. }
  60. while true; do
  61. read -r -e -p "> " QUESTION
  62. chat_completion "${QUESTION}"
  63. done