ndurner commited on
Commit
c144d94
·
1 Parent(s): 26f4619

streaming chat, switch to conversation API

Browse files
Files changed (2) hide show
  1. app.py +23 -14
  2. llm.py +148 -184
app.py CHANGED
@@ -34,34 +34,43 @@ def process_values_js():
34
  def bot(message, history, aws_access, aws_secret, aws_token, system_prompt, temperature, max_tokens, model: str, region):
35
  try:
36
  llm = LLM.create_llm(model)
37
- body = llm.generate_body(message, history, system_prompt, temperature, max_tokens)
38
 
39
  config = Config(
40
- read_timeout=600,
41
- connect_timeout=30,
42
- retries={
43
  'max_attempts': 10,
44
  'mode': 'adaptive'
45
  }
46
  )
47
 
48
  sess = boto3.Session(
49
- aws_access_key_id=aws_access,
50
- aws_secret_access_key=aws_secret,
51
- aws_session_token=aws_token,
52
- region_name=region)
53
  br = sess.client(service_name="bedrock-runtime", config = config)
54
 
55
- response = br.invoke_model(body=body, modelId=f"{model}",
56
- accept="application/json", contentType="application/json")
57
- response_body = json.loads(response.get('body').read())
58
- result = llm.read_response(response_body)
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  except Exception as e:
61
  raise gr.Error(f"Error: {str(e)}")
62
 
63
- return result
64
-
65
  def import_history(history, file):
66
  with open(file.name, mode="rb") as f:
67
  content = f.read()
 
34
  def bot(message, history, aws_access, aws_secret, aws_token, system_prompt, temperature, max_tokens, model: str, region):
35
  try:
36
  llm = LLM.create_llm(model)
37
+ messages = llm.generate_body(message, history)
38
 
39
  config = Config(
40
+ read_timeout = 600,
41
+ connect_timeout = 30,
42
+ retries = {
43
  'max_attempts': 10,
44
  'mode': 'adaptive'
45
  }
46
  )
47
 
48
  sess = boto3.Session(
49
+ aws_access_key_id = aws_access,
50
+ aws_secret_access_key = aws_secret,
51
+ aws_session_token = aws_token,
52
+ region_name = region)
53
  br = sess.client(service_name="bedrock-runtime", config = config)
54
 
55
+ response = br.converse_stream(
56
+ modelId = model,
57
+ messages = messages,
58
+ system = [{"text": system_prompt}],
59
+ inferenceConfig = {
60
+ "temperature": temperature,
61
+ "maxTokens": max_tokens,
62
+ }
63
+ )
64
+ response_stream = response.get('stream')
65
+
66
+ partial_response = ""
67
+ for chunk in llm.read_response(response_stream):
68
+ partial_response += chunk
69
+ yield partial_response
70
 
71
  except Exception as e:
72
  raise gr.Error(f"Error: {str(e)}")
73
 
 
 
74
  def import_history(history, file):
75
  with open(file.name, mode="rb") as f:
76
  content = f.read()
llm.py CHANGED
@@ -7,211 +7,175 @@ from doc2json import process_docx
7
  import fitz
8
  from PIL import Image
9
  import io
 
 
 
10
 
11
  # constants
12
  log_to_console = False
