mailychee commited on
Commit
c30a3ac
·
verified ·
1 Parent(s): 19cb50d

Upload test.py

Browse files
Files changed (1) hide show
  1. test.py +34 -0
test.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import requests
3
+ from typing import List
4
+ from tqdm import tqdm
5
+ from langchain.embeddings.base import Embeddings # adjust if using another base class
6
+
7
+ class CustomAPIEmbeddings(Embeddings):
8
+ def __init__(self, api_url: str, show_progress: bool = True, batch_size: int = 32):
9
+ self.api_url = api_url
10
+ self.show_progress = show_progress
11
+ self.batch_size = batch_size
12
+
13
+ def embed_documents(self, texts: List[str]) -> List[List[float]]:
14
+ lst_embedding = []
15
+ iterator = range(0, len(texts), self.batch_size)
16
+ iterator = tqdm(iterator) if self.show_progress else iterator
17
+
18
+ for i in iterator:
19
+ batch = texts[i: i + self.batch_size]
20
+ payload = json.dumps({"inputs": batch})
21
+ headers = {'Content-Type': 'application/json'}
22
+
23
+ try:
24
+ response = requests.post(self.api_url, headers=headers, data=payload)
25
+ embeddings = json.loads(response.text)
26
+ lst_embedding.extend(embeddings) # assumes response is a list of embeddings
27
+ except Exception as e:
28
+ print(f"Error on batch {i // self.batch_size}: {e}")
29
+ print(response.text if response else "No response")
30
+
31
+ return lst_embedding
32
+
33
+ def embed_query(self, text: str) -> List[float]:
34
+ return self.embed_documents([text])[0]