Spaces:
Configuration error
Configuration error
| """Helper for interacting with the Creator Catalog custom GPT.""" | |
| from __future__ import annotations | |
| import os | |
| from typing import Dict, List, Optional | |
| from openai import OpenAI | |
| def get_env(name: str) -> Optional[str]: | |
| """Return an env var, preferring HF space secret prefix.""" | |
| return os.environ.get(f"REPO_SECRET_{name}") or os.environ.get(name) | |
| DEFAULT_INSTRUCTIONS = ( | |
| "You are the Creator Catalog assistant. Provide concise, practical answers " | |
| "that help curate creator data, headshots, and related metadata." | |
| ) | |
| class CustomGPT: | |
| """Wrapper around the OpenAI API for a custom GPT.""" | |
| def __init__( | |
| self, | |
| model: Optional[str] = None, | |
| instructions: Optional[str] = None, | |
| temperature: float = 0.4, | |
| ) -> None: | |
| self.api_key = get_env("OPENAI_API_KEY") | |
| if not self.api_key: | |
| raise ValueError("Missing OPENAI_API_KEY (or REPO_SECRET_OPENAI_API_KEY)") | |
| self.base_url = get_env("OPENAI_BASE_URL") | |
| self.model = model or get_env("CUSTOM_GPT_MODEL") or "gpt-4o-mini" | |
| self.instructions = ( | |
| instructions or get_env("CUSTOM_GPT_INSTRUCTIONS") or DEFAULT_INSTRUCTIONS | |
| ) | |
| self.temperature = temperature | |
| self.client = OpenAI(api_key=self.api_key, base_url=self.base_url) | |
| def build_messages( | |
| self, | |
| prompt: str, | |
| history: Optional[List[Dict[str, str]]] = None, | |
| ) -> List[Dict[str, str]]: | |
| messages: List[Dict[str, str]] = [ | |
| {"role": "system", "content": self.instructions} | |
| ] | |
| if history: | |
| messages.extend(history) | |
| messages.append({"role": "user", "content": prompt}) | |
| return messages | |
| def run( | |
| self, | |
| prompt: str, | |
| history: Optional[List[Dict[str, str]]] = None, | |
| temperature: Optional[float] = None, | |
| ) -> str: | |
| """Send the prompt + history to the custom GPT and return the reply text.""" | |
| response = self.client.chat.completions.create( | |
| model=self.model, | |
| messages=self.build_messages(prompt, history), | |
| temperature=temperature if temperature is not None else self.temperature, | |
| ) | |
| return response.choices[0].message.content or "" | |