受公司脚本大神的启发,我今天也自己用32行代码做了个简单的命令行版chatgpt。
虽然网页版很好用,但这两天不知道为什么我的登录都被禁用了,好在api_key的curl方式还能用。
功能和大神们的当然没法比,不过好在简单,我自己也从中复习了一些bash array的坑人特性。
#!/bin/bash
export OPENAI_PROXY=socks5h://192.168.0.11:7890
export OPENAI_KEY=secrtkey-kfcvme50
source ~/.myopen_api_key #feed you own key
curlxk() {curl -sx ${OPENAI_PROXY} -H "Authorization: Bearer ${OPENAI_KEY}" "$@" | jq -rM '.choices[0].message'
}
function join_by {local d=${1-} f=${2-}if shift 2; thenprintf %s "$f" "${@/#/$d}"fi
}
declare talk_history=()
read -p 我问: line
while [ ! "$line" == "" ]; donew_item=$(echo '{"role": "user", "content": ""}'|jq -rMc --arg line "$line" '.content=$line')talk_history[${#talk_history[@]}]=$new_itemSAVEIFS="$IFS"IFS=','RESPONSE=$(curlxk -H "Content-Type: application/json" https://api.openai.com/v1/chat/completions \-d "$(echo '{"model": "gpt-3.5-turbo", "messages": [], "temperature": 0.7 }'| jq -rMc --argjson msgs "[${talk_history[*]}]" '.messages=$msgs')")IFS=${SAVEIFS}echo -n 'AI答:'echo $RESPONSE|jq -rM '.content'talk_history[${#talk_history[@]}]=$RESPONSEread -p 我问: line
done