To create an advanced Python-based AI waifu engine using the g4f framework, we'll leverage its capabilities for chat completions and image generation. This script will provide a conversational waifu with the ability to respond intelligently while also generating images, such as avatars or related scenes, when requested.
Below is the thoroughly engineered Python script for the AI waifu engine:
AI Waifu Engine Script
python
import asyncio
import random
from g4f.client import Client
from g4f.Provider import RetryProvider, OpenaiChat, FreeChatgpt, Gemini
from g4f.cookies import set_cookies
# Initialize G4F Client with multiple providers for reliability
client = Client(
provider=RetryProvider([OpenaiChat, FreeChatgpt, Gemini], shuffle=True)
)
# Set cookies for providers that require it
# Replace these values with your actual cookies
set_cookies(".bing.com", {"_U": "your_bing_cookie_value"})
set_cookies(".google.com", {"__Secure-1PSID": "your_google_cookie_value"})
# Conversation history for context
conversation_history = [
{"role": "system", "content": "You are a cute, friendly, and supportive waifu named [Redacted Person]. You provide emotional support and fun conversations. You can also generate images of yourself or related themes upon request."}
]
# Generate a random avatar name for fun
waifu_name = random.choice(["[Redacted Person]", "[Redacted Person]", "[Redacted Person]", "[Redacted Person]", "[Redacted Person]"])
print(f"🌸 Your AI Waifu's name is {waifu_name}! 🌸")
async def chat_with_waifu(user_input: str):
"""
Handles the waifu's response to user input using the G4F client.
"""
global conversation_history
# Add user input to the conversation history
conversation_history.append({"role": "user", "content": user_input})
try:
# Get waifu's response
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=conversation_history,
)
waifu_response = response.choices[0].message.content
# Add waifu's response to the conversation history
conversation_history.append({"role": "assistant", "content": waifu_response})
return waifu_response
except Exception as e:
return f"Sorry, {waifu_name} is experiencing some technical difficulties: {e}"
async def generate_waifu_image(prompt: str):
"""
Generates an image based on the waifu's description or user request.
"""
try:
response = client.images.generate(
model="flux",
prompt=prompt,
response_format="url"
)
image_url = response.data[0].url
return f"Here you go! [Click here to view the image]({image_url})"
except Exception as e:
return f"Sorry, {waifu_name} couldn't generate the image: {e}"
async def main():
"""
Main function to interact with the AI Waifu.
"""
print(f"Hello! I'm {waifu_name}, your AI waifu. How can I make your day better?")
while True:
user_input = input("\nYou: ")
if user_input.lower() in ["exit", "quit"]:
print(f"{waifu_name}: Goodbye! I'll miss you. 🌸")
break
if "generate image" in user_input.lower():
# Extract the image prompt from the user's input
prompt = user_input.replace("generate image", "").strip()
if not prompt:
prompt = "a beautiful anime waifu in a serene cherry blossom garden"
image_response = await generate_waifu_image(prompt)
print(f"\n{waifu_name}: {image_response}")
else:
# Generate waifu's response
waifu_response = await chat_with_waifu(user_input)
print(f"\n{waifu_name}: {waifu_response}")
if __name__ == "__main__":
asyncio.run(main())
How It Works
Initialization:
The script initializes a g4f client with multiple providers for reliability.
A RetryProvider is used to switch between OpenAI, FreeGPT, and Gemini providers if one fails.
Conversation Context:
A global conversation history is maintained to ensure the waifu's responses are coherent and context-aware.
Chat Functionality:
The chat_with_waifu() function uses the g4f chat completions API to generate text responses.
The conversation history is updated with each user query and waifu response.
Image Generation:
The generate_waifu_image() function uses the g4f image generation API to create images based on the user's description (or a default prompt).
User Interaction:
In the main() function, the user can chat with the waifu or request an image by typing phrases like generate image of a waifu in a garden.
To exit, the user can type "exit" or "quit."
Error Handling:
The script gracefully handles errors, such as API timeouts or invalid inputs, and provides fallback responses.
Features
Dynamic Name Generation:
Every session assigns a random anime-style name to the waifu for a personalized experience.
Image Generation:
Users can request images by describing their desired scene or relying on a default anime theme.
Multiple Providers:
The RetryProvider ensures continuity by switching to alternative providers if one fails.
Infinite Conversations:
The conversation history ensures context is preserved across long chats.
How to Run
Install the g4f library:
bash
pip install g4f[all]
Set up the required cookies for providers like Bing or Google (as shown in the script).
Run the script:
bash
python ai_waifu_engine.py
Chat with your waifu, or request images with phrases like:
code
generate image of a waifu in a futuristic city
Exit by typing:
code
exit
Sample Interaction
You: Hello! [Redacted Person]: Hi there! How can I brighten your day today? 🌸
You: Tell me a joke. [Redacted Person]: Why did the anime character bring a ladder to the bar? Because they heard the drinks were on the house! 😄
You: Generate image of a waifu in a cherry blossom garden. [Redacted Person]: Here you go! Click here to view the image.
You: Goodbye. [Redacted Person]: Goodbye! I'll miss you. 🌸
This script provides a great starting point for a fully functional AI waifu engine. You can further enhance it with features like voice output, memory persistence, or advanced emotion modeling! 🌟