AIFinder / example_api.py
CompactAI's picture
Upload 15 files
0051294 verified
#!/usr/bin/env python3
"""
Example: Call the AIFinder public API to classify text.
Usage:
python example_api.py
Requirements:
pip install requests
IMPORTANT — Strip <think>/<thinking> tags!
Many reasoning models wrap chain-of-thought in <think>…</think> or
<thinking>…</thinking> blocks. These tags confuse the classifier because
they are NOT part of the model's actual output style. The API strips them
automatically, but you should also strip them on your side to avoid sending
unnecessary data.
API details:
POST /v1/classify
No API key required. Rate limit: 60 requests/minute per IP.
"""
import re
import json
import requests
# Change this to your server URL (local or HuggingFace Space).
API_URL = "https://huggingface.co/spaces/CompactAI/AIFinder/v1/classify"
# Number of top results to return (default on server is 5).
TOP_N = 5
EXAMPLE_TEXT = """\
I'd be happy to help you understand how neural networks work!
Neural networks are computational models inspired by the human brain. They consist of layers of interconnected nodes (neurons) that process information. Here's a breakdown:
1. **Input Layer**: Receives the raw data
2. **Hidden Layers**: Process and transform the data through weighted connections
3. **Output Layer**: Produces the final prediction
Each connection has a weight, and each neuron has a bias. During training, the network adjusts these weights using backpropagation to minimize the difference between predicted and actual outputs.
The key insight is that by stacking multiple layers, neural networks can learn increasingly abstract representations of data, enabling them to solve complex tasks like image recognition, natural language processing, and more.
Would you like me to dive deeper into any specific aspect?
"""
def strip_think_tags(text: str) -> str:
"""Remove <think>…</think> and <thinking>…</thinking> blocks."""
return re.sub(
r"<think(?:ing)?>.*?</think(?:ing)?>", "", text, flags=re.DOTALL
).strip()
def classify(text: str, top_n: int = TOP_N) -> dict:
"""Send text to the AIFinder API and return the JSON response."""
cleaned = strip_think_tags(text)
resp = requests.post(
API_URL,
json={"text": cleaned, "top_n": top_n},
timeout=30,
)
resp.raise_for_status()
return resp.json()
def main():
print("AIFinder API Example")
print("=" * 50)
print(f"Endpoint : {API_URL}")
print(f"Top-N : {TOP_N}")
print()
result = classify(EXAMPLE_TEXT)
print(f"Best match : {result['provider']} ({result['confidence']:.1f}%)")
print()
print("Top providers:")
for entry in result["top_providers"]:
bar = "█" * int(entry["confidence"] / 5) + "░" * (
20 - int(entry["confidence"] / 5)
)
print(f" {entry['name']:.<25s} {entry['confidence']:5.1f}% {bar}")
if __name__ == "__main__":
main()