ChatBot / app.py
Eddyhzd
test
3b313c8
raw
history blame
2.14 kB
import gradio as gr
from openai import OpenAI
import os
import json
import requests
cle_api = os.environ.get("CLE_API_MISTRAL")
MCP_URL = "https://hackathoncra-gradio-mcp.hf.space/gradio_api/mcp/"
# Initialisation du client Mistral (API compatible OpenAI)
clientLLM = OpenAI(api_key=cle_api, base_url="https://api.mistral.ai/v1")
def call_mcp(payload: dict):
"""Appel simple au serveur MCP Gradio"""
headers = {"Content-Type": "application/json"}
response = requests.post(MCP_URL, data=json.dumps(payload), headers=headers)
print(response.json())
response.raise_for_status()
return response.json()
# Chatbot avec Mistral + MCP
def chatbot(message, history):
# Préparer l’historique pour Mistral
messages = []
for user_msg, bot_msg in history:
messages.append({"role": "user", "content": user_msg})
messages.append({"role": "assistant", "content": bot_msg})
messages.append({"role": "user", "content": message})
# Appel API Mistral
response = clientLLM.chat.completions.create(
model="mistral-small-latest",
messages=messages
)
bot_reply = response.choices[0].message.content.strip()
# Vérifier si la réponse contient un JSON MCP
try:
mcp_payload = json.loads(bot_reply)
mcp_result = call_mcp(mcp_payload)
bot_reply = f"Réponse via MCP:\n{json.dumps(mcp_result, indent=2)}"
except json.JSONDecodeError:
# Pas de JSON MCP, réponse normale
pass
history.append(("Vous: " + message, "Bot: " + bot_reply))
return history, history
def call_mcp(payload: dict):
"""
Fonction générique pour interroger le serveur MCP hébergé sur Gradio.
"""
headers = {"Content-Type": "application/json"}
response = requests.post(MCP_URL, data=json.dumps(payload), headers=headers)
response.raise_for_status()
return response.json()
with gr.Blocks() as demo:
chatbot_ui = gr.Chatbot(label="ChatBot")
msg = gr.Textbox(placeholder="Écrivez un message...")
msg.submit(chatbot, [msg, chatbot_ui], [chatbot_ui, chatbot_ui])
demo.launch(debug=True)