File size: 5,646 Bytes
227a7da
 
 
 
23aeabb
227a7da
 
 
 
 
a70f9b1
227a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93a26b1
227a7da
 
 
 
 
93a26b1
227a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bfe948
227a7da
 
 
 
859bf4c
93a26b1
 
227a7da
 
 
 
 
 
 
 
93a26b1
 
227a7da
93a26b1
8bfe948
93a26b1
227a7da
93a26b1
227a7da
 
 
 
 
 
 
93a26b1
227a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
f439690
 
227a7da
 
 
 
 
 
 
 
9b1fd32
227a7da
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
from langchain_community.vectorstores import Chroma
from langchain_community.embeddings import HuggingFaceBgeEmbeddings

from langchain.docstore.document import Document
from transformers import AutoTokenizer
from config import *
import os
import torch
from predibase import Predibase, FinetuningConfig, DeploymentConfig
pb_auth  = os.environ.get("pb_token")
pb = Predibase(api_token='pb_8PhUywZ5VQCQFmGl8ZgfiQ')

if torch.cuda.is_available():
    device = "cuda"
else:
    device = "cpu"

os.environ['CURL_CA_BUNDLE'] = ""
embedding_int = HuggingFaceBgeEmbeddings(
    model_name=MODEL_NAME,
    encode_kwargs=ENCODE_KWARGS,
    query_instruction=QUERY_INSTRUCTION
)

embedding_sim = HuggingFaceBgeEmbeddings(
    model_name=MODEL_NAME,
    encode_kwargs=ENCODE_KWARGS,
    query_instruction='Retrieve semantically similar text.'
)

db = Chroma(persist_directory=PERSIST_DIRECTORY, embedding_function=embedding_int)
retriever = db.as_retriever(search_kwargs={"k": TOP_K})

lorax_client = pb.deployments.client("llama-3-8b-instruct") # Insert deployment name here

lora_weights_rec = REC_LORA_MODEL
lora_weights_exp = EXP_LORA_MODEL
hf_auth  = os.environ.get("hf_token")


tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL, token=hf_auth)


first_token = 'First'
second_token = 'Second'
# 获取token的ID
first_id = tokenizer.convert_tokens_to_ids(first_token)
second_id = tokenizer.convert_tokens_to_ids(second_token)


def generate_prompt(target_occupation, skill_gap, courses):
    return f"""
### Instruction:
"As an education expert, you have been provided with a target occupation, a skill gap, and information on two candidate courses. Your task is to determine which course better matches the target occupation and skill gap. Please respond with 'First' or 'Second' to indicate your recommendation.

### Input:
Target Occupation: {target_occupation}
Skill Gap: {skill_gap}
candidate courses: {courses}

### Response:
"""
'''
prompt_re = ChatPromptTemplate.from_template(template_re)
chain_re = (
    runnable
    | prompt_re
)
'''
def evaluate(
        prompt=None,
        temperature=0,
        top_p=1.0,
        top_k=40,
        num_beams=1,
        max_new_tokens=20,
        batch_size=1,
        **kwargs,
    ):

        resp = lorax_client.generate(prompt,adapter_id='wt3639/Llama-3-8B-Instruct_CourseRec_lora', adapter_source='hub', max_new_tokens=max_new_tokens)
        
        return resp

def compare_docs_with_context(doc_a, doc_b, target_occupation_name, target_occupation_dsp,skill_gap):
    
    #courses = f"First: name: {doc_a.metadata['name']}  description:{doc_a.metadata['description']} Second: name: {doc_b.metadata['name']}  description:{Sdoc_b.metadata['description']}" 
    courses = f"First: name: {doc_a.metadata['name']}  learning outcomes:{doc_a.metadata['skills'][:1500]} Second: name: {doc_b.metadata['name']}  learning outcomes:{doc_b.metadata['skills'][:1500]}" 
    target_occupation = f"name: {target_occupation_name} description: {target_occupation_dsp[:1500]}"
    skill_gap = skill_gap
    prompt = generate_prompt(target_occupation, skill_gap, courses)
    prompt = prompt
    output = evaluate(prompt)
    # Compare based on the response: [A] means doc_a > doc_b, [B] means doc_a < doc_b
    print(output)
    result_token_id = output.details.tokens[0].id
    if result_token_id == first_id:
        return 1  # doc_a should come before doc_b
    elif result_token_id == second_id:
        return -1  # doc_a should come after doc_b
    else:
        return 0  # Consider them equal if the response is unclear


#-----------------------------------------explanation-------------------------------------


def generate_prompt_exp(input_text):
    return f"""
### Instruction:
As an education expert, you have been provided with information on target occupations and skills gaps, along with recommended course details. Your task is to explain the recommendation in German, focusing on how the course's learning outcomes and target skills relate to the identified skills gaps.

### Input:
{input_text}

### Response:
"""

def generate_exp(
        prompt=None,
        temperature=0.2,
        top_p=0.5,
        top_k=20,
        num_beams=1,
        max_new_tokens=512,
        batch_size=1,
        do_sample=True,
        **kwargs,
    ):

        
        resp = lorax_client.generate(prompt,adapter_id=EXP_LORA_MODEL, adapter_source='hub', max_new_tokens=max_new_tokens)
        
        return resp.generated_text


def find_similar_occupation(target_occupation_query, berufe, top_k, similarity_func):
  
    # Pro kurs wird ein Document erstellt. Dieses enthält Metadaten sowie einen page_content. 
    # Der Inhalt von page_content wird embedded und so für die sucher verwendet.
    docs = []
    for index, beruf in berufe.iterrows():  
        # Create document.
        doc = Document(
            page_content= beruf['short name'] + ' ' + beruf['full name'] + ' ' + beruf['description'],  
            metadata={
                "id": beruf["id"],
                "name": beruf['short name'],
                "description": beruf["description"],
                "entry_requirements": beruf["entry requirements"]
            },
        )
        docs.append(doc)
    
    db_temp = Chroma.from_documents(documents = docs, embedding= embedding_sim, collection_metadata = {"hnsw:space": similarity_func})
    # Retriever will search for the top_5 most similar documents to the query.
    retriever_temp = db_temp.as_retriever(search_kwargs={"k": top_k})
    top_similar_occupations = retriever_temp.get_relevant_documents(target_occupation_query)

    return top_similar_occupations