Chris4K commited on
Commit
120d4a1
·
verified ·
1 Parent(s): bbb822d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -108
app.py CHANGED
@@ -1,65 +1,22 @@
1
  import streamlit as st
2
  import os
3
  import requests
4
-
 
 
5
  from PIL import Image
6
- #from pydub.playback import Audio
7
  from pydub import AudioSegment
8
-
9
  import IPython
10
  import soundfile as sf
 
 
11
 
12
- def play_audio(audio):
13
- sf.write("speech_converted.wav", audio.numpy(), samplerate=16000)
14
- return IPython.display.Audio("speech_converted.wav")
15
-
16
-
17
- # From transformers import BertModel, BertTokenizer
18
- from transformers import load_tool
19
- #from transformers import HfAgent, load_tool
20
 
21
- import torch
22
- from transformers import AutoModelForCausalLM, AutoTokenizer, Agent, LocalAgent
23
-
24
- # checkpoint = "THUDM/agentlm-7b"
25
- # model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.bfloat16)
26
- # tokenizer = AutoTokenizer.from_pretrained(checkpoint)
27
-
28
- # agent = LocalAgent(model, tokenizer)
29
- # agent.run("Draw me a picture of rivers and lakes.")
30
-
31
- # print(agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!"))
32
-
33
- # Load tools
34
- random_character_tool = load_tool("Chris4K/random-character-tool")
35
- text_generation_tool = load_tool("Chris4K/text-generation-tool")
36
- #sentiment_tool = load_tool("Chris4K/sentiment-tool")
37
- token_counter_tool = load_tool("Chris4K/token-counter-tool")
38
- most_downloaded_model = load_tool("Chris4K/most-downloaded-model")
39
- #rag_tool = load_tool("Chris4K/rag-tool")
40
- word_counter_tool = load_tool("Chris4K/word-counter-tool")
41
- sentence_counter_tool = load_tool("Chris4K/sentence-counter-tool")
42
- emojify_text_tool = load_tool("Chris4K/EmojifyTextTool")
43
- namedEntityRecognitionTool = load_tool("Chris4K/NamedEntityRecognitionTool")
44
- textDownloadTool = load_tool("Chris4K/TextDownloadTool")
45
- sourcecode_retriever_tool = load_tool("Chris4K/source-code-retriever-tool")
46
-
47
- text_to_image = load_tool("Chris4K/text-to-image")
48
- text_to_video = load_tool("Chris4K/text-to-video")
49
- image_transformation = load_tool("Chris4K/image-transformation")
50
- latent_upscaler_tool = load_tool("Chris4K/latent-upscaler-tool")
51
-
52
- tools = [random_character_tool, text_generation_tool,
53
- #sentiment_tool,
54
- token_counter_tool, most_downloaded_model,
55
- word_counter_tool, sentence_counter_tool, emojify_text_tool , namedEntityRecognitionTool, sourcecode_retriever_tool,
56
- text_to_image, text_to_video, image_transformation, latent_upscaler_tool ]
57
-
58
- # Define the custom HfAgent class with token and input_params for e.g max_new_token
59
  class CustomHfAgent(Agent):