13
-
14
- def process_pdf_img(pdf_fn: str):
15
- pdf = fitz.open(pdf_fn)
16
- message_parts = []
17
-
18
- for page in pdf.pages():
19
- # Create a transformation matrix for rendering at the calculated scale
20
- mat = fitz.Matrix(0.6, 0.6)
21
-
22
- # Render the page to a pixmap
23
- pix = page.get_pixmap(matrix=mat, alpha=False)
24
-
25
- # Convert pixmap to PIL Image
26
- img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
27
-
28
- # Convert PIL Image to bytes
29
- img_byte_arr = io.BytesIO()
30
- img.save(img_byte_arr, format='PNG')
31
- img_byte_arr = img_byte_arr.getvalue()
32
-
33
- # Encode image to base64
34
- base64_encoded = base64.b64encode(img_byte_arr).decode('utf-8')
35
-
36
- # Append the message part
37
- message_parts.append({
38
- "type": "text",
39
- "text": f"Page {page.number} of file '{pdf_fn}'"
40
- })
41
- message_parts.append({"type": "image", "source": {"type": "base64",
42
- "media_type": "image/png",
43
- "data": base64_encoded}})
44
-
45
- pdf.close()
46
-
47
- return message_parts
48
-
49
- def encode_image(image_data):
50
- """Generates a prefix for image base64 data in the required format for the
51
- four known image formats: png, jpeg, gif, and webp.
52
-
53
- Args:
54
- image_data: The image data, encoded in base64.
55
-
56
- Returns:
57
- An object encoding the image
58
- """
59
-
60
- # Get the first few bytes of the image data.
61
- magic_number = image_data[:4]
62
-
63
- # Check the magic number to determine the image type.
64
- if magic_number.startswith(b'\x89PNG'):
65
- image_type = 'png'
66
- elif magic_number.startswith(b'\xFF\xD8'):
67
- image_type = 'jpeg'
68
- elif magic_number.startswith(b'GIF89a'):
69
- image_type = 'gif'
70
- elif magic_number.startswith(b'RIFF'):
71
- if image_data[8:12] == b'WEBP':
72
- image_type = 'webp'
73
- else:
74
- # Unknown image type.
75
- raise Exception("Unknown image type")
76
- else:
77
- # Unknown image type.
78
- raise Exception("Unknown image type")
79
-
80
- return {"type": "base64",
81
- "media_type": "image/" + image_type,
82
- "data": base64.b64encode(image_data).decode('utf-8')}
83
-
84
- def encode_file(fn: str) -> list:
85
- user_msg_parts = []
86
-
87
- if fn.endswith(".docx"):
88
- user_msg_parts.append({"type": "text", "text": process_docx(fn)})
89
- elif fn.endswith(".pdf"):
90
- user_msg_parts.extend(process_pdf_img(fn))
91
- else:
92
- with open(fn, mode="rb") as f:
93
- content = f.read()
94
-
95
- isImage = False
96
- if isinstance(content, bytes):
97
- try:
98
- # try to add as image
99
- content = encode_image(content)
100
- isImage = True
101
- except:
102
- # not an image, try text
103
- content = content.decode('utf-8', 'replace')
104
- else:
105
- content = str(content)
106
-
107
- if isImage:
108
- user_msg_parts.append({"type": "image",
109
- "source": content})
110
- else:
111
- fname = os.path.basename(fn)
112
- user_msg_parts.append({"type": "text", "text": f"``` {fname}\n{content}\n```"})
113
-
114
- return user_msg_parts
115
 
116
  LLMClass = TypeVar('LLMClass', bound='LLM')
117
- class LLM(ABC):
118
- @abstractmethod
119
- def generate_body(message, history, system_prompt, temperature, max_tokens):
120
- pass
121
-
122
- @abstractmethod
123
- def read_response(message, history, system_prompt, temperature, max_tokens):
124
- pass
125
 
 
126
  @staticmethod
127
  def create_llm(model: str) -> Type[LLMClass]:
128
- if model.startswith("anthropic.claude"):
129
- return Claude()
130
- elif model.startswith("mistral."):
131
- return Mistral()
132
- else:
133
- raise ValueError(f"Unsupported model: {model}")
 
134
 
135
- class Claude(LLM):
136
- @staticmethod
137
- def generate_body(message, history, system_prompt, temperature, max_tokens):
138
- history_claude_format = []
139
- user_msg_parts = []
140
  for human, assi in history:
141
  if human:
142
- if type(human) is tuple:
143
- user_msg_parts.extend(encode_file(human[0]))
 
144
  else:
145
- user_msg_parts.append({"type": "text", "text": human})
146
-
147
- if assi is not None:
148
- if user_msg_parts:
149
- history_claude_format.append({"role": "user", "content": user_msg_parts})
150
  user_msg_parts = []
151
 
152
- history_claude_format.append({"role": "assistant", "content": assi})
 
 
 
153
 
154
- if message['text']:
155
- user_msg_parts.append({"type": "text", "text": message['text']})
156
- if message['files']:
157
- for file in message['files']:
158
- user_msg_parts.extend(encode_file(file['path']))
159
- history_claude_format.append({"role": "user", "content": user_msg_parts})
160
  user_msg_parts = []
