alchemine commited on
Commit
efd850d
·
1 Parent(s): dac5492

feat: update API

Browse files
Files changed (1) hide show
  1. app.py +84 -35
app.py CHANGED
@@ -1,62 +1,111 @@
 
 
 
 
 
 
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
 
 
1
+ import logging
2
+ from os import getenv
3
+ from uuid import uuid4
4
+
5
+ import requests
6
+ from requests import Response, RequestException
7
  import gradio as gr
 
8
 
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ INFLO_AGENT_API_URL = f"{getenv('INFLO_AGENT_API_HOST')}:{getenv('INFLO_AGENT_API_PORT')}"
13
+ DEFAULT_HEADERS = {"accept": "application/json", "Content-Type": "application/json"}
14
+ DEFAULT_USER_ID = str(uuid4())
15
+
16
+ def get_request_log(
17
+ url: str, headers: dict, json: dict, response: Response | None = None
18
+ ) -> dict:
19
+ """Get the request log.
20
+
21
+ Args:
22
+ url (str): The URL of the API.
23
+ headers (dict): The headers of the API.
24
+ json (dict): The JSON data of the API.
25
+ response (Response): The response of the API.
26
+
27
+ Returns:
28
+ dict: The request log.
29
+ """
30
+ log = dict(
31
+ url=url,
32
+ headers=headers,
33
+ json=json,
34
+ reproduction_code=f"import requests; requests.post(url='{url}', headers={headers}, json={json})",
35
+ )
36
+
37
+ if response:
38
+ log.update(
39
+ response=dict(status_code=response.status_code, json=response.json())
40
+ )
41
+
42
+ return log
43
+
44
+
45
+ def safe_request(url: str, json: dict, headers: dict = DEFAULT_HEADERS) -> dict:
46
+ """Requests with validation.
47
+
48
+ Args:
49
+ url (str): The URL of the API.
50
+ json (dict): The JSON data of the API.
51
+ headers (dict): The headers of the API.
52
+
53
+ Returns:
54
+ Response: The response of the API.
55
+ """
56
+ try:
57
+ response = requests.post(url=url, headers=headers, json=json)
58
+ response.raise_for_status()
59
+ log = get_request_log(url, headers, json)
60
+ logger.info(log)
61
+ return response.json()
62
+ except RequestException:
63
+ log = get_request_log(url, headers, json)
64
+ logger.error(log, exc_info=True)
65
+ raise
66
 
67
 
68
  def respond(
69
  message,
70
  history: list[tuple[str, str]],
71
+ user_id: str = DEFAULT_USER_ID,
 
 
 
72
  ):
73
+ messages = []
 
74
  for val in history:
75
  if val[0]:
76
  messages.append({"role": "user", "content": val[0]})
77
  if val[1]:
78
  messages.append({"role": "assistant", "content": val[1]})
 
79
  messages.append({"role": "user", "content": message})
80
 
81
+ result = safe_request(
82
+ url=f"{INFLO_AGENT_API_URL}/chat/completions",
83
+ json={"query": message, "user_id": user_id},
84
+ )
85
+ response, context = result["response"], result["context"]
86
+ yield response
87
 
88
+ # response = ""
89
+ # for message in client.chat_completion(
90
+ # messages,
91
+ # max_tokens=max_tokens,
92
+ # stream=True,
93
+ # temperature=temperature,
94
+ # top_p=top_p,
95
+ # ):
96
+ # token = message.choices[0].delta.content
97
+ # response += token
98
+ # yield response
99
 
 
 
100
 
101
+
102
 
103
  """
104
  For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
105
  """
106
  demo = gr.ChatInterface(
107
  respond,
108
+ additional_inputs=[gr.Textbox(value=DEFAULT_USER_ID, label="User ID")],
 
 
 
 
 
 
 
 
 
 
 
109
  )
110
 
111