• Stars
    star
    114
  • Rank 300,985 (Top 7 %)
  • Language
    Python
  • License
    MIT License
  • Created over 1 year ago
  • Updated about 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A single-file Python script that interacts with ChatGPT API in the command-line.

ai.py

A single-file Python script that interacts with ChatGPT API in the command-line.

Features:

  • Use shortcuts to access predefined prompts
  • Highlight code in output
  • Support one-shot queries and conversations
  • Use special command like !set to control the behavior when chatting

Install

Just copy the script to a folder in $PATH, like /usr/local/bin. You can also change its name to ai to get ride of the .py extension.

Here's a command that can directly install the script into your system:

curl https://raw.githubusercontent.com/reorx/ai.py/master/ai.py -o /usr/local/bin/ai && chmod +x /usr/local/bin/ai

You can also install it with pip or pipx:

pip install aidotpy

Usage

Paste your OpenAI API key to ~/.config/ai-py/config.json, or set it in AI_PY_API_KEY environment variable.

mkdir -p ~/.config/ai-py
echo '{"api_key":"<Your API key>"}' > ~/.config/ai-py/config.json

For detail usage of the script, please read the description of ./ai.py -h:

usage: ai [-h] [-s SYSTEM] [-c] [--history HISTORY] [-w] [-v] [-t] [-d] [--version] [PROMPT]

A simple CLI for ChatGPT API

positional arguments:
  PROMPT                your prompt, leave it empty to run REPL. you can use @ to load prompt
                        from the prompts file.

options:
  -h, --help            show this help message and exit
  -s SYSTEM, --system SYSTEM
                        system message to use at the beginning of the conversation. if starts
                        with @, the message will be located through the prompts file
  -c, --conversation    enable conversation, which means all the messages will be sent to the
                        API, not just the last one. This is only useful to REPL
  --history HISTORY     load the history from a JSON file.
  -w, --write-history   write new messages to --history file after each chat.
  -v, --verbose         verbose mode, show execution info and role in the message
  -t, --show-tokens     show a breakdown of the tokens used in the prompt and in the response
  -d, --debug           debug mode, enable logging
  --version             show program's version number and exit

One-off query

Pass the prompt as the first argument:

./ai.py 'hello world'

You can also pass the prompt through a pipe (|):

head README.md | ./ai.py 'Proofreading the following text:'

REPL

Run without argument for Readโ€“evalโ€“print loop:

./ai.py

By default only the last message and the system message are sent to the API, if you want it to remember all the context (i.e. send all the messages in each chat), add -c argument to enable conversation:

./ai.py -c

System message

You can pass a system message to define the behavior for the assistant:

./ai.py -s 'You are a proofreader' 'its nice know you'

You can also save your predefined system messages in ~/.config/ai-py/prompts.json and refer them with @ at the beginning, this will be covered in the next section.

Prompt shortcuts

You can predefine prompts in ~/.config/ai-py/prompts.json and refer to them by using @ as a prefix. This works for both system messages and user messages.

Suppose your ~/.config/ai-py/prompts.json looks like this:

{
  "system": {
    "cli": "As a technology assistant with expertise in command line, answer questions in simple and short words for users who have a high-level background. Provide only one example, and explain as less as possible."
  },
  "user": {
    "native": "Paraphrase the following sentences to make it more native:\n",
    "revise": "Revise the following sentences to make them more clear concise and coherent:\n",
    "": ""
  }
}

Then you can use the cli prompt shortcut in system message by:

./ai.py -s @cli

and use the native or revise prompt shortcut in user message by:

./ai.py '@native its nice know you'

It's great to get to know you.

Verbose mode

Add -v to print role name and parameters used in the API call.

Screenshot

Special commands

You can use special commands to control the behavior of the script when running in REPL.

Here's a list of available commands:

  • !set <key> <value>: set a key-value pair in the config, available keys are:
    • verbose: set to True or False, e.g. !set verbose True
    • conversation: set to True or False, e.g. !set conversation True
    • system: set the system message. e.g. !set system you are a poet, !set system @cli
    • params: set the parmeters for the ChatGPT API. e.g. !set params temperature 0.5
    • model: set the model to use. e.g. !set model gpt-4
  • !info: print the execution info
  • !write-history: write current messages to history file. e.g. !write-history history.json

More Repositories

1

awesome-chatgpt-api

Curated list of apps and tools that not only use the new ChatGPT API, but also allow users to configure their own API keys, enabling free and on-demand usage of their own quota.
Python
5,617
star
2

httpstat

curl statistics made simple
Python
5,588
star
3

sui2

a startpage for your server and / or new tab page
JavaScript
391
star
4

Share-to-ChatGPT-Shortcut

An Apple Shortcut for sharing text to ChatGPT using personalized prompts
303
star
5

jsoncv

A toolkit for building your CV with JSON and creating stylish HTML/PDF files.
JavaScript
249
star
6

obsidian-paste-image-rename

Renames pasted images and all the other attachments added to the vault
TypeScript
234
star
7

cht-colors

Chinese Traditional Colors
HTML
216
star
8

python-terminal-color

Drop-in single file library for printing color in terminal
Python
69
star
9

torext

[WORKING ON] The missing tornado mate
Python
61
star
10

minimal-bilibili

็ป™ไฝ ็บฏๅ‡€็š„ Bilibili ่ง†้ข‘ๅ‘็Žฐไฝ“้ชŒ
TypeScript
60
star
11

xiami_exporter

Export your data from Xiami
JavaScript
59
star
12