161
-
162
- if log_to_console:
163
- print(f"br_prompt: {str(history_claude_format)}")
164
-
165
- body = json.dumps({
166
- "anthropic_version": "bedrock-2023-05-31",
167
- "system": system_prompt,
168
- "max_tokens": max_tokens,
169
- "temperature": temperature,
170
- "messages": history_claude_format
171
- })
172
 
173
- return body
174
-
175
- @staticmethod
176
- def read_response(response_body) -> Type[str]:
177
- return response_body.get('content')[0].get('text')
178
-
179
- class Mistral(LLM):
180
- @staticmethod
181
- def generate_body(message, history, system_prompt, temperature, max_tokens):
182
- prompt = "<s>"
183
- for human, assi in history:
184
- if human:
185
- if type(human) is tuple:
186
- prompt += f"[INST] {encode_file(human[0])} [/INST]"
187
- else:
188
- prompt += f"[INST] {human} [/INST]"
189
 
190
- if assi is not None:
191
- prompt += f"{assi}</s>"
 
 
 
192
 
193
- if message['text'] or message['files']:
194
- prompt += "[INST] "
 
195
 
196
- if message['text']:
197
- prompt += message['text']
198
- if message['files']:
199
- for file in message['files']:
200
- prompt += f"{encode_file(file['path'])}\n"
201
-
202
- prompt += " [/INST]"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
 
204
- if log_to_console:
205
- print(f"br_prompt: {str(prompt)}")
206
 
207
- body = json.dumps({
208
- "prompt": prompt,
209
- "max_tokens": max_tokens,
210
- "temperature": temperature,
211
- })
212
 
213
- return body
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
- @staticmethod
216
- def read_response(response_body) -> Type[str]:
217
- return response_body.get('outputs')[0].get('text')
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  import fitz
8
  from PIL import Image
9
  import io
10
+ import boto3
11
+ from botocore.config import Config
12
+ import re
13
 
14
  # constants
15
  log_to_console = False
16
+ use_document_message_type = False # AWS document message type usage
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  LLMClass = TypeVar('LLMClass', bound='LLM')
 
 
 
 
 
 
 
 
19
 
20
+ class LLM:
21
  @staticmethod
22
  def create_llm(model: str) -> Type[LLMClass]:
23
+ return LLM()
24
+
25
+ def generate_body(self, message, history):
26
+ messages = []
27
+
28
+ # AWS API requires strict user, assi, user, ... sequence
29
+ lastTypeHuman = False
30
 
 
 
 
 
 
31
  for human, assi in history:
32
  if human:
33
+ if lastTypeHuman:
34
+ last_msg = messages.pop()
35
+ user_msg_parts = last_msg["content"]
36
  else:
 
 
 
 
 
37
  user_msg_parts = []
38
 
39
+ if isinstance(human, tuple):
40
+ user_msg_parts.extend(self._process_file(human[0]))
41
+ else:
42
+ user_msg_parts.extend([{"text": human}])
43
 
44
+ messages.append({"role": "user", "content": user_msg_parts})
45
+ lastTypeHuman = True
46
+ if assi:
47
+ messages.append({"role": "assistant", "content": [{"text": assi}]})
48
+ lastTypeHuman = False
49
+
50
  user_msg_parts = []
51
+ if message.text:
52
+ user_msg_parts.append({"text": message.text})
53
+ if message.files:
54
+ for file in message.files:
55
+ user_msg_parts.extend(self._process_file(file.path))
 
 
 
 
 
 
56
 
57
+ if user_msg_parts:
58
+ messages.append({"role": "user", "content": user_msg_parts})
59
+
60
+ return messages
 
 
 
 
 
 
 
 
 
 
 
 
61
 
62
+ def _process_file(self, file_path):
63
+ if use_document_message_type and self._is_supported_document_type(file_path):
64
+ return [self._create_document_message(file_path)]
65
+ else:
66
+ return self._encode_file(file_path)
67
 
68
+ def _is_supported_document_type(self, file_path):
69
+ supported_extensions = ['.pdf', '.csv', '.doc', '.docx', '.xls', '.xlsx', '.html', '.txt', '.md']
70
+ return os.path.splitext(file_path)[1].lower() in supported_extensions
71
 
