Chris4K commited on
Commit
6bab521
·
verified ·
1 Parent(s): d6555d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +41 -136
app.py CHANGED
@@ -2,95 +2,40 @@ import streamlit as st
2
  import os
3
  import requests
4
 
5
-
6
- #from transformers import BertModel, BertTokenizer
7
  from transformers import HfAgent, load_tool
8
 
9
  import torch
10
  from transformers import AutoModelForCausalLM, AutoTokenizer, Agent, LocalAgent
11
 
 
 
 
12
 
13
- #checkpoint = "THUDM/agentlm-7b"
14
- #model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.bfloat16)
15
- #tokenizer = AutoTokenizer.from_pretrained(checkpoint)
16
-
17
- #agent = LocalAgent(model, tokenizer)
18
- #agent.run("Draw me a picture of rivers and lakes.")
19
 
20
- #print(agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!"))
21
 
22
  # Load tools
23
  controlnet_transformer = load_tool("huggingface-tools/text-to-image")
24
  upscaler = load_tool("diffusers/latent-upscaler-tool")
25
 
26
- tools = [controlnet_transformer, upscaler ]
27
-
28
-
29
- ############ HfAgent
30
- from huggingface_hub import login
31
- #Do this before HfAgent() and it should work
32
-
33
- #from huggingface_hub import login
34
- # load tools
35
- from transformers.tools import HfAgent
36
- from transformers.tools import Agent
37
- #import textract
38
- #from utils import logging
39
- import time
40
-
41
- from huggingface_hub import HfFolder, hf_hub_download, list_spaces
42
-
43
-
44
 
 
45
 
 
46
  class CustomHfAgent(Agent):
47
- """
48
- Agent that uses an inference endpoint to generate code.
49
-
50
- Args:
51
- url_endpoint (`str`):
52
- The name of the url endpoint to use.
53
- token (`str`, *optional*):
54
- The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated when
55
- running `huggingface-cli login` (stored in `~/.huggingface`).
56
- chat_prompt_template (`str`, *optional*):
57
- Pass along your own prompt if you want to override the default template for the `chat` method. Can be the
58
- actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
59
- `chat_prompt_template.txt` in this repo in this case.
60
- run_prompt_template (`str`, *optional*):
61
- Pass along your own prompt if you want to override the default template for the `run` method. Can be the
62
- actual prompt template or a repo ID (on the Hugging Face Hub). The prompt should be in a file named
63
- `run_prompt_template.txt` in this repo in this case.
64
- additional_tools ([`Tool`], list of tools or dictionary with tool values, *optional*):
65
- Any additional tools to include on top of the default ones. If you pass along a tool with the same name as
66
- one of the default tools, that default tool will be overridden.
67
-
68
- Example:
69
-
70
- ```py
71
- from transformers import HfAgent
72
-
73
- agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
74
- agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!")
75
- ```
76
- """
77
-
78
  def __init__(
79
  self, url_endpoint, token=os.environ['HF_token'], chat_prompt_template=None, run_prompt_template=None, additional_tools=None
80
  ):
81
- # super()._init_(self, url_endpoint, token=None, chat_prompt_template=None, run_prompt_template=None, additional_tools=None)
82
- self.url_endpoint = url_endpoint
83
- if token is None:
84
- self.token = f"Bearer {HfFolder().get_token()}"
85
- elif token.startswith("Bearer") or token.startswith("Basic"):
86
- self.token = token
87
- else:
88
- self.token = f"Bearer {token}"
89
  super().__init__(
90
  chat_prompt_template=chat_prompt_template,
91
  run_prompt_template=run_prompt_template,
92
  additional_tools=additional_tools,
93
  )
 
 
94
 
95
  def generate_one(self, prompt, stop):
96
  headers = {"Authorization": self.token}
@@ -98,7 +43,6 @@ class CustomHfAgent(Agent):
98
  "inputs": prompt,
99
  "parameters": {"max_new_tokens": 192, "return_full_text": False, "stop": stop},
100
  }
101
- print(inputs)
102
  response = requests.post(self.url_endpoint, json=inputs, headers=headers)
103
  if response.status_code == 429:
104
  print("Getting rate-limited, waiting a tiny bit before trying again.")
@@ -114,52 +58,6 @@ class CustomHfAgent(Agent):
114
  return result[: -len(stop_seq)]
115
  return result
116
 
117
-
118
-
119
-
120
- # create agent
121
- #agent = HfAgent(API_URL)
122
-
123
- #print(agent)
124
- # instruct agent
125
-
126
-
127
- # Use CustomHfAgent in your code
128
- agent = CustomHfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder")
129
- print("-----")
130
- print(agent.token)
131
-
132
- print("-----")
133
- agent.token = os.environ['HF_token']
134
- print("-----")
135
- print(agent.token)
136
-
137
- print("-----")
138
-
139
- #agent.token = "Bearer xxx"
140
- #print(agent.token)
141
- #agent.run("Answer the following question", question ="what is the capitol of the usa?", context="The capitol of the usa is London")
142
- agent.chat("Draw me a picture of rivers and lakes")
143
-
144
- #agent.chat("Transform the picture so that there is a rock in there")
145
-
146
- #result = agent.generate_one("What is the capitol of the usa.", stop=["your_stop_sequence"])
147
- #print(result)
148
-
149
- #agent.run("Show me an image of a horse")
150
-
151
-
152
-
153
-
154
- #####
155
-
156
-
157
-
158
-
159
- # Define the model and tokenizer
160
- #model = BertModel.from_pretrained('bert-base-uncased')
161
- #tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
162
-
163
  # Create the Streamlit app
