Spaces:
Sleeping
Sleeping
Create custom-llama3.py
Browse files- custom-llama3.py +126 -0
custom-llama3.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
from langchain_core.callbacks.manager import CallbackManagerForLLMRun
|
| 3 |
+
from langchain_core.language_models.llms import LLM
|
| 4 |
+
import json
|
| 5 |
+
import requests
|
| 6 |
+
|
| 7 |
+
class CustomLlama3(LLM):
|
| 8 |
+
url: str = "https://api-inference.huggingface.co/models/meta-llama/Meta-Llama-3-8B-Instruct"
|
| 9 |
+
bearer_token: str
|
| 10 |
+
max_new_tokens: int = 512
|
| 11 |
+
top_p: float = 0.9
|
| 12 |
+
temperature: float = 0.7
|
| 13 |
+
|
| 14 |
+
def _call(
|
| 15 |
+
self,
|
| 16 |
+
prompt: str,
|
| 17 |
+
stop: Optional[List[str]] = None,
|
| 18 |
+
run_manager: Optional[CallbackManagerForLLMRun] = None,
|
| 19 |
+
**kwargs: Any,
|
| 20 |
+
) -> str:
|
| 21 |
+
if stop is not None:
|
| 22 |
+
raise ValueError("stop kwargs are not permitted.")
|
| 23 |
+
json_body = {
|
| 24 |
+
"inputs": prompt,
|
| 25 |
+
"parameters": {"max_new_tokens":self.max_new_tokens, "top_p":self.top_p, "temperature":self.temperature}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
data = json.dumps(json_body)
|
| 29 |
+
headers = {
|
| 30 |
+
'Content-Type': 'application/json',
|
| 31 |
+
'Authorization': f'Bearer {self.bearer_token}'
|
| 32 |
+
}
|
| 33 |
+
response = requests.request("POST", self.url, headers=headers, data=data)
|
| 34 |
+
response.raise_for_status()
|
| 35 |
+
try:
|
| 36 |
+
result=json.loads(response.content.decode("utf-8"))[0]['generated_text']
|
| 37 |
+
target_substring = '<|end_header_id|>'
|
| 38 |
+
substring_length = len(target_substring)
|
| 39 |
+
last_occurrence_index = result.rfind(target_substring)
|
| 40 |
+
if last_occurrence_index != -1:
|
| 41 |
+
return result[last_occurrence_index + substring_length:].strip()
|
| 42 |
+
except:
|
| 43 |
+
return response
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def _identifying_params(self) -> Dict[str, Any]:
|
| 47 |
+
"""Return a dictionary of identifying parameters."""
|
| 48 |
+
return {"llmUrl": self.url}
|
| 49 |
+
|
| 50 |
+
@property
|
| 51 |
+
def _llm_type(self) -> str:
|
| 52 |
+
return "CustomLlama3"
|
| 53 |
+
|
| 54 |
+
###########
|
| 55 |
+
|
| 56 |
+
from langchain_core.prompts import PromptTemplate
|
| 57 |
+
|
| 58 |
+
prompt = PromptTemplate(
|
| 59 |
+
template="""<|begin_of_text|><|start_header_id|>system<|end_header_id|> You are a grader assessing relevance
|
| 60 |
+
of a retrieved document to a user question. If the document contains keywords related to the user question,
|
| 61 |
+
grade it as relevant. It does not need to be a stringent test. The goal is to filter out erroneous retrievals. \n
|
| 62 |
+
Give a binary score 'yes' or 'no' score to indicate whether the document is relevant to the question. \n
|
| 63 |
+
Provide the binary score as a JSON with a single key 'score' and no premable or explanation.
|
| 64 |
+
<|eot_id|><|start_header_id|>user<|end_header_id|>
|
| 65 |
+
Here is the retrieved document: \n\n {document} \n\n
|
| 66 |
+
Here is the user question: {question} \n <|eot_id|><|start_header_id|>assistant<|end_header_id|>
|
| 67 |
+
""",
|
| 68 |
+
input_variables=["question", "document"],
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
##########
|
| 72 |
+
|
| 73 |
+
from google.colab import userdata
|
| 74 |
+
|
| 75 |
+
remote_llm = CustomLlama3(bearer_token = userdata.get('HF_TOKEN'))
|
| 76 |
+
|
| 77 |
+
retrieval_grader = prompt | remote_llm
|
| 78 |
+
|
| 79 |
+
# Example usage
|
| 80 |
+
question = "What are the health benefits of apples?"
|
| 81 |
+
document = "Apples are rich in vitamins and fiber."
|
| 82 |
+
|
| 83 |
+
result = retrieval_grader.invoke({
|
| 84 |
+
"question": question,
|
| 85 |
+
"document": document
|
| 86 |
+
})
|
| 87 |
+
|
| 88 |
+
print(result)
|
| 89 |
+
|
| 90 |
+
###########
|
| 91 |
+
|
| 92 |
+
from langchain_community.document_loaders import WebBaseLoader
|
| 93 |
+
from langchain_community.vectorstores import Chroma
|
| 94 |
+
from langchain_community.embeddings.sentence_transformer import SentenceTransformerEmbeddings
|
| 95 |
+
from langchain_text_splitters import RecursiveCharacterTextSplitter
|
| 96 |
+
|
| 97 |
+
urls = [
|
| 98 |
+
"https://lilianweng.github.io/posts/2023-06-23-agent/",
|
| 99 |
+
"https://lilianweng.github.io/posts/2023-03-15-prompt-engineering/",
|
| 100 |
+
"https://lilianweng.github.io/posts/2023-10-25-adv-attack-llm/",
|
| 101 |
+
]
|
| 102 |
+
|
| 103 |
+
docs = [WebBaseLoader(url).load() for url in urls]
|
| 104 |
+
docs_list = [item for sublist in docs for item in sublist]
|
| 105 |
+
|
| 106 |
+
text_splitter = RecursiveCharacterTextSplitter.from_tiktoken_encoder(
|
| 107 |
+
chunk_size=250, chunk_overlap=0
|
| 108 |
+
)
|
| 109 |
+
doc_splits = text_splitter.split_documents(docs_list)
|
| 110 |
+
|
| 111 |
+
embedding_function = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")
|
| 112 |
+
|
| 113 |
+
# Add to vectorDB
|
| 114 |
+
vectorstore = Chroma.from_documents(
|
| 115 |
+
documents=doc_splits,
|
| 116 |
+
collection_name="rag-chroma",
|
| 117 |
+
embedding=embedding_function,
|
| 118 |
+
)
|
| 119 |
+
retriever = vectorstore.as_retriever()
|
| 120 |
+
|
| 121 |
+
question = "agent memory"
|
| 122 |
+
docs = retriever.invoke(question)
|
| 123 |
+
|
| 124 |
+
doc_txt = docs[3].page_content
|
| 125 |
+
print(retrieval_grader.invoke({"question": question, "document": doc_txt}))
|
| 126 |
+
|