Last active
January 12, 2025 02:07
-
-
Save shaoyanji/85f97d067f3ebe034fea2d4a489ec4a4 to your computer and use it in GitHub Desktop.
tgpt integration within neovim
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env luajit | |
-- Handle command-line arguments | |
local args = {...} | |
for i, v in ipairs(args) do | |
-- print("Argument " .. i .. ": " .. v) | |
end | |
-- Handle piped input | |
--local piped_input = io.stdin:read("*a") | |
--if piped_input and piped_input ~= "" then | |
-- print("Received piped input:", piped_input) | |
--end | |
-- Your main script logic here | |
-- Fetch the x-vqd-4 header | |
local handle = io.popen("curl -s -X GET https://duckduckgo.com/duckchat/v1/status -H 'x-vqd-accept: 1' -D -") | |
local result = handle:read("*a") | |
handle:close() | |
-- Extract the x-vqd-4 value | |
local vqd = result:match("x%-vqd%-4: ([^\r\n]+)") | |
if vqd then | |
-- Use the extracted vqd in the POST request | |
local request = io.popen(string.format([[ | |
curl -s -X POST 'https://duckduckgo.com/duckchat/v1/chat' \ | |
-H 'x-vqd-4: %s' \ | |
-H 'Content-Type: application/json' \ | |
-H 'Accept: text/event-stream' \ | |
-d '{ | |
"model": "claude-3-haiku-20240307", | |
"messages": [{"role": "user", "content": "%s"}] | |
}' \ | |
--no-buffer | |
]], vqd, args[1])) | |
local response = request:read("*a") | |
request:close() | |
-- Parse the JSON stream and extract messages | |
local messages = {} | |
for line in response:gmatch("[^\r\n]+") do | |
if line:match("^data:") then | |
local message = line:match('"message":"(.-)"') | |
if message then | |
message = message:gsub('\\"', '"') -- Unescape quotes | |
table.insert(messages, message) | |
end | |
end | |
end | |
-- Concatenate and print messages | |
-- print("Extracted messages:") | |
print(table.concat(messages, "")) | |
else | |
-- print("Command output:\n" .. response) | |
--else | |
print("Failed to extract x-vqd-4 header") | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# /// script | |
# dependencies = [ | |
# "requests", | |
# ] | |
# /// | |
import requests | |
import json | |
import sys | |
from threading import Thread | |
from queue import Queue | |
import argparse | |
import sys | |
def choose_model(): | |
print() | |
print("Please choose an AI model:") | |
print("1. GPT-4o mini") | |
print("2. Claude 3 Haiku") | |
print("3. Llama 3.1 70B") | |
print("4. Mixtral 8x7B") | |
print() | |
models = { | |
"1": "gpt-4o-mini", | |
"2": "claude-3-haiku-20240307", | |
"3": "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", | |
"4": "mistralai/Mixtral-8x7B-Instruct-v0.1" | |
} | |
while True: | |
choice = input("Enter your choice (1-4): ").strip() | |
if choice in models: | |
return models[choice] | |
else: | |
print("Invalid choice. Please try again.") | |
def fetch_vqd(): | |
url = "https://duckduckgo.com/duckchat/v1/status" | |
headers = {"x-vqd-accept": "1"} | |
response = requests.get(url, headers=headers) | |
if response.status_code == 200: | |
return response.headers.get("x-vqd-4") | |
else: | |
raise Exception(f"Failed to initialize chat: {response.status_code} {response.text}") | |
def fetch_response(chat_url, vqd, model, messages): | |
payload = { | |
"model": model, | |
"messages": messages | |
} | |
headers = { | |
"x-vqd-4": vqd, | |
"Content-Type": "application/json", | |
"Accept": "text/event-stream" | |
} | |
response = requests.post(chat_url, headers=headers, json=payload, stream=True) | |
if response.status_code != 200: | |
raise Exception(f"Failed to send message: {response.status_code} {response.text}") | |
return response | |
def process_stream(response, output_queue): | |
for line in response.iter_lines(): | |
if line: | |
line = line.decode("utf-8") | |
if line == "data: [DONE]": | |
break | |
if line.startswith("data: "): | |
try: | |
data = json.loads(line[6:]) | |
message = data.get("message", "") | |
if message: | |
output_queue.put(message) | |
except json.JSONDecodeError: | |
continue | |
def interactive(): | |
model = choose_model() | |
try: | |
vqd = fetch_vqd() | |
except Exception as e: | |
print(f"Error: {e}") | |
sys.exit(1) | |
print() | |
print("Chat initialized successfully. You can start chatting now.") | |
print("Type 'exit' to end the conversation.") | |
print() | |
chat_url = "https://duckduckgo.com/duckchat/v1/chat" | |
messages = [] | |
while True: | |
print() | |
user_input = input("You: ").strip() | |
if user_input.lower() == "exit": | |
print("Exiting chat. Goodbye!") | |
break | |
messages.append({"content": user_input, "role": "user"}) | |
try: | |
response = fetch_response(chat_url, vqd, model, messages) | |
except Exception as e: | |
print(f"Error: {e}") | |
continue | |
output_queue = Queue() | |
thread = Thread(target=process_stream, args=(response, output_queue)) | |
thread.start() | |
print() | |
print("AI:", end=" ") | |
while thread.is_alive() or not output_queue.empty(): | |
while not output_queue.empty(): | |
print(output_queue.get(), end="", flush=True) | |
print() | |
thread.join() | |
def noninteractive(text): | |
model = "claude-3-haiku-20240307" | |
try: | |
vqd = fetch_vqd() | |
except Exception as e: | |
print(f"Error: {e}") | |
sys.exit(1) | |
chat_url = "https://duckduckgo.com/duckchat/v1/chat" | |
messages = [] | |
messages.append({"content": text, "role": "user"}) | |
try: | |
response = fetch_response(chat_url, vqd, model, messages) | |
except Exception as e: | |
print(f"Error: {e}") | |
output_queue = Queue() | |
thread = Thread(target=process_stream, args=(response, output_queue)) | |
thread.start() | |
print() | |
while thread.is_alive() or not output_queue.empty(): | |
while not output_queue.empty(): | |
print(output_queue.get(), end="", flush=True) | |
print() | |
thread.join() | |
def main(): | |
"""Inspired by duckduckGO-chat-cli""" | |
parser = argparse.ArgumentParser(description="a simple CLI program that takes a comment and returns a response") | |
parser.add_argument('texts', nargs='+', help='Text inputs to be processed') | |
args = parser.parse_args() | |
if args.texts: | |
noninteractive(" ".join(args.texts)) | |
else: | |
interactive() | |
if __name__ == "__main__": | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# Run the LuaJIT script and capture its output | |
args_string="$*" | |
output=$(luajit $(which duck.lua) "$args_string") | |
# Use echo -e to print the output | |
echo -e "$output" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
vim.api.nvim_set_keymap('n', '<C-Enter>', ':%! tgpt -q -w<CR>', { noremap = true, silent = true }) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment