#!/bin/bash # AI-Cut: Structured field extraction tool # Beautiful implementation using composable functions SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" source "$SCRIPT_DIR/ai-common" show_usage() { cat << 'EOF' Usage: ai-cut -f FIELDS [FILE...] Extract structured fields from unstructured text using natural language field descriptions. Options: -f FIELDS Comma-separated field descriptions (required) -j Output as JSON objects (default: TSV) -h Show this help message EOF } build_extraction_prompt() { local fields="$1" local json_output="$2" local format_instructions if [[ "$json_output" == "true" ]]; then format_instructions='For each line or record in the input, extract the specified fields and output as a JSON object with the field names as keys. Output one JSON object per line. Output ONLY the raw JSON - do not wrap in markdown code blocks or add any other formatting. Example format: {"field1": "value1", "field2": "value2", "field3": "value3"}' else format_instructions='For each line or record in the input, extract the specified fields and output as tab-separated values. Output the fields in the same order as specified. Example format: value1 value2 value3' fi cat << EOF You are a structured data extraction tool. Extract the following fields from the unstructured text: $fields $format_instructions EOF } process_extraction_response() { local response="$1" local json_output="$2" if [[ "$json_output" == "true" ]]; then process_json_response "$response" else echo "$response" return 0 fi } validate_and_setup() { local fields="$1" shift local files=("$@") ensure_dependencies ensure_argument_provided "Field specification (-f)" "$fields" show_usage [[ ${#files[@]} -gt 0 ]] && ensure_files_exist "${files[@]}" } main() { local fields="" local json_output="false" local files=() # Parse options while getopts "f:jh" opt; do case $opt in f) fields="$OPTARG" ;; j) json_output="true" ;; h) handle_help_option show_usage ;; \?) handle_invalid_option "$OPTARG" ;; esac done shift $((OPTIND-1)) files=("$@") # Early validation with immediate exit on failure validate_and_setup "$fields" "${files[@]}" # Process input with early exit local input input=$(process_input_sources "${files[@]}") || exit "$EXIT_NO_MATCH" # Execute LLM request with early exit local prompt response prompt=$(build_extraction_prompt "$fields" "$json_output") response=$(execute_llm_request "$prompt" "$input") || handle_llm_error $? # Process response with early exit local result result=$(process_extraction_response "$response" "$json_output") || exit $? echo "$result" } main "$@"