60
- def __init__(
61
- self, url_endpoint, token=os.environ['HF_token'], chat_prompt_template=None, run_prompt_template=None, additional_tools=None, input_params=None
62
- ):
63
  super().__init__(
64
  chat_prompt_template=chat_prompt_template,
65
  run_prompt_template=run_prompt_template,
@@ -71,17 +28,12 @@ class CustomHfAgent(Agent):
71
 
72
  def generate_one(self, prompt, stop):
73
  headers = {"Authorization": self.token}
74
- # Use the value from input_params or a default value if not provided
75
  max_new_tokens = self.input_params.get("max_new_tokens", 192)
76
-
77
- # Set padding and truncation options
78
  parameters = {"max_new_tokens": max_new_tokens, "return_full_text": False, "stop": stop, "padding": True, "truncation": True}
79
-
80
  inputs = {
81
  "inputs": prompt,
82
  "parameters": parameters,
83
  }
84
-
85
  response = requests.post(self.url_endpoint, json=inputs, headers=headers)
86
 
87
  if response.status_code == 429:
@@ -92,79 +44,67 @@ class CustomHfAgent(Agent):
92
  raise ValueError(f"Errors {inputs} {response.status_code}: {response.json()}")
93
  print(response)
94
  result = response.json()[0]["generated_text"]
95
- # Inference API returns the stop sequence
96
  for stop_seq in stop:
97
  if result.endswith(stop_seq):
98
  return result[: -len(stop_seq)]
99
  return result
100
 
101
- #################
102
- #################
 
 
 
 
 
 
 
 
 
 
 
103
  # Define the callback function to handle the form submission
104
- def handle_submission():
105
- selected_tools = [tools[idx] for idx, checkbox in enumerate(tool_checkboxes) if checkbox]
106
- print(selected_tools)
107
- # Initialize the agent
108
  agent = CustomHfAgent(
109
- #url_endpoint="https://api-inference.huggingface.co/models/bigcode/starcoder",
110
- # codellama/CodeLlama-7b-Instruct-hf # WizardLM/WizardCoder-Python-34B-V1.0 # deepseek-ai/deepseek-coder-6.7b-instruct # mistralai/Mixtral-8x7B-v0.1 # bigscience/bloom
111
- url_endpoint="https://api-inference.huggingface.co/models/bigcode/starcoder", #
112
  token=os.environ['HF_token'],
113
  additional_tools=selected_tools,
114
  input_params={"max_new_tokens": 192},
115
  )
116
- #agent.tools = selected_tools
117
 
118
  response = agent.run(user_message)
119
 
120
  print("Agent Response\n {}".format(response))
121
-
122
- return response
123
 
124
- # Add the callback function to the Streamlit app
125
- #if submit_button:
126
- # handle_submission()
127
- #################
128
 
129
- ######
130
-
131
  st.title("Hugging Face Agent and tools")
132
 
133
- # Initialize chat history
134
  if "messages" not in st.session_state:
135
  st.session_state.messages = []
136
 
137
- # Display chat messages from history on app rerun
138
  for message in st.session_state.messages:
139
  with st.chat_message(message["role"]):
140
  st.markdown(message["content"])
141
-
142
- # Checkboxes for the tools to be used by the agent
143
- tool_checkboxes = [st.checkbox(f"{tool.name} --- {tool.description} ") for tool in tools]
144
 
145
- # Display a welcome message
 
146
  with st.chat_message("assistant"):
147
  st.markdown("Hello there! How can I assist you today?")
148
-
149
- # Input field for the user's message
150
- #user_message = st.chat_input("Enter message")
151
 
152
- # React to user input
153
  if user_message := st.chat_input("Enter message"):
154
- # Display user message in chat message container
155
  st.chat_message("user").markdown(user_message)
156
- # Add user message to chat history
157
  st.session_state.messages.append({"role": "user", "content": user_message})
158
 
159
- response = handle_submission()
160
- # Display the agent's response
161
- ## https://docs.streamlit.io/library/cheatsheet
162
  with st.chat_message("assistant"):
163
  if response is None:
164
  st.warning("The agent's response is None. Please try again.")
 
 
165
  elif isinstance(response, Image.Image):
166
  st.image(response)
167
- # elif hasattr(response, 'audio'):
168
  elif "audio" in str(response):
169
  audio_data = base64.b64decode(response.split(",")[1])
170
  audio = AudioSegment.from_file(io.BytesIO(audio_data))
@@ -175,23 +115,7 @@ if user_message := st.chat_input("Enter message"):
175
  st.markdown(response)
176
  elif isinstance(response, int):
177
  st.markdown(response)
178
- #elif "text" in response:
179
- # st.markdown(response)
180
  else:
181
  st.warning("Unrecognized response type. Please try again.")
182
 
183
-
184
- # Display assistant response in chat message container
185
- #with st.chat_message("assistant"):
186
- # st.markdown(response)
187
- # Add assistant response to chat history
188
  st.session_state.messages.append({"role": "assistant", "content": response})
189
-
190
-
191
- # Submit button
192
- #submit_button = st.button("Submit")
193
-
194
-
195
-
196
-
197
-
 
1
  import streamlit as st
2
  import os
3
  import requests
4
+ import base64
5
+ import io
6
+ import time
7
  from PIL import Image
 
8
  from pydub import AudioSegment
 
9
  import IPython
10
  import soundfile as sf
11
+ from transformers import load_tool, Agent
12
+ import torch
13
 
14
+ class ToolLoader:
15
+ def __init__(self, tool_names):
16
+ self.tools = [load_tool(tool_name) for tool_name in tool_names]
 
 
 
 
 
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  class CustomHfAgent(Agent):
19
+ def __init__(self, url_endpoint, token, chat_prompt_template=None, run_prompt_template=None, additional_tools=None, input_params=None):
 
 
20
  super().__init__(
21
  chat_prompt_template=chat_prompt_template,
22
  run_prompt_template=run_prompt_template,
 
28
 
29
  def generate_one(self, prompt, stop):
30
  headers = {"Authorization": self.token}
 
31
  max_new_tokens = self.input_params.get("max_new_tokens", 192)
 
 
32
  parameters = {"max_new_tokens": max_new_tokens, "return_full_text": False, "stop": stop, "padding": True, "truncation": True}
 
33
  inputs = {
34
  "inputs": prompt,
35
  "parameters": parameters,
36
  }
 
37
  response = requests.post(self.url_endpoint, json=inputs, headers=headers)
38
 
39
  if response.status_code == 429:
 
44
  raise ValueError(f"Errors {inputs} {response.status_code}: {response.json()}")
45
  print(response)
46
  result = response.json()[0]["generated_text"]
 
47
  for stop_seq in stop:
48
  if result.endswith(stop_seq):
49
  return result[: -len(stop_seq)]
50
  return result
51
 
52
+ def load_tools(tool_names):
53
+ return [load_tool(tool_name) for tool_name in tool_names]
54
+
55
+ # Define the tool names to load
56
+ tool_names = [
57
+ "Chris4K/random-character-tool",
58
+ "Chris4K/text-generation-tool",
59
+ # Add other tool names as needed
60
+ ]
61
+
62
+ # Create tool loader instance
63
+ tool_loader = ToolLoader(tool_names)
64
+
65
  # Define the callback function to handle the form submission
66
+ def handle_submission(user_message, selected_tools):
 
 
 
67
  agent = CustomHfAgent(
68
+ url_endpoint="https://api-inference.huggingface.co/models/bigcode/starcoder",
 
 
69
  token=os.environ['HF_token'],
70
  additional_tools=selected_tools,
71
  input_params={"max_new_tokens": 192},
72
  )
 
73
 
74
  response = agent.run(user_message)
75
 
76
  print("Agent Response\n {}".format(response))
 
 
77
 
78
+ return response
 
 
 
79
 
 
 
80
  st.title("Hugging Face Agent and tools")
81
 
 
82
  if "messages" not in st.session_state:
83
  st.session_state.messages = []
84
 
 
85
  for message in st.session_state.messages:
86
  with st.chat_message(message["role"]):
87
  st.markdown(message["content"])
 
 
 
88
 
89
+ tool_checkboxes = [st.checkbox(f"{tool.name} --- {tool.description} ") for tool in tool_loader.tools]
90
+
91
  with st.chat_message("assistant"):
92
  st.markdown("Hello there! How can I assist you today?")
 
 
 
93
 
 
94
  if user_message := st.chat_input("Enter message"):
 
95
  st.chat_message("user").markdown(user_message)
 
96
  st.session_state.messages.append({"role": "user", "content": user_message})
97
 
98
+ selected_tools = [tool_loader.tools[idx] for idx, checkbox in enumerate(tool_checkboxes) if checkbox]
99
+ response = handle_submission(user_message, selected_tools)
100
+
101
  with st.chat_message("assistant"):
102
  if response is None:
103
  st.warning("The agent's response is None. Please try again.")
104
+ elif "emojified_text" in response:
105
+ st.markdown(f"Emojified Text: {response['emojified_text']}")
106
  elif isinstance(response, Image.Image):
107
  st.image(response)
 
108
  elif "audio" in str(response):
109
  audio_data = base64.b64decode(response.split(",")[1])
110
  audio = AudioSegment.from_file(io.BytesIO(audio_data))
 
115
  st.markdown(response)
116
  elif isinstance(response, int):
117
  st.markdown(response)
 
 
118
  else:
119
  st.warning("Unrecognized response type. Please try again.")
120
 
 
 
 
 
 
121
  st.session_state.messages.append({"role": "assistant", "content": response})