72
+ def _create_document_message(self, file_path):
73
+ with open(file_path, 'rb') as file:
74
+ file_content = file.read()
75
+
76
+ file_name = re.sub(r'[^a-zA-Z0-9\s\-\(\)\[\]]', '', os.path.basename(file_path))[:200].strip() or "unnamed_file"
77
+ file_extension = os.path.splitext(file_path)[1][1:] # Remove the dot
78
+
79
+ return {
80
+ "document": {
81
+ "name": file_name,
82
+ "format": file_extension,
83
+ "source": {
84
+ "bytes": file_content
85
+ }
86
+ }
87
+ }
88
+
89
+ def _encode_file(self, fn: str) -> list:
90
+ if fn.endswith(".docx"):
91
+ return [{"text": process_docx(fn)}]
92
+ elif fn.endswith(".pdf"):
93
+ return self._process_pdf_img(fn)
94
+ else:
95
+ with open(fn, mode="rb") as f:
96
+ content = f.read()
97
+
98
+ if isinstance(content, bytes):
99
+ try:
100
+ # try to add as image
101
+ image_data = self._encode_image(content)
102
+ return [{"image": image_data}]
103
+ except:
104
+ # not an image, try text
105
+ content = content.decode('utf-8', 'replace')
106
+ else:
107
+ content = str(content)
108
 
109
+ fname = os.path.basename(fn)
110
+ return [{"text": f"``` {fname}\n{content}\n```"}]
111
 
112
+ def _process_pdf_img(self, pdf_fn: str):
113
+ pdf = fitz.open(pdf_fn)
114
+ message_parts = []
 
 
115
 
116
+ for page in pdf.pages():
117
+ # Create a transformation matrix for rendering at the calculated scale
118
+ mat = fitz.Matrix(0.6, 0.6)
119
+
120
+ # Render the page to a pixmap
121
+ pix = page.get_pixmap(matrix=mat, alpha=False)
122
+
123
+ # Convert pixmap to PIL Image
124
+ img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
125
+
126
+ # Convert PIL Image to bytes
127
+ img_byte_arr = io.BytesIO()
128
+ img.save(img_byte_arr, format='PNG')
129
+ img_byte_arr = img_byte_arr.getvalue()
130
+
131
+ # Append the message parts
132
+ message_parts.append({"text": f"Page {page.number} of file '{pdf_fn}'"})
133
+ message_parts.append({"image": {
134
+ "format": "png",
135
+ "source": {"bytes": img_byte_arr}
136
+ }})
137
+
138
+ pdf.close()
139
+
140
+ return message_parts
141
+
142
+ def _encode_image(self, image_data):
143
+ # Get the first few bytes of the image data.
144
+ magic_number = image_data[:4]
145
+
146
+ # Check the magic number to determine the image type.
147
+ if magic_number.startswith(b'\x89PNG'):
148
+ image_type = 'png'
149
+ elif magic_number.startswith(b'\xFF\xD8'):
150
+ image_type = 'jpeg'
151
+ elif magic_number.startswith(b'GIF89a'):
152
+ image_type = 'gif'
153
+ elif magic_number.startswith(b'RIFF'):
154
+ if image_data[8:12] == b'WEBP':
155
+ image_type = 'webp'
156
+ else:
157
+ # Unknown image type.
158
+ raise Exception("Unknown image type")
159
+ else:
160
+ # Unknown image type.
161
+ raise Exception("Unknown image type")
162
 
163
+ return {
164
+ "format": image_type,
165
+ "source": {"bytes": image_data}
166
+ }
167
+
168
+ def read_response(self, response_stream):
169
+ for event in response_stream:
170
+ if 'contentBlockDelta' in event:
171
+ yield event['contentBlockDelta']['delta']['text']
172
+ if 'messageStop' in event:
173
+ if log_to_console:
174
+ print(f"\nStop reason: {event['messageStop']['stopReason']}")
175
+ if 'metadata' in event:
176
+ metadata = event['metadata']
177
+ if 'usage' in metadata and log_to_console:
178
+ print("\nToken usage:")
179
+ print(f"Input tokens: {metadata['usage']['inputTokens']}")
180
+ print(f"Output tokens: {metadata['usage']['outputTokens']}")
181
+ print(f"Total tokens: {metadata['usage']['totalTokens']}")