Views
No views yet
1import json
2from unsloth import FastLanguageModel
3
4# loading the model and tokenizer
5model, tokenizer = FastLanguageModel.from_pretrained(
6 model_name="atasoglu/Turkish-Llama-3-8B-function-calling",
7 load_in_4bit=True,
8)
9FastLanguageModel.for_inference(model)1# define the prompt templates
2system_prompt = """Sen yardımsever, akıllı ve fonksiyon çağrısı yapabilen bir asistansın.
3Aşağıda JSON parçası içinde verilen fonksiyonları kullanarak kullanıcının sorusunu uygun şekilde cevaplamanı istiyorum.
4
5Fonksiyon çağrısı yaparken uyman gereken talimatlar:
6
7* Fonksiyonlar, JSON şeması olarak ifade edilmiştir.
8* Eğer kullanıcının sorusu, bu fonksiyonlardan en az biri kullanılarak cevaplanabiliyorsa; uygun bir fonksiyon çağrısını JSON parçası içinde oluştur.
9* Fonksiyonların parametreleri için asla uydurmalar yapma ve sadece kullanıcının verdiği bilgileri kullan.
10* Eğer kullanıcının sorusu herhangi bir fonksiyon ile cevaplanamıyorsa, sadece "Verilen fonksiyonlarla cevaplanamaz" metnini döndür ve başka bir açıklama yapma.
11
12Bu talimatlara uyarak soruları cevaplandır."""
13
14user_prompt = """### Fonksiyonlar
15
16'''json
17{tools}
18'''
19
20### Soru
21
22{query}"""
23
24# define the tools and messages
25tools = [
26 {
27 "type": "function",
28 "function": {
29 "name": "get_weather",
30 "description": "Get current temperature for a given location.",
31 "parameters": {
32 "type": "object",
33 "properties": {
34 "location": {
35 "type": "string",
36 "description": "City and country e.g. Bogotá, Colombia",
37 }
38 },
39 "required": ["location"],
40 "additionalProperties": False,
41 },
42 "strict": True,
43 },
44 }
45]
46query = "Paris'te hava şu anda nasıl?"
47messages = [
48 {
49 "role": "system",
50 "content": system_prompt,
51 },
52 {
53 "role": "user",
54 "content": user_prompt.format(
55 tools=json.dumps(tools, ensure_ascii=False),
56 query=query,
57 ),
58 },
59]1import re
2
3
4# define an evaluation function
5def eval_function_calling(text):
6 match_ = re.search(r"```json(.*)```", text, re.DOTALL)
7 if match_ is None:
8 return False, text
9 return True, json.loads(match_.group(1).strip())
10
11
12# tokenize the inputs
13inputs = tokenizer.apply_chat_template(
14 messages,
15 add_generation_prompt=True,
16 return_dict=True,
17 return_tensors="pt",
18).to("cuda")
19
20# define generation arguments
21generation_kwargs = dict(
22 do_sample=True,
23 use_cache=True,
24 max_new_tokens=500,
25 temperature=0.3,
26 top_p=0.9,
27 top_k=40,
28)
29
30# finally, generate the output
31outputs = model.generate(**inputs, **generation_kwargs)
32output_ids = outputs[:, inputs["input_ids"].shape[1] :]
33generated_texts = tokenizer.batch_decode(output_ids, skip_special_tokens=True)
34has_function_calling, results = eval_function_calling(generated_texts[0])
35
36# print the model response
37if has_function_calling:
38 for result in results:
39 fn = result["function"]
40 name, args = fn["name"], fn["arguments"]
41 print(f"Calling {name!r} function with these arguments: {args}")
42else:
43 print(f"No function call: {results!r}")Calling 'get_weather' function with these arguments: {"location":"Paris, France"}