함수 호출은 처음 Phi Family 제품군에서 등장했으며, 이제 Phi-4-mini를 통해 사용할 수 있습니다.
이 예시는 프리미어 리그 결과를 시뮬레이션하는 방법을 보여줍니다. 목표는 Phi-4-mini가 실시간 경기 정보를 제공하도록 하는 것입니다. 아래는 샘플 코드입니다:
import torch
import json
import random
import string
import re
from transformers import AutoModelForCausalLM, AutoProcessor, GenerationConfig,pipeline,AutoTokenizer
model_path = "Your Phi-4-mini location"
model = AutoModelForCausalLM.from_pretrained(
model_path,
device_map="cuda",
attn_implementation="flash_attention_2",
torch_dtype="auto",
trust_remote_code=True)
tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
# Tools should be a list of functions stored in json format
tools = [
{
"name": "get_match_result",
"description": "get match result",
"parameters": {
"match": {
"description": "The name of the match",
"type": "str",
"default": "Arsenal vs ManCity"
}
}
},
]
# Function implementations
def get_match_result(match: str) -> str:
# This would be replaced by a weather API
match_data = {
"Arsenal vs ManCity": "1:1",
"Chelsea vs ManUnited": "0:2"
}
return match_data.get(match, "I don't know")
messages = [
{
"role": "system",
"content": "You are a helpful assistant",
"tools": json.dumps(tools), # pass the tools into system message using tools argument
},
{
"role": "user",
"content": "What is the result of Arsenal vs ManCity today?"
}
]
inputs = tokenizer.apply_chat_template(messages, add_generation_prompt=True, return_dict=True, return_tensors="pt")
inputs = {k: v.to(model.device) for k, v in inputs.items()}
output = model.generate(**inputs, max_new_tokens=128)
print(tokenizer.decode(output[0][len(inputs["input_ids"][0]):]))
tokenizer.batch_decode(output)
response = tokenizer.decode(output[0][len(inputs["input_ids"][0]):], skip_special_tokens=True)
tool_call_id = ''.join(random.choices(string.ascii_letters + string.digits, k=9))
messages.append({"role": "assistant", "tool_calls": [{"type": "function", "id": tool_call_id, "function": response}]})
try :
tool_call = json.loads(response)[0]
except :
json_part = re.search(r'\[.*\]', response, re.DOTALL).group(0)
tool_call = json.loads(json_part)[0]
function_name = tool_call["name"]
arguments = tool_call["arguments"]
result = get_match_result(**arguments)
messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": "get_match_result", "content": str(result)})
print(messages)
면책 조항:
이 문서는 AI 번역 서비스 Co-op Translator를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있으나, 자동 번역에는 오류나 부정확한 내용이 포함될 수 있습니다. 원본 문서(모국어로 작성된 문서)를 권위 있는 출처로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.