File size: 3,067 Bytes
ff72db3 |
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 |
import os
from huggingface_hub import InferenceClient
class Evaluation:
def __init__(self, model: str = "Qwen/Qwen2.5-72B-Instruct"):
"""
Args:
model (str): ์ฌ์ฉํ Hugging Face ๋ชจ๋ธ ์ด๋ฆ (๊ธฐ๋ณธ๊ฐ: Qwen/Qwen2.5-72B-Instruct).
"""
self.api_key = os.getenv("HF_API_KEY")
if not self.api_key:
raise ValueError("HF_API_KEY ํ๊ฒฝ๋ณ์๊ฐ ์ค์ ๋์ง ์์์ต๋๋ค.")
self.client = InferenceClient(api_key=self.api_key)
self.model = model
def evaluate(self, instruction: str, answer: str) -> str:
"""
์ฌ์ฉ์์ ๋ต๋ณ๊ณผ ํ๊ฐ ๊ธฐ์ค์ ๊ธฐ๋ฐ์ผ๋ก AI ๋ชจ๋ธ ํ๊ฐ๋ฅผ ์ํํฉ๋๋ค.
Args:
instruction (str): ํ๊ฐ ๊ธฐ์ค์ด ํฌํจ๋ ์ง์นจ.
answer (str): ์ฌ์ฉ์ ๋ต๋ณ.
Returns:
str: ํ๊ฐ ๊ฒฐ๊ณผ.
"""
messages = [
{"role": "system", "content": "์์
๋๊ตฌ ๊ตฌ์ฑ ๋ง๋ฒ์ฌ์
๋๋ค. ํด์ฆ, ๊ณผ์ , ํ ๋ก ์ ์์ฑํ ์ ์์ต๋๋ค."},
{"role": "user", "content": instruction},
]
try:
stream = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.2,
max_tokens=2048,
top_p=0.7,
stream=True,
)
result = ""
for chunk in stream:
if "delta" in chunk.choices[0]:
result += chunk.choices[0].delta.content
print(f"Intermediate result: {result}") # ๋๋ฒ๊น
์ฉ ์ถ๋ ฅ
return result.strip()
except Exception as e:
error_message = f"An error occurred during evaluation: {e}"
print(error_message) # ๋๋ฒ๊น
์ฉ ์ถ๋ ฅ
return error_message
async def evaluate_stream(self, instruction: str):
"""
๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก ํ๊ฐ ๊ฒฐ๊ณผ๋ฅผ ์คํธ๋ฆฌ๋ฐ ์ฒ๋ฆฌํฉ๋๋ค.
Args:
instruction (str): ํ๊ฐ ๊ธฐ์ค์ด ํฌํจ๋ ์ง์นจ.
Yields:
str: ์ค์๊ฐ ํ๊ฐ ๊ฒฐ๊ณผ.
"""
messages = [
{"role": "system", "content": "์ ์๋์๊ฒ ๊ผญ ํ์ํ ์์
๋๊ตฌ ๊ตฌ์ฑ ๋ง๋ฒ์ฌ์
๋๋ค."},
{"role": "user", "content": instruction},
]
try:
stream = self.client.chat.completions.create(
model=self.model,
messages=messages,
temperature=0.2,
max_tokens=2048,
top_p=0.7,
stream=True,
)
for chunk in stream:
if "delta" in chunk.choices[0]:
content = chunk.choices[0].delta.content
print(f"Streaming result: {content}") # ๋๋ฒ๊น
์ฉ ์ถ๋ ฅ
yield content
except Exception as e:
error_message = f"Error: {e}"
print(error_message) # ๋๋ฒ๊น
์ฉ ์ถ๋ ฅ
yield error_message
|