164
  st.title("Hugging Face Agent")
165
 
@@ -170,34 +68,41 @@ message_input = st.text_input("Enter your message:", "")
170
  tool_checkboxes = [st.checkbox(f"Use {tool}") for tool in tools]
171
 
172
  # Submit button
173
- #submit_button = st.button("Submit")
174
-
175
 
176
  # Define the callback function to handle the form submission
177
  def handle_submission():
178
  # Get the user's message and the selected tools
179
- message = message_input
180
- selected_tools = [tool for tool, checkbox in zip(tools, tool_checkboxes) if checkbox]
181
-
182
- # Initialize the agent with the selected tools
183
- #agent = HfAgent("https://api-inference.huggingface.co/models/bigcode/starcoder", additional_tools=tools)
184
- #agent = HfAgent("https://api-inference.huggingface.co/models/OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5", additional_tools=tools)
185
- #agent = HfAgent("https://api-inference.huggingface.co/models/THUDM/agentlm-7b", additional_tools=tools)
186
-
187
 
188
- # agent.config.tokenizer = tokenizer
189
- # agent.config.tools = selected_tools
190
 
191
- # Process the user's message
192
- # inputs = tokenizer.encode_plus(message, add_special_tokens=True, return_tensors="pt")
193
- # outputs = agent(inputs['input_ids'], attention_mask=inputs['attention_mask'])
194
 
195
  # Display the agent's response
196
- response = agent.run(message)
197
- st.text(f"{response:.4f}")
198
- return "done"
199
-
200
-
201
- # Add the callback function to the Streamlit app
202
- submit_button = st.button("Submit", on_click=handle_submission)
203
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import os
3
  import requests
4
 
5
+ # From transformers import BertModel, BertTokenizer
 
6
  from transformers import HfAgent, load_tool
7
 
8
  import torch
9
  from transformers import AutoModelForCausalLM, AutoTokenizer, Agent, LocalAgent
10
 
11
+ # checkpoint = "THUDM/agentlm-7b"
12
+ # model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto", torch_dtype=torch.bfloat16)
13
+ # tokenizer = AutoTokenizer.from_pretrained(checkpoint)
14
 
15
+ # agent = LocalAgent(model, tokenizer)
16
+ # agent.run("Draw me a picture of rivers and lakes.")
 
 
 
 
17
 
18
+ # print(agent.run("Is the following `text` (in Spanish) positive or negative?", text="¡Este es un API muy agradable!"))
19
 
20
  # Load tools
21
  controlnet_transformer = load_tool("huggingface-tools/text-to-image")
22
  upscaler = load_tool("diffusers/latent-upscaler-tool")
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
 
25
+ tools = [controlnet_transformer, upscaler]
26
 
27
+ # Define the custom HfAgent class
28
  class CustomHfAgent(Agent):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  def __init__(
30
  self, url_endpoint, token=os.environ['HF_token'], chat_prompt_template=None, run_prompt_template=None, additional_tools=None
31
  ):
 
 
 
 
 
 
 
 
32
  super().__init__(
33
  chat_prompt_template=chat_prompt_template,
34
  run_prompt_template=run_prompt_template,
35
  additional_tools=additional_tools,
36
  )
37
+ self.url_endpoint = url_endpoint
38
+ self.token = token
39
 
40
  def generate_one(self, prompt, stop):
41
  headers = {"Authorization": self.token}
 
43
  "inputs": prompt,
44
  "parameters": {"max_new_tokens": 192, "return_full_text": False, "stop": stop},
45
  }
 
46
  response = requests.post(self.url_endpoint, json=inputs, headers=headers)
47
  if response.status_code == 429:
48
  print("Getting rate-limited, waiting a tiny bit before trying again.")
 
58
  return result[: -len(stop_seq)]
59
  return result
60
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61
  # Create the Streamlit app
62
  st.title("Hugging Face Agent")
63
 
 
68
  tool_checkboxes = [st.checkbox(f"Use {tool}") for tool in tools]
69
 
70
  # Submit button
71
+ submit_button = st.button("Submit")
 
72
 
73
  # Define the callback function to handle the form submission
74
  def handle_submission():
75
  # Get the user's message and the selected tools
76
+ message = message_input.value
77
+ selected_tools = [tool for tool, checkbox in tool_checkboxes]
 
 
 
 
 
 
78
 
79
+ # Initialize the agent
80
+ agent = CustomHfAgent(url_endpoint="https://api-inference.huggingface.co/models/bigcode/starcoder", token=os.environ['HF_token'])
81
 
82
+ # Run the agent with the user's message and selected tools
83
+ response = agent.run(message, tools=selected_tools)
 
84
 
85
  # Display the agent's response
86
+ # Display the agent's response
87
+ if response.startswith("Image:"):
88
+ # Display the image response
89
+ image_data = base64.b64decode(response.split(",")[1])
90
+ img = Image.open(io.BytesIO(image_data))
91
+ st.image(img)
92
+ else:
93
+ # Display the text response
94
+ st.write(response)
95
+
96
+ # Add a button to trigger the agent to respond again
97
+ st.button("Ask Again")
98
+
99
+ # Define a callback function to handle the button click
100
+ def ask_again():
101
+ # Reset the message input field
102
+ message_input.value = ""
103
+
104
+ # Run the agent again with an empty message
105
+ agent.run("")
106
+
107
+ # Add the callback function to the button
108
+ st.button("Ask Again").do(ask_again)