github-toc-sidebar

Show GitHub Readme TOC as a sidebar
TypeScript
44
star
13

n8n-workflows

My workflows for n8n automation
Python
38
star
14

obsidian-people-link

Easily create links to people within your documents.
TypeScript
37
star
15

obsidian-telegraph-publish

Publish your Obsidian note to a Telegraph page.
TypeScript
36
star
16

refgen

JavaScript
34
star
17

flomo-to-obsidian

JavaScript
30
star
18

cx-extractor

Automatically exported from code.google.com/p/cx-extractor
HTML
29
star
19

autotagger

Tag .mp3 and .m4a audio files from iTunes data automatically.
Python
28
star
20

substance

Extract substance from the web
HTML
23
star
21

obsidian-daily-notes-opener

Easily open daily notes and periodic notes in new pane; customize periodic notes background; quick append new line to daily notes.
TypeScript
21
star
22

project_sketch

A nerd's boilerplate for your Python project.
Python
20
star
23

readability

html main body extractor
HTML
17
star
24

dotfiles

my rcs
Vim Script
15
star
25

deptest

dependent testing framework
Python
15
star
26

chatroom

simple chatroom using tornado long polling feature
JavaScript
14
star
27

rdl

Redis dump & load tool.
Python
12
star
28

squared

JavaScript
11
star
29

simplemongo

A Simple & Clear MongoDB ORM
Python
9
star
30

ts

Twitter Search CLI
Python
9
star
31

xiamifav

xiami html5 client
JavaScript
7
star
32

miniflux-on-railway

miniflux deployed on railway.app
Python
7
star
33

drawtable

Draw ASCII art box with text.
Python
7
star
34

getenv

Environment variable definition with type
Python
7
star
35

userscripts

My UserScripts
JavaScript
7
star
36

blog

HTML
6
star
37

params

A Python package that does better in request parameters validation than django.forms, wtforms, web_args or so.
Python
6
star
38

n8n-on-railway

Shell
6
star
39

eurasia

Automatically exported from code.google.com/p/eurasia
Python
5
star
40

things-to-ticktick

Export tasks from Things.app to TickTick format
Shell
5
star
41

pyconv

Text file code conversion tool
Python
4
star
42

dbflip

flip reading for douban note
JavaScript
4
star
43

beatles

Data and tools to enjoy The Beatles better.
Python
4
star
44

rss-filter

Modify and regenerate RSS source piped in
TypeScript
4
star
45

V2EXWitch

Chrome Extension - V2EX Account Switcher & Notifier
JavaScript
3
star
46

python-playground

Python
3
star
47

scripts

miscellaneous scripts I use
Shell
3
star
48

litekv

Simple kv store for Python
Python
3
star
49

cv

My CV site.
JavaScript
3
star
50

window-opener

TypeScript
3
star
51

pex_uwsgi_demo

Python
3
star
52

json_include

An extension for JSON to support file including
Python
3
star
53

feishu-exporter

Export Feishu docs with ease
JavaScript
3
star
54

fuload

Automatically exported from code.google.com/p/fuload
C++
2
star
55

gouken

Go microservice framework built on top of grpc
Go
2
star
56

aima-python

Automatically exported from code.google.com/p/aima-python
Python
2
star
57

django_starter_pack

My personal starter pack for Django projects
Python
2
star
58

learn_applescript

Notes & code pieces recorded during my exploration to AppleScript.
AppleScript
2
star
59

minireact

A minimal react project boilerplate
JavaScript
2
star
60

stexplorer

Download songs from SongTaste
Python
2
star
61

gopkg_opml

Python
1
star
62

qdan-archives

my archives on qdan.me
CSS
1
star
63

papermodx-example

HTML
1
star
64

rime_dict

Tools for manipulating userdict of rime input method
Python
1
star
65

pinback

Pinboard backup tool
Python
1
star
66

apibox

[WORKING ON] Building blocks for HTTP API development
Python
1
star
67

learn_spider

Practicing code to learn to write a spider
Python
1
star
68

whuspec

My graduation project.
HTML
1
star
69

obsidian-chatgpt

TypeScript
1
star
70

go-to-douban

I am Xiao Meng, and I want to work in Douban, I create this repository for announcing and yelling
1
star
71

start

Shell
1
star
72

python-installer

Shell
1
star
73

printable-css

HTML
1
star
74

kindle_ebook_template

for publishing kindle ebook - specially for chinese
1
star
75

pinyindep

essentials for implement pinyin transforming capability in your projects with python
Python
1
star
76

quiverweb

Web service for Quiver note app
Python
1
star
77

gatsby-starter-netlify-cms

JavaScript
1
star
78

alfred-workflows

my alfred workflows
Python
1
star
79

awesome-javascript-editors

A collection of awesome javascript editors
1
star
80

torext-admin

Python
1
star
81

html-cutter

A Chrome extension to cut out HTML fragments from a page.
JavaScript
1
star
82

simplate

Created with CodeSandbox
JavaScript
1
star
83

tomorrow

A new task scheduler, aimed at quick, clean, and clear
1
star
84

webpack-chrome-boilerplate

A boilerplate for building Chrome extensions with Webpack
TypeScript
1
star
85

SMU-MScCDA-ProgrammingTest-2023

Python
1
star
86

nasdaqtrader-rss

Python
1
star
87

n8n-on-fly

1
star
88

proto-typist

generate proto code from proto code
Python
1
star
89

project-nowhere

Automatically exported from code.google.com/p/project-nowhere
PHP
1
star