Download runtime/graphkit/_api.py from VISAI-AI/icj-citation-graph: direct link, hf CLI and curl.
- Browser
- Download file 2.98 kB
-
https://huggingface.co/datasets/VISAI-AI/icj-citation-graph/resolve/main/runtime/graphkit/_api.py
- Command line
-
hf download hf://datasets/VISAI-AI/icj-citation-graph/runtime/graphkit/_api.py
-
curl -L -o _api.py https://huggingface.co/datasets/VISAI-AI/icj-citation-graph/resolve/main/runtime/graphkit/_api.py
2.98 kB
| import os | |
| import time | |
| from urllib.parse import urlsplit | |
| import requests | |
| from ._vectors import validate_vectors | |
| def api_settings(): | |
| endpoint = os.getenv('EMBEDDING_BASE_URL', '').rstrip('/') | |
| model = os.getenv('EMBEDDING_MODEL', '') | |
| if not endpoint or not model: | |
| raise ValueError('Set EMBEDDING_BASE_URL and EMBEDDING_MODEL before calling the API.') | |
| if not endpoint.endswith('/embeddings'): | |
| endpoint += '/embeddings' | |
| parsed = urlsplit(endpoint) | |
| if parsed.scheme not in {'http', 'https'} or not parsed.hostname or parsed.username or parsed.password: | |
| raise ValueError('Use an HTTP(S) endpoint without credentials in the URL.') | |
| dimension = int(os.getenv('EMBEDDING_DIMENSIONS', '0')) | |
| max_chars = int(os.getenv('EMBEDDING_MAX_CHARS', '8000')) | |
| if dimension < 0 or max_chars < 1: | |
| raise ValueError('Dimensions must be nonnegative and max chars positive.') | |
| return {'endpoint': endpoint, 'model': model, 'dimensions': dimension, 'max_chars': max_chars, | |
| 'prefix': os.getenv('EMBEDDING_DOCUMENT_PREFIX', ''), 'normalize': True} | |
| def response_vectors(payload, count, dimension): | |
| items = payload.get('data') | |
| if not isinstance(items, list) or len(items) != count: | |
| raise ValueError('Embedding response count does not match the request.') | |
| indexes = [item.get('index') for item in items] | |
| if any(type(index) is not int for index in indexes) or sorted(indexes) != list(range(count)): | |
| raise ValueError('Embedding response indexes are missing, duplicated or out of range.') | |
| ordered = sorted(items, key=lambda item: item['index']) | |
| return validate_vectors([item['embedding'] for item in ordered], dimension, normalize=True) | |
| def embed(settings, texts): | |
| payload = {'model': settings['model'], 'input': [settings['prefix'] + text[:settings['max_chars']] for text in texts], 'encoding_format': 'float'} | |
| if settings['dimensions']: | |
| payload['dimensions'] = settings['dimensions'] | |
| headers = {'Content-Type': 'application/json'} | |
| if os.getenv('EMBEDDING_API_KEY'): | |
| headers['Authorization'] = 'Bearer ' + os.environ['EMBEDDING_API_KEY'] | |
| for attempt in range(5): | |
| try: | |
| response = requests.post(settings['endpoint'], json=payload, headers=headers, timeout=(15, 120)) | |
| except (requests.ConnectionError, requests.Timeout): | |
| if attempt == 4: | |
| raise RuntimeError('Embedding endpoint connection failed after five attempts.') from None | |
| else: | |
| if response.status_code == 200: | |
| return response_vectors(response.json(), len(texts), settings['dimensions']) | |
| if response.status_code not in {408, 429, 500, 502, 503, 504} or attempt == 4: | |
| raise RuntimeError(f'Embedding endpoint returned HTTP {response.status_code}; check model, credentials and limits.') | |
| time.sleep(min(2 ** attempt, 16)) | |
| raise RuntimeError('Embedding retries exhausted.') | |