сырой текст задания → плоская карточка: extract_task_card.py
This commit is contained in:
+85
@@ -0,0 +1,85 @@
|
||||
from pathlib import Path
|
||||
import os
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List
|
||||
|
||||
# ------------------------------
|
||||
# Модель карточки задания
|
||||
# ------------------------------
|
||||
class TaskCard(BaseModel):
|
||||
title: str = Field(..., description="Название задания")
|
||||
subject: str = Field(..., description="Тема/область задачи")
|
||||
deadline_hint: str = Field(..., description="Подсказка по дедлайну")
|
||||
deliverable_type: str = Field(
|
||||
..., description="Тип сдачи (отчёт, код и т.д.)"
|
||||
)
|
||||
grading_hints: List[str] = Field(
|
||||
..., description="Ключевые критерии оценки"
|
||||
)
|
||||
|
||||
# ------------------------------
|
||||
# Интеграция с LangChain
|
||||
# ------------------------------
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.prompts import PromptTemplate
|
||||
from langchain_core.output_parsers import PydanticOutputParser
|
||||
|
||||
parser = PydanticOutputParser(pydantic_object=TaskCard)
|
||||
|
||||
prompt_template = """
|
||||
You are an assistant that extracts structured information from a natural language description of a task.
|
||||
Return the data in JSON format matching the following schema:
|
||||
{format_instructions}
|
||||
Input: {input_text}
|
||||
"""
|
||||
|
||||
prompt = PromptTemplate(
|
||||
template=prompt_template,
|
||||
input_variables=["input_text"],
|
||||
partial_variables={"format_instructions": parser.get_format_instructions()},
|
||||
)
|
||||
|
||||
# ------------------------------
|
||||
# Настройка LLM
|
||||
# ------------------------------
|
||||
def get_llm() -> ChatOpenAI:
|
||||
"""
|
||||
Создаёт экземпляр модели OpenAI.
|
||||
Ключ берётся из переменной окружения OPENAI_API_KEY.
|
||||
"""
|
||||
api_key = os.getenv("OPENAI_API_KEY")
|
||||
if not api_key:
|
||||
raise RuntimeError(
|
||||
"Переменная окружения OPENAI_API_KEY не найдена. "
|
||||
"Пожалуйста, установите ключ API."
|
||||
)
|
||||
return ChatOpenAI(model="gpt-4o-mini", temperature=0.2, openai_api_key=api_key)
|
||||
|
||||
# ------------------------------
|
||||
# Основная цепочка
|
||||
# ------------------------------
|
||||
def build_chain() -> PromptTemplate:
|
||||
llm = get_llm()
|
||||
return prompt | llm | parser
|
||||
|
||||
# ------------------------------
|
||||
# Тестовый запуск
|
||||
# ------------------------------
|
||||
if __name__ == "__main__":
|
||||
# Загрузка переменных окружения из .env, если файл существует
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv(dotenv_path=Path(".env"))
|
||||
except Exception:
|
||||
pass # Если dotenv не установлен – просто продолжим
|
||||
|
||||
raw_text = (
|
||||
"Сдайте к пятнице мини-отчёт по LangChain: 2 страницы, упор на агентов. "
|
||||
"Оценка: за полноту и за пример кода."
|
||||
)
|
||||
|
||||
chain = build_chain()
|
||||
result = chain.invoke({"input_text": raw_text})
|
||||
print(result.model_dump(indent=4))
|
||||
Reference in New Issue
Block a user