binary1ne commited on
Commit
876196b
·
verified ·
1 Parent(s): cec5e38

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +69 -50
app.py CHANGED
@@ -1,64 +1,83 @@
 
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
 
26
- messages.append({"role": "user", "content": message})
 
 
 
 
 
27
 
28
- response = ""
 
 
29
 
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
 
39
- response += token
40
- yield response
 
 
 
41
 
 
 
 
 
 
 
 
 
 
42
 
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
- ],
60
- )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
  demo.launch()
 
 
 
 
1
+ import requests
2
  import gradio as gr
3
+ import logging
4
+ import nest_asyncio
5
+ from typing import Any
6
+ from llama_index.tools.mcp import BasicMCPClient, McpToolSpec
7
 
8
+ # Logging Setup
9
+ logger = logging.getLogger(__name__)
 
 
10
 
11
+ # Default Hugging Face model and API URL
12
+ DEFAULT_HUGGINGFACE_MODEL = "Eric1227/dolphin-2.5-mixtral-8x7b-MLX-6bit" # Use your desired model
13
+ HUGGINGFACE_API_URL = "https://api-inference.huggingface.co/models/{model_name}"
14
+ API_KEY = "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" # Your Hugging Face API key
15
 
16
+ # Apply nest_asyncio to handle event loops in Jupyter (if using it)
17
+ nest_asyncio.apply()
 
 
 
 
 
 
 
18
 
19
+ # Remote MCP Client Setup (Update with your remote MCP server URL)
20
+ REMOTE_MCP_URL = "http://your.remote.mcp.server/sse"
21
+ mcp_client = BasicMCPClient(REMOTE_MCP_URL)
22
+ mcp_tool = McpToolSpec(client=mcp_client)
 
23
 
24
+ # Function to call Hugging Face Inference API
25
+ def query_huggingface_api(prompt: str, model_name: str = DEFAULT_HUGGINGFACE_MODEL) -> str:
26
+ headers = {
27
+ "Authorization": f"Bearer {API_KEY}",
28
+ "Content-Type": "application/json"
29
+ }
30
 
31
+ payload = {
32
+ "inputs": prompt
33
+ }
34
 
35
+ response = requests.post(HUGGINGFACE_API_URL.format(model_name=model_name),
36
+ headers=headers, json=payload)
 
 
 
 
 
 
37
 
38
+ if response.status_code == 200:
39
+ return response.json()[0]["generated_text"]
40
+ else:
41
+ logger.error(f"Error from Hugging Face API: {response.status_code}, {response.text}")
42
+ return "Error processing your request."
43
 
44
+ # Function to interact with MCP (for processing or augmenting responses)
45
+ def interact_with_mcp(input_text: str) -> str:
46
+ # Send input to MCP (modify as per your MCP interaction logic)
47
+ try:
48
+ response = mcp_client.query(input_text) # Assuming `query` method is used for MCP interaction
49
+ return response['response'] # Adjust based on your MCP response format
50
+ except Exception as e:
51
+ logger.error(f"Error interacting with MCP: {str(e)}")
52
+ return "MCP interaction failed."
53
 
54
+ # Create the function that Gradio will call for inference
55
+ def generate_response_with_mcp(prompt: str) -> str:
56
+ # First, interact with the Hugging Face model
57
+ model_response = query_huggingface_api(prompt)
58
+
59
+ # Then, send that response to the MCP system for additional processing
60
+ mcp_response = interact_with_mcp(model_response)
61
+
62
+ # Combine Hugging Face and MCP responses (or modify logic as needed)
63
+ return f"Model Response: {model_response}\n\nMCP Response: {mcp_response}"
 
 
 
 
 
 
 
 
64
 
65
+ # Set up Gradio interface
66
+ def launch_gradio_interface():
67
+ with gr.Blocks() as demo:
68
+ gr.Markdown("### Hugging Face Model + Remote MCP Integration")
69
+
70
+ with gr.Row():
71
+ prompt_input = gr.Textbox(label="Enter Your Prompt", placeholder="Type something here...")
72
+ output_text = gr.Textbox(label="Generated Response")
73
+
74
+ # Button to submit the prompt
75
+ submit_btn = gr.Button("Generate Response")
76
+
77
+ # Link the button action to the function
78
+ submit_btn.click(generate_response_with_mcp, inputs=prompt_input, outputs=output_text)
79
 
 
80
  demo.launch()
81
+
82
+ if __name__ == "__main__":
83
+ launch_gradio_interface()