zakerytclarke commited on
Commit
d6dc06a
·
verified ·
1 Parent(s): fde5fa2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +249 -0
app.py CHANGED
@@ -6,6 +6,255 @@ import requests
6
  import time
7
  from langsmith import traceable
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  def log_time(func):
10
  def wrapper(*args, **kwargs):
11
  start_time = time.time()
 
6
  import time
7
  from langsmith import traceable
8
 
9
+
10
+ ##### Begin Library Code
11
+ from transformers import pipeline
12
+ import torch
13
+ from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
14
+ import numpy as np
15
+ from sklearn.metrics.pairwise import cosine_similarity
16
+ from pydantic import BaseModel
17
+ from typing import List, Optional
18
+ from tqdm import tqdm
19
+ import re
20
+ import os
21
+
22
+
23
+ class TeapotAISettings(BaseModel):
24
+ """
25
+ Pydantic settings model for TeapotAI configuration.
26
+
27
+ Attributes:
28
+ use_rag (bool): Whether to use RAG (Retrieve and Generate).
29
+ rag_num_results (int): Number of top documents to retrieve based on similarity.
30
+ rag_similarity_threshold (float): Similarity threshold for document relevance.
31
+ verbose (bool): Whether to print verbose updates.
32
+ log_level (str): The log level for the application (e.g., "info", "debug").
33
+ """
34
+ use_rag: bool = True # Whether to use RAG (Retrieve and Generate)
35
+ rag_num_results: int = 3 # Number of top documents to retrieve based on similarity
36
+ rag_similarity_threshold: float = 0.5 # Similarity threshold for document relevance
37
+ verbose: bool = True # Whether to print verbose updates
38
+ log_level: str = "info" # Log level setting (e.g., 'info', 'debug')
39
+
40
+
41
+ class TeapotAI:
42
+ """
43
+ TeapotAI class that interacts with a language model for text generation and retrieval tasks.
44
+
45
+ Attributes:
46
+ model (str): The model identifier.
47
+ model_revision (Optional[str]): The revision/version of the model.
48
+ api_key (Optional[str]): API key for accessing the model (if required).
49
+ settings (TeapotAISettings): Configuration settings for the AI instance.
50
+ generator (callable): The pipeline for text generation.
51
+ embedding_model (callable): The pipeline for feature extraction (document embeddings).
52
+ documents (List[str]): List of documents for retrieval.
53
+ document_embeddings (np.ndarray): Embeddings for the provided documents.
54
+ """
55
+
56
+ def __init__(self, model_revision: Optional[str] = None, api_key: Optional[str] = None,
57
+ documents: List[str] = [], settings: TeapotAISettings = TeapotAISettings()):
58
+ """
59
+ Initializes the TeapotAI class with optional model_revision and api_key.
60
+
61
+ Parameters:
62
+ model_revision (Optional[str]): The revision/version of the model to use.
63
+ api_key (Optional[str]): The API key for accessing the model if needed.
64
+ documents (List[str]): A list of documents for retrieval. Defaults to an empty list.
65
+ settings (TeapotAISettings): The settings configuration (defaults to TeapotAISettings()).
66
+ """
67
+ self.model = "teapotai/teapotllm"
68
+ self.model_revision = model_revision
69
+ self.api_key = api_key
70
+ self.settings = settings
71
+
72
+ if self.settings.verbose:
73
+ print(""" _____ _ _ ___ __o__ _;;
74
+ |_ _|__ __ _ _ __ ___ | |_ / \ |_ _| __ /-___-\__/ /
75
+ | |/ _ \/ _` | '_ \ / _ \| __| / _ \ | | ( | |__/
76
+ | | __/ (_| | |_) | (_) | |_ / ___ \ | | \_|~~~~~~~|
77
+ |_|\___|\__,_| .__/ \___/ \__/ /_/ \_\___| \_____/
78
+ |_| """)
79
+
80
+ if self.settings.verbose:
81
+ print(f"Loading Model: {self.model} Revision: {self.model_revision or 'Latest'}")
82
+
83
+ # self.generator = pipeline("text2text-generation", model=self.model, revision=self.model_revision) if model_revision else pipeline("text2text-generation", model=self.model)
84
+
85
+ self.tokenizer = AutoTokenizer.from_pretrained(self.model)
86
+ model = AutoModelForSeq2SeqLM.from_pretrained(self.model)
87
+ model.eval()
88
+
89
+ # Quantization settings
90
+ quantization_dtype = torch.qint8 # or torch.float16
91
+ quantization_config = torch.quantization.get_default_qconfig('fbgemm') # or 'onednn'
92
+
93
+ self.quantized_model = torch.quantization.quantize_dynamic(
94
+ model, {torch.nn.Linear}, dtype=quantization_dtype
95
+ )
96
+
97
+ self.documents = documents
98
+
99
+ if self.settings.use_rag and self.documents:
100
+ self.embedding_model = pipeline("feature-extraction", model="teapotai/teapotembedding")
101
+ self.document_embeddings = self._generate_document_embeddings(self.documents)
102
+
103
+ def _generate_document_embeddings(self, documents: List[str]) -> np.ndarray:
104
+ """
105
+ Generate embeddings for the provided documents using the embedding model.
106
+
107
+ Parameters:
108
+ documents (List[str]): A list of document strings to generate embeddings for.
109
+
110
+ Returns:
111
+ np.ndarray: A NumPy array of document embeddings.
112
+ """
113
+ embeddings = []
114
+
115
+ if self.settings.verbose:
116
+ print("Generating embeddings for documents...")
117
+ for doc in tqdm(documents, desc="Document Embedding", unit="doc"):
118
+ embeddings.append(self.embedding_model(doc)[0][0])
119
+ else:
120
+ for doc in documents:
121
+ embeddings.append(self.embedding_model(doc)[0][0])
122
+
123
+ return np.array(embeddings)
124
+
125
+ def rag(self, query: str) -> List[str]:
126
+ """
127
+ Perform RAG (Retrieve and Generate) by finding the most relevant documents based on cosine similarity.
128
+
129
+ Parameters:
130
+ query (str): The query string to find relevant documents for.
131
+
132
+ Returns:
133
+ List[str]: A list of the top N most relevant documents.
134
+ """
135
+ if not self.settings.use_rag or not self.documents:
136
+ return []
137
+
138
+ query_embedding = self.embedding_model(query)[0][0]
139
+ similarities = cosine_similarity([query_embedding], self.document_embeddings)[0]
140
+
141
+ filtered_indices = [i for i, similarity in enumerate(similarities) if similarity >= self.settings.rag_similarity_threshold]
142
+ top_n_indices = sorted(filtered_indices, key=lambda i: similarities[i], reverse=True)[:self.settings.rag_num_results]
143
+
144
+ return [self.documents[i] for i in top_n_indices]
145
+
146
+ def generate(self, input_text: str) -> str:
147
+ """
148
+ Generate text based on the input string using the teapotllm model.
149
+
150
+ Parameters:
151
+ input_text (str): The text prompt to generate a response for.
152
+
153
+ Returns:
154
+ str: The generated output from the model.
155
+ """
156
+
157
+ inputs = self.tokenizer(input_text, return_tensors="pt", padding=True, truncation=True)
158
+
159
+
160
+ with torch.no_grad():
161
+ outputs = self.quantized_model.generate(inputs["input_ids"], max_length=512)
162
+
163
+
164
+ result = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
165
+
166
+
167
+ if self.settings.log_level == "debug":
168
+ print(input_text)
169
+ print(result)
170
+
171
+ return result
172
+
173
+ def query(self, query: str, context: str = "") -> str:
174
+ """
175
+ Handle a query and context, using RAG if no context is provided, and return a generated response.
176
+
177
+ Parameters:
178
+ query (str): The query string to be answered.
179
+ context (str): The context to guide the response. Defaults to an empty string.
180
+
181
+ Returns:
182
+ str: The generated response based on the input query and context.
183
+ """
184
+ if self.settings.use_rag and not context:
185
+ context = "\n".join(self.rag(query)) # Perform RAG if no context is provided
186
+
187
+ input_text = f"Context: {context}\nQuery: {query}"
188
+ return self.generate(input_text)
189
+
190
+ def chat(self, conversation_history: List[dict]) -> str:
191
+ """
192
+ Engage in a chat by taking a list of previous messages and generating a response.
193
+
194
+ Parameters:
195
+ conversation_history (List[dict]): A list of previous messages, each containing 'content'.
196
+
197
+ Returns:
198
+ str: The generated response based on the conversation history.
199
+ """
200
+ chat_history = "".join([message['content'] + "\n" for message in conversation_history])
201
+
202
+ if self.settings.use_rag:
203
+ context_documents = self.rag(chat_history) # Perform RAG on the conversation history
204
+ context = "\n".join(context_documents)
205
+ chat_history = f"Context: {context}\n" + chat_history
206
+
207
+ return self.generate(chat_history + "\n" + "agent:")
208
+
209
+ def extract(self, class_annotation: BaseModel, query: str = "", context: str = "") -> BaseModel:
210
+ """
211
+ Extract fields from a Pydantic class annotation by querying and processing each field.
212
+
213
+ Parameters:
214
+ class_annotation (BaseModel): The Pydantic class to extract fields from.
215
+ query (str): The query string to guide the extraction. Defaults to an empty string.
216
+ context (str): Optional context for the query.
217
+
218
+ Returns:
219
+ BaseModel: An instance of the provided Pydantic class with extracted field values.
220
+ """
221
+ if self.settings.use_rag:
222
+ context_documents = self.rag(query)
223
+ context = "\n".join(context_documents) + context
224
+
225
+ output = {}
226
+ for field_name, field in class_annotation.__fields__.items():
227
+ type_annotation = field.annotation
228
+ description = field.description
229
+ description_annotation = f"({description})" if description else ""
230
+
231
+ result = self.query(f"Extract the field {field_name} {description_annotation} to a {type_annotation}", context=context)
232
+
233
+ # Process result based on field type
234
+ if type_annotation == bool:
235
+ parsed_result = (
236
+ True if re.search(r'\b(yes|true)\b', result, re.IGNORECASE)
237
+ else (False if re.search(r'\b(no|false)\b', result, re.IGNORECASE) else None)
238
+ )
239
+ elif type_annotation in [int, float]:
240
+ parsed_result = re.sub(r'[^0-9.]', '', result)
241
+ if parsed_result:
242
+ try:
243
+ parsed_result = type_annotation(parsed_result)
244
+ except Exception:
245
+ parsed_result = None
246
+ else:
247
+ parsed_result = None
248
+ elif type_annotation == str:
249
+ parsed_result = result.strip()
250
+ else:
251
+ raise ValueError(f"Unsupported type annotation: {type_annotation}")
252
+
253
+ output[field_name] = parsed_result
254
+
255
+ return class_annotation(**output)
256
+
257
+ ##### End Library Code
258
  def log_time(func):
259
  def wrapper(*args, **kwargs):
260
  start_time = time.time()