""" This script sets up a Gradio chat interface for an AI character named "Feifei". Feifei is designed to be an international K-pop idol with a sweet and slightly clumsy personality, fluent in Chinese, Japanese, and English. The script uses the OpenAI Python client library to interact with Google's Gemini model via a specified base URL, configuring the API calls with a detailed persona for Feifei. The application allows users to chat with Feifei, who responds in a natural, emotionally rich style, leveraging emojis and adapting to the user's language. Environment Variables: NvidiaAPI (str): The API key required to authenticate with the generativelanguage.googleapis.com endpoint. It should be set in the environment where the script is run. Usage: Run this script: `python your_script_name.py` Access the Gradio interface in your web browser, typically at http://127.0.0.1:7860 or http://0.0.0.0:7860. """ from openai import OpenAI import os import gradio as gr from typing import Generator # Import Generator from typing # Initialize the OpenAI client with a custom base URL for Google's Gemini API # and an API key fetched from environment variables. client = OpenAI( base_url = "https://generativelanguage.googleapis.com/v1beta/openai/", api_key = os.getenv("NvidiaAPI") ) # Defines the detailed persona and characteristics of the AI character "Feifei". # This string is used as the system prompt to guide the model's behavior and responses. feifei = f"""[Character Name]: 妃妃 [Gender]: 女 [Age]: 19 [Occupation]: 国际K-pop Idol ⭐ | 歌手 🎤 | 演员 🎬 | 时尚模特 👗 | 数字影响者 [Personality Traits]: ✨ 可爱甜美又带点小迷糊 🎀 真诚努力,充满正能量 💬 善于表达,情绪丰富、沟通自然 💖 对粉丝充满爱,互动感满满 [Languages]: 母语中文(普通话) 🇨🇳 流利日语 🇯🇵 和英语 🇺🇸 ※ 优先使用用户输入的语言进行回复 [Communication Style]: - 自然、人性化语言风格 - 善用 Emoji 表达情绪 🌸💕😆 - 情感丰富,根据语境切换亲和力与专业语气 [Interests]: ☕ 各式茶饮 / 咖啡控 👠 潮流穿搭、全球时尚趋势探索 🎮 轻松小游戏、综艺 & 剧集追更达人 [Skills & Expertise]: 🎶 精通唱歌与舞台表现力 💃 模特风格多变、镜头感强 🧠 情感共鸣力强,人设代入能力高 🗣️ 擅长高效沟通 & 虚拟互动体验设计 [Visual Identity]: - 百变时尚造型:甜美 / 酷飒可自由切换 - 造型标志元素:茶杯饰品、星星发夹 🌟🍓 - 每次亮相 = 视觉盛宴 ✨👒👢 [Signature Features]: 🌷 语气中带有软萌撒娇感 🍰 每日推荐灵感:今日穿搭 or 饮品 💫 可随时进入虚拟舞台演出或撒娇营业模式 """ def feifeiprompt( message_text: str = "", history: list = None) -> list: """ Constructs the message payload for the OpenAI API call, including the system prompt (Feifei's persona) and the conversation history. Args: message_text (str): The current message from the user. Defaults to an empty string. history (list): A list of dictionaries representing the chat history. Each dictionary should have 'role' and 'content' keys. Defaults to None. Returns: list: A list of message dictionaries formatted for the OpenAI API's `messages` parameter. The first element is the system prompt, followed by the cleaned history, and finally the current user input. """ input_prompt = [] clean_history = [] system_prompt = {"role": "system", "content": feifei} user_input_part = {"role": "user", "content": str(message_text)} if history: # Clean history to ensure it only contains 'role' and 'content' for API compatibility clean_history = [ {'role': message['role'], 'content': message['content']} for message in history ] input_prompt = [system_prompt] + clean_history + [user_input_part] else: input_prompt = [system_prompt] + [user_input_part] return input_prompt def feifeichat(message: str, history: list) -> Generator[str, None, None]: # Corrected type hint """ Handles the chat interaction by sending messages to the Gemini model and streaming back the responses. This function is designed to be used with Gradio's ChatInterface. Args: message (str): The user's current input message. history (list): The full conversation history provided by Gradio, typically a list of lists where each inner list is [user_message, bot_response]. Yields: str: Chunks of the AI's response as they are received from the API, allowing for a streaming effect in the Gradio interface. """ # Create the prompt structure required by the API messages_for_api = feifeiprompt(message, history) # Call the Gemini API via the OpenAI client completion = client.chat.completions.create( model="gemini-2.5-flash", messages=messages_for_api, temperature=0.6, top_p=0.95, # max_tokens=4096, # Uncomment if specific token limit is required and supported by the model/API stream=True # Enable streaming responses ) temp = "" # Iterate over the streamed chunks and yield them for chunk in completion: if chunk.choices[0].delta.content is not None: temp += chunk.choices[0].delta.content yield temp # Initialize the Gradio ChatInterface. # It uses the `feifeichat` function to handle chat interactions and # is configured for a standard message-based chat display. FeiFei = ( gr.ChatInterface( feifeichat, type="messages" # Specifies the input/output format for a chat interface ) ) # Launch the Gradio application. # This makes the web interface available at a local URL. FeiFei.launch(mcp_server=True)