if "joke" in message.lower(): try: logger.info("Initializing OpenAI client for NSFW joke") client = OpenAI(api_key=config['xai_api_key'], base_url=config['api_base_url']) # Get recent jokes from history (last 3 assistant responses with "joke" intent) recent_jokes = [msg['content'] for msg in list(history)[-6:] if msg['role'] == 'assistant' and 'joke' in msg.get('content', '').lower()] recent_jokes_str = "; ".join(recent_jokes) if recent_jokes else "none" joke_prompt = ( f"Generate a crude, adult-themed joke in British English, using varied themes (e.g., food, animals, objects, pub life) and slang like 'shagging', 'knob', 'bollocking', or 'tits up', " f"similar in tone to 'The cheeky carrots were proper knobbed up in the soup!' " f"Keep it short, cheeky, suitable for an IRC audience, and distinct from these recent jokes: {recent_jokes_str}. " f"Deliver the joke in one sentence." ) response = client.chat.completions.create( model="grok-3", messages=[ {"role": "system", "content": joke_prompt}, {"role": "user", "content": "Tell me a crude NSFW joke."} ], temperature=0.9, # random af max_tokens=50, timeout=config['api_timeout'] ) reply = response.choices[0].message.content.strip() reply = normalize_reply_text(reply) logger.info(f"Generated NSFW joke: {reply}") except (APIError, APIConnectionError, Timeout, BadRequestError) as e: logger.error(f"Joke API call failed: {type(e).__name__}: {str(e)}") reply = "The naughty spud got caught shagging in the stew!" history.append({"role": "user", "content": message}) history.append({"role": "assistant", "content": reply}) save_history(session_key, history) return jsonify({'reply': reply}), 200, {'Cache-Control': 'no-store, no-cache, must-revalidate, max-age=0', 'X-Session-ID': session_id, 'X-Timestamp': timestamp}