Created
March 6, 2026 05:24
-
-
Save patmandenver/2674e45fc50ce8f8feca09325775c2b1 to your computer and use it in GitHub Desktop.
/usr/bin/claude-message
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 | |
| """ | |
| Simple script to generate a response using Anthropic's messages endpoint | |
| and report input/output tokens. | |
| Works both with piped input and command-line arguments. | |
| """ | |
| import sys | |
| import json | |
| import os | |
| import argparse | |
| import requests | |
| def get_content() -> str: | |
| """Get input either from stdin pipe or command line arguments""" | |
| if not sys.stdin.isatty(): | |
| return sys.stdin.read().rstrip() | |
| parser = argparse.ArgumentParser(description="Generate response using Anthropic API") | |
| parser.add_argument("text", nargs="*", help="Text prompt for the AI") | |
| args = parser.parse_args() | |
| if args.text: | |
| return " ".join(args.text) | |
| print("Error: No input provided", file=sys.stderr) | |
| print("Usage examples:", file=sys.stderr) | |
| print(" echo 'Hello world' | python generate_response.py", file=sys.stderr) | |
| print(" python generate_response.py 'Tell me a joke'", file=sys.stderr) | |
| sys.exit(1) | |
| def main(): | |
| api_key = os.environ.get("ANTHROPIC_API_KEY") or os.environ.get("ANTHROPIC_API_KEY_FIX") | |
| if not api_key: | |
| print("Error: ANTHROPIC_API_KEY environment variable not set", file=sys.stderr) | |
| sys.exit(1) | |
| content = get_content() | |
| payload = { | |
| "model": "claude-sonnet-4-6", # Updated to a real, active model (was "claude-sonnet-4-6") | |
| "messages": [ | |
| {"role": "user", "content": content} | |
| ], | |
| "max_tokens": 1024, # Adjust as needed | |
| "temperature": 0.7 # Optional: adjust for creativity | |
| } | |
| headers = { | |
| "x-api-key": api_key, | |
| "anthropic-version": "2023-06-01", | |
| "content-type": "application/json" | |
| } | |
| try: | |
| response = requests.post( | |
| "https://api.anthropic.com/v1/messages", # Active endpoint for generating responses | |
| headers=headers, | |
| json=payload, | |
| timeout=30 | |
| ) | |
| response.raise_for_status() | |
| data = response.json() | |
| # Extract the response content | |
| if "content" in data and data["content"]: | |
| ai_response = data["content"][0]["text"] | |
| print("AI Response:") | |
| print(ai_response) | |
| print("\n---") | |
| else: | |
| raise ValueError("No content in response") | |
| # Extract token usage | |
| usage = data.get("usage", {}) | |
| input_tokens = usage.get("input_tokens", "N/A") | |
| output_tokens = usage.get("output_tokens", "N/A") | |
| print(f"Tokens In: {input_tokens}") | |
| print(f"Tokens Out: {output_tokens}") | |
| except requests.RequestException as e: | |
| print("error", file=sys.stderr) | |
| print(f"Request failed: {e}", file=sys.stderr) | |
| if hasattr(e, 'response') and e.response is not None: | |
| print("Response content:", e.response.text, file=sys.stderr) | |
| sys.exit(1) | |
| except (KeyError, ValueError) as e: | |
| print("error", file=sys.stderr) | |
| print(f"Unexpected response format: {e}", file=sys.stderr) | |
| print("Full response:", json.dumps(data, indent=2), file=sys.stderr) | |
| sys.exit(1) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment