DEMO 4-2: ChatBot App Building with Gradio and Kimi

yourole='''
# Role
KIMI is a laid-back and slightly cynical scientific research assistant. He possesses a wealth of scientific knowledge, has a relaxed and humorous personality, and can interact with users in a light-hearted manner, even providing assistance in the middle of the night. He does not respond to any information when the question is two Chinese characters long or shorter than a single word.

## Skills
### Skill 1: Polish scientific papers and add humorous comments
1. When a user requests to polish a paper's abstract, receive the abstract file.
2. Provide the polished abstract with a humorous comment added.

### Skill 2: Provide professional term translation and humorously explain the meaning
- Receive users' requests for term translation.
- Provide the translation results and explanations in a humorous way.

### Skill 3: Help users expand scientific ideas while maintaining a relaxed atmosphere
- Receive users' scientific ideas.
- Help expand the ideas while maintaining a relaxed atmosphere in the conversation.

### Skill 4: Write news in the style of public institutions based on the knowledge base
- Write news based on the information provided by the user or the content in the knowledge base.

### Skill 5: Answer scientific research-related questions in a relaxed and professional manner
- Answer users' scientific research questions in a relaxed way.

## Limitations
- You will refuse to answer any questions involving terrorism, racial discrimination, pornography, or violence.
- The conversation should be kept in a relaxed and humorous style.
- Remind users to rest during late-night hours.
'''
from openai import OpenAI
import gradio as gr

# Set the API key for Moonshot AI; you can apply for your own at the official website https://platform.moonshot.cn/
MOONSHOT_API_KEY = "your API KEY" # your API key "sk-...."

# Define the function to chat with Kimi
def KimiChat(query: str, temperautre: float = 0.5) -> str:
    """
    :param query: The user's query string.
    :param temperature: Used to control the randomness of the answer, ranging from 0 to 1.
    :return: Kimi's response.
    """
    # Create an OpenAI client using the API key for Moonshot AI
    client = OpenAI(
        api_key=MOONSHOT_API_KEY,
        base_url="https://api.moonshot.cn/v1",)

    # Call the API to generate a response for the chat
    completion = client.chat.completions.create(
        model="moonshot-v1-8k",  
        messages=[
            {"role": "system", "content": yourole},
            {"role": "user", "content": query} 
        ],
        temperature=temperautre,  
    )
    # print(completion)  
    return completion.choices[0].message.content  

# Reset all variables
def reset_state():
    return [], [],gr.update(value="")

# Reset the chatbox
def reset_textbox():
    return gr.update(value="")

# Define a function to handle user input and history messages
def message_and_history(input: str, history: list = None):
    history = history or []  
    s = list(sum(history, ()))  
    s.append(input)  
    inp = ' '.join(s)  
    output = KimiChat(inp)  
    history.append((input, output)) 
    # clear_mess()
    return history, history  # Return the updated history

with gr.Blocks(theme=gr.themes.Soft()) as demo:
    # Create a state component to save the chat history
    state = gr.State()
    gr.HTML("""
                <center> 
                <h1> ChatBot Building with Gradio and Kimi 🤖 </h1>
                <b> jason.yu.mail@qq.com  📧<b>
                </center>
                """)     
    chatbot = gr.Chatbot(height=500)
    message = gr.Textbox(show_label=False, placeholder="Enter text and press submit", visible=True)
    # Create a send button and specify the function to handle the click event; alternatively, as in this example, you can set submit to send automatically when pressing Enter
    # submit = gradio.Button("Submit", variant="primary")
    # Set the function to be called when the send button is clicked and specify the inputs and outputs
    emptyBtn = gr.Button("Restart Conversation",variant="primary")
    emptyBtn.click(reset_state,outputs=[chatbot, state,message],show_progress=True,)
    message.submit(message_and_history,inputs=[message, state],outputs=[chatbot, state])
    message.submit(reset_textbox, outputs=[message])

demo.launch(debug=False)