|
| 1 | +import hashlib |
| 2 | +import json |
| 3 | +import os |
| 4 | +import time |
| 5 | +import requests |
| 6 | +from dotenv import load_dotenv |
| 7 | +from typing import Optional |
| 8 | +from requests.exceptions import HTTPError |
| 9 | + |
| 10 | +load_dotenv(override=True) |
| 11 | + |
| 12 | +# Create schema-to-js_id mapping |
| 13 | +API_HOST = os.environ.get("DOTTXT_API_HOST", "api.dottxt.co") |
| 14 | +API_KEY = os.environ.get("DOTTXT_API_KEY", None) |
| 15 | + |
| 16 | +def check_api_key() -> None: |
| 17 | + if not API_KEY: |
| 18 | + raise ValueError("DOTTXT_API_KEY environment variable is not set") |
| 19 | + |
| 20 | +def get_headers(api_key: Optional[str] = None) -> dict: |
| 21 | + if api_key is None: |
| 22 | + check_api_key() |
| 23 | + api_key = API_KEY |
| 24 | + return {"Authorization": f"Bearer {api_key}"} |
| 25 | + |
| 26 | +SCHEMA_HASH_TO_COMPLETION_URL = {} |
| 27 | + |
| 28 | +def to_hash(pydantic_class): |
| 29 | + schema = pydantic_class.model_json_schema() |
| 30 | + schema_string = json.dumps(schema) |
| 31 | + return hashlib.sha256(schema_string.encode()).hexdigest() |
| 32 | + |
| 33 | +def poll_status(url: str, api_key: Optional[str] = None) -> dict: |
| 34 | + headers = get_headers(api_key) |
| 35 | + while True: |
| 36 | + status_res = requests.get(url, headers=headers) |
| 37 | + status_json = status_res.json() |
| 38 | + if status_res.status_code != 200 or status_json["status"] != "in_progress": |
| 39 | + break |
| 40 | + time.sleep(1) |
| 41 | + return status_json |
| 42 | + |
| 43 | +def get_schema_by_name(name: str, api_key: Optional[str] = None) -> Optional[dict]: |
| 44 | + headers = get_headers(api_key) |
| 45 | + try: |
| 46 | + response = requests.get(f"https://{API_HOST}/v1/json-schemas", headers=headers) |
| 47 | + response.raise_for_status() |
| 48 | + schemas = response.json()['items'] |
| 49 | + |
| 50 | + for schema in schemas: |
| 51 | + if schema['name'] == name: |
| 52 | + return schema |
| 53 | + return None |
| 54 | + except HTTPError as e: |
| 55 | + if e.response.status_code == 403: |
| 56 | + raise ValueError("Authentication failed. Please check your API key.") from e |
| 57 | + else: |
| 58 | + raise |
| 59 | + except Exception as e: |
| 60 | + raise |
| 61 | + |
| 62 | + |
| 63 | +def create_schema(schema: str, name: str, api_key: Optional[str] = None) -> dict: |
| 64 | + data = {"name": name, "json_schema": schema} |
| 65 | + headers = get_headers(api_key) |
| 66 | + try: |
| 67 | + response = requests.post( |
| 68 | + f"https://{API_HOST}/v1/json-schemas", |
| 69 | + headers=headers, |
| 70 | + json=data |
| 71 | + ) |
| 72 | + response.raise_for_status() |
| 73 | + return response.json() |
| 74 | + except HTTPError as e: |
| 75 | + if e.response.status_code == 403: |
| 76 | + raise ValueError("Authentication failed. Please check your API key.") from e |
| 77 | + else: |
| 78 | + raise |
| 79 | + except Exception as e: |
| 80 | + raise |
| 81 | + |
| 82 | + |
| 83 | +def get_completion_endpoint(model_class, api_key: Optional[str] = None): |
| 84 | + schema_hash = to_hash(model_class) |
| 85 | + |
| 86 | + if schema_hash in SCHEMA_HASH_TO_COMPLETION_URL: |
| 87 | + completion_url = SCHEMA_HASH_TO_COMPLETION_URL[schema_hash] |
| 88 | + return completion_url |
| 89 | + |
| 90 | + # Check next to see if the schema_has is already stored by checking |
| 91 | + # GET https://api.dottxt.co/v1/json-schemas |
| 92 | + schema_response = get_schema_by_name(schema_hash, api_key) |
| 93 | + |
| 94 | + # If the schema exists poll the status and return the completion URL |
| 95 | + if schema_response: |
| 96 | + status_url = schema_response["status_url"] |
| 97 | + final_status = poll_status(status_url, api_key) |
| 98 | + completion_url = final_status["completion_url"] |
| 99 | + if completion_url: |
| 100 | + SCHEMA_HASH_TO_COMPLETION_URL[schema_hash] = completion_url |
| 101 | + return completion_url |
| 102 | + |
| 103 | + # Okay, we don't have a completion URL for this schema. Let's create it. |
| 104 | + schema_string = json.dumps(model_class.model_json_schema()) |
| 105 | + schema_response = create_schema(schema_string, schema_hash, api_key) |
| 106 | + |
| 107 | + # If we get here, we need to wait for the schema to be created |
| 108 | + status_url = schema_response["status_url"] |
| 109 | + final_status = poll_status(status_url, api_key) |
| 110 | + |
| 111 | + completion_url = final_status["completion_url"] |
| 112 | + if not completion_url: |
| 113 | + raise ValueError(f"No completion URL available for schema: {schema_hash}") |
| 114 | + |
| 115 | + SCHEMA_HASH_TO_COMPLETION_URL[schema_hash] = completion_url |
| 116 | + return completion_url |
| 117 | + |
| 118 | +def create_completion(model_class, prompt: str, max_tokens: int = 30000, api_key: Optional[str] = None): |
| 119 | + completion_url = get_completion_endpoint(model_class, api_key) |
| 120 | + data = {"prompt": prompt, "max_tokens": max_tokens} |
| 121 | + headers = get_headers(api_key) |
| 122 | + completion_response = requests.post(completion_url, headers=headers, json=data) |
| 123 | + completion_response.raise_for_status() |
| 124 | + |
| 125 | + # get json |
| 126 | + completion_response_json = completion_response.json() |
| 127 | + |
| 128 | + # convert to pydantic model |
| 129 | + model = model_class.model_validate_json(completion_response_json['data']) |
| 130 | + |
| 131 | + return model |
0 commit comments