Spaces:
Sleeping
Sleeping
| import os | |
| from typing import List, Dict | |
| try: | |
| from groq import Groq | |
| except ImportError: | |
| Groq = None | |
| DEFAULT_MODEL = "llama-3.3-70b-versatile" | |
| def get_client() -> "Groq": | |
| api_key = os.getenv("GROQ_API_KEY") | |
| if not api_key: | |
| raise RuntimeError("Missing GROQ_API_KEY. Set it in Space → Settings → Variables & Secrets.") | |
| if Groq is None: | |
| raise RuntimeError("Package 'groq' not installed. Add 'groq' to requirements.txt.") | |
| return Groq(api_key=api_key) | |
| def chat_once(messages: List[Dict[str, str]], | |
| model: str = DEFAULT_MODEL, | |
| temperature: float = 0.6, | |
| top_p: float = 0.9, | |
| max_tokens: int = 600) -> str: | |
| client = get_client() | |
| resp = client.chat.completions.create( | |
| model=model, | |
| messages=messages, | |
| temperature=temperature, | |
| top_p=top_p, | |
| max_tokens=max_tokens, | |
| ) | |
| return resp.choices[0].message.content.strip() | |
| def generate_post(prompt: str, | |
| model: str, | |
| temperature: float, | |
| top_p: float, | |
| max_tokens: int) -> str: | |
| messages = [ | |
| {"role": "system", "content": "You craft concise, original, high-signal LinkedIn posts. Respond with plain text only."}, | |
| {"role": "user", "content": prompt}, | |
| ] | |
| return chat_once(messages, model, temperature, top_p, max_tokens) | |
| def transform_post(instruction: str, | |
| post_text: str, | |
| model: str, | |
| temperature: float, | |
| top_p: float, | |
| max_tokens: int) -> str: | |
| messages = [ | |
| {"role": "system", "content": "You are a precise LinkedIn editor. Respond with plain text only."}, | |
| {"role": "user", "content": f"Instruction:\n{instruction}\n\nPost:\n{post_text}"} | |
| ] | |
| return chat_once(messages, model, temperature, top_p, max_tokens) | |
| def generate_hooks(topic: str, | |
| audience: str, | |
| tone: str, | |
| count: int, | |
| model: str, | |
| temperature: float, | |
| top_p: float, | |
| max_tokens: int) -> str: | |
| messages = [ | |
| {"role": "system", "content": "You generate punchy first lines for viral LinkedIn posts."}, | |
| {"role": "user", "content": f"Create {count} distinct, curiosity-driving first lines for a post.\nTopic: {topic}\nAudience: {audience}\nTone: {tone}\nRules: 1 line each, no labels, no emojis."} | |
| ] | |
| return chat_once(messages, model, temperature, top_p, max_tokens) | |