Views
No views yet
1from huggingface_hub import InferenceClient
2import numpy as np
3
4def get_HF_embeddings(text, api_key, model, mean_pool=True, l2_normalize=True):
5 """
6 Fetches embeddings from HuggingFace serverless Inference API for a single string or a list of strings.
7 Args:
8 text (str or list): Input text or list of texts.
9 api_key (str): HuggingFace API key.
10 model (str): Model repo.
11 mean_pool (bool): If True, mean-pool the output.
12 l2_normalize (bool): If True, L2 normalize the output.
13 Returns:
14 np.ndarray: Embedding(s) as numpy array(s).
15 """
16 client = InferenceClient(api_key=api_key)
17 if isinstance(text, str):
18 texts = [text]
19 single_input = True
20 else:
21 texts = text
22 single_input = False
23
24 result = client.feature_extraction(
25 text=texts,
26 model=model
27 )
28
29 if mean_pool:
30 embeddings = [np.mean(r, axis=0) for r in result]
31 if l2_normalize:
32 embeddings = [
33 e / np.linalg.norm(e) if np.linalg.norm(e) > 0 else e for e in embeddings]
34 else:
35 embeddings = [r for r in result]
36
37 if single_input:
38 return embeddings[0]
39 return np.array(embeddings)task parameter for different application needs:
retrieval.query – For query embeddings in asymmetric retrievalretrieval.passage – For passage embeddings in asymmetric retrievalseparation – For clustering and re-rankingclassification – For classification taskstext-matching – For symmetric similarity tasks (e.g., STS)transformers or the sentence-transformers library.sentence-transformers library.1from sentence_transformers import SentenceTransformer
2
3model = SentenceTransformer("Sajjad313/jina-embedding-v3", trust_remote_code=True)
4
5# Task-specific usage: Retrieval query embedding
6query_embedding = model.encode(
7 ["What is the weather like in Berlin today?"],
8 task="retrieval.query"
9)1from transformers import AutoTokenizer, AutoModel
2
3tokenizer = AutoTokenizer.from_pretrained("jinaai/jina-embeddings-v3")
4model = AutoModel.from_pretrained("jinaai/jina-embeddings-v3")
5
6inputs = tokenizer(
7 "What is the weather like in Berlin today?",
8 return_tensors="pt", padding=True, truncation=True
9)
10outputs = model(**inputs)
11embedding = outputs.last_hidden_state[:, 0] # CLS token embeddingNote: Using thetransformerslibrary gives you basic access to the model’s output, but for full task-specific capabilities, usesentence-transformers.