feat: set environment variable LLM_FUNCTION_NAME (#27)

This commit is contained in:
sigoden
2024-06-06 16:33:24 +08:00
committed by GitHub
parent 26b4338b81
commit 39447fb39e
3 changed files with 72 additions and 62 deletions
+38 -32
View File
@@ -1,47 +1,51 @@
#!/usr/bin/env node #!/usr/bin/env node
const path = require("path"); const path = require("path");
const fs = require('fs'); const fs = require("fs");
function parseArgv() { function parseArgv() {
let func_file = process.argv[1]; let funcName = process.argv[1];
let func_data = null; let funcData = null;
if (func_file.endsWith("bin.js")) { if (funcName.endsWith("bin.js")) {
func_file = process.argv[2] funcName = process.argv[2];
func_data = process.argv[3] funcData = process.argv[3];
} else { } else {
func_file = path.basename(func_file) funcName = path.basename(funcName);
func_data = process.argv[2]; funcData = process.argv[2];
} }
if (!func_file.endsWith(".js")) { if (funcName.endsWith(".js")) {
func_file += '.js' funcName = funcName.slice(0, -3);
} }
return [func_file, func_data] return [funcName, funcData];
} }
function loadFunc(func_file) { function loadFunc(funcName) {
const func_path = path.resolve(process.env["LLM_FUNCTIONS_DIR"], `tools/${func_file}`) const funcFileName = `${funcName}.js`;
const funcPath = path.resolve(
process.env["LLM_FUNCTIONS_DIR"],
`tools/${funcFileName}`,
);
try { try {
return require(func_path); return require(funcPath);
} catch { } catch {
console.log(`Invalid function: ${func_file}`) console.log(`Invalid function: ${funcFileName}`);
process.exit(1) process.exit(1);
} }
} }
function loadEnv(filePath) { function loadEnv(filePath) {
try { try {
const data = fs.readFileSync(filePath, 'utf-8'); const data = fs.readFileSync(filePath, "utf-8");
const lines = data.split('\n'); const lines = data.split("\n");
lines.forEach(line => { lines.forEach((line) => {
if (line.trim().startsWith('#') || line.trim() === '') return; if (line.trim().startsWith("#") || line.trim() === "") return;
const [key, ...value] = line.split('='); const [key, ...value] = line.split("=");
process.env[key.trim()] = value.join('=').trim(); process.env[key.trim()] = value.join("=").trim();
}); });
} catch {} } catch {}
} }
@@ -50,25 +54,27 @@ process.env["LLM_FUNCTIONS_DIR"] = path.resolve(__dirname, "..");
loadEnv(path.resolve(process.env["LLM_FUNCTIONS_DIR"], ".env")); loadEnv(path.resolve(process.env["LLM_FUNCTIONS_DIR"], ".env"));
const [func_file, func_data] = parseArgv(); const [funcName, funcData] = parseArgv();
process.env["LLM_FUNCTION_NAME"] = funcName;
if (process.env["LLM_FUNCTION_ACTION"] == "declarate") { if (process.env["LLM_FUNCTION_ACTION"] == "declarate") {
const { declarate } = loadFunc(func_file); const { declarate } = loadFunc(funcName);
console.log(JSON.stringify(declarate(), null, 2)) console.log(JSON.stringify(declarate(), null, 2));
} else { } else {
if (!func_data) { if (!funcData) {
console.log("No json data"); console.log("No json data");
process.exit(1) process.exit(1);
} }
let args; let args;
try { try {
args = JSON.parse(func_data) args = JSON.parse(funcData);
} catch { } catch {
console.log("Invalid json data") console.log("Invalid json data");
process.exit(1) process.exit(1);
} }
const { execute } = loadFunc(func_file); const { execute } = loadFunc(funcName);
execute(args) execute(args);
} }
+18 -15
View File
@@ -6,30 +6,31 @@ import sys
import importlib.util import importlib.util
def parse_argv(): def parse_argv():
func_file = sys.argv[0] func_name = sys.argv[0]
func_data = None func_data = None
if func_file.endswith("bin.py"): if func_name.endswith("bin.py"):
func_file = sys.argv[1] if len(sys.argv) > 1 else None func_name = sys.argv[1] if len(sys.argv) > 1 else None
func_data = sys.argv[2] if len(sys.argv) > 2 else None func_data = sys.argv[2] if len(sys.argv) > 2 else None
else: else:
func_file = os.path.basename(func_file) func_name = os.path.basename(func_name)
func_data = sys.argv[1] if len(sys.argv) > 1 else None func_data = sys.argv[1] if len(sys.argv) > 1 else None
if not func_file.endswith(".py"): if func_name.endswith(".py"):
func_file += ".py" func_name = func_name[:-3]
return func_file, func_data return func_name, func_data
def load_func(func_file): def load_func(func_name):
func_path = os.path.join(os.environ["LLM_FUNCTIONS_DIR"], f"tools/{func_file}") func_file_name = f"{func_name}.py"
func_path = os.path.join(os.environ["LLM_FUNCTIONS_DIR"], f"tools/{func_file_name}")
if os.path.exists(func_path): if os.path.exists(func_path):
spec = importlib.util.spec_from_file_location(func_file, func_path) spec = importlib.util.spec_from_file_location(f"{func_file_name}", func_path)
module = importlib.util.module_from_spec(spec) module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module) spec.loader.exec_module(module)
return module return module
else: else:
print(f"Invalid function: {func_file}") print(f"Invalid function: {func_file_name}")
sys.exit(1) sys.exit(1)
def load_env(file_path): def load_env(file_path):
@@ -45,14 +46,16 @@ def load_env(file_path):
except FileNotFoundError: except FileNotFoundError:
pass pass
os.environ["LLM_FUNCTIONS_DIR"] = os.path.join(os.path.dirname(__file__), "..") os.environ["LLM_FUNCTIONS_DIR"] = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
load_env(os.path.join(os.environ["LLM_FUNCTIONS_DIR"], ".env")) load_env(os.path.join(os.environ["LLM_FUNCTIONS_DIR"], ".env"))
func_file, func_data = parse_argv() func_name, func_data = parse_argv()
os.environ["LLM_FUNCTION_NAME"] = func_name
if os.getenv("LLM_FUNCTION_ACTION") == "declarate": if os.getenv("LLM_FUNCTION_ACTION") == "declarate":
module = load_func(func_file) module = load_func(func_name)
print(json.dumps(module.declarate(), indent=2)) print(json.dumps(module.declarate(), indent=2))
else: else:
if not func_data: if not func_data:
@@ -66,5 +69,5 @@ else:
print("Invalid json data") print("Invalid json data")
sys.exit(1) sys.exit(1)
module = load_func(func_file) module = load_func(func_name)
module.execute(args) module.execute(args)
+15 -14
View File
@@ -8,26 +8,27 @@ if [[ -f "$LLM_FUNCTIONS_DIR/.env" ]]; then
fi fi
if [[ "$0" == *bin.sh ]]; then if [[ "$0" == *bin.sh ]]; then
FUNC_FILE="$1" func_name="$1"
FUNC_DATA="$2" func_data="$2"
else else
FUNC_FILE="$(basename "$0")" func_name="$(basename "$0")"
FUNC_DATA="$1" func_data="$1"
fi fi
if [[ "$FUNC_FILE" != *'.sh' ]]; then if [[ "$func_name" == *.sh ]]; then
FUNC_FILE="$FUNC_FILE.sh" func_name="${func_name:0:$((${#func_name}-3))}"
fi fi
FUNC_FILE="$LLM_FUNCTIONS_DIR/tools/$FUNC_FILE" export LLM_FUNCTION_NAME="$func_name"
func_file="$LLM_FUNCTIONS_DIR/tools/$func_name.sh"
export JQ=jq export JQ=jq
if [[ "$OS" == "Windows_NT" ]]; then if [[ "$OS" == "Windows_NT" ]]; then
export JQ="jq -b" export JQ="jq -b"
FUNC_FILE="$(cygpath -w "$FUNC_FILE")" func_file="$(cygpath -w "$func_file")"
fi fi
if [[ "$LLM_FUNCTION_ACTION" == "declarate" ]]; then if [[ "$LLM_FUNCTION_ACTION" == "declarate" ]]; then
argc --argc-export "$FUNC_FILE" | \ argc --argc-export "$func_file" | \
$JQ -r ' $JQ -r '
def parse_description(flag_option): def parse_description(flag_option):
if flag_option.describe == "" then if flag_option.describe == "" then
@@ -69,13 +70,13 @@ if [[ "$LLM_FUNCTION_ACTION" == "declarate" ]]; then
parameters: parse_parameter([.flag_options[] | select(.id != "help" and .id != "version")]) parameters: parse_parameter([.flag_options[] | select(.id != "help" and .id != "version")])
}' }'
else else
if [[ -z "$FUNC_DATA" ]]; then if [[ -z "$func_data" ]]; then
echo "No json data" echo "No json data"
exit 1 exit 1
fi fi
data="$( data="$(
echo "$FUNC_DATA" | \ echo "$func_data" | \
$JQ -r ' $JQ -r '
to_entries | .[] | to_entries | .[] |
(.key | split("_") | join("-")) as $key | (.key | split("_") | join("-")) as $key |
@@ -92,10 +93,10 @@ else
} }
while IFS= read -r line; do while IFS= read -r line; do
if [[ "$line" == '--'* ]]; then if [[ "$line" == '--'* ]]; then
ARGS+=("$line") args+=("$line")
else else
ARGS+=("$(echo "$line" | $JQ -r '.')") args+=("$(echo "$line" | $JQ -r '.')")
fi fi
done <<< "$data" done <<< "$data"
"$FUNC_FILE" "${ARGS[@]}" "$func_file" "${args[@]}"
fi fi