add main.py
This commit is contained in:
@@ -1,9 +1,19 @@
|
||||
"""
|
||||
Main entry point for the "сырой текст задания → плоская карточка" task.
|
||||
|
||||
The script demonstrates how to convert a free‑form description of an assignment into a structured data object using LangChain and Pydantic.
|
||||
The script demonstrates how to:
|
||||
1. Define a Pydantic model that represents a parsed task card.
|
||||
2. Build a LangChain chain that takes an informal description and returns a validated
|
||||
:class:`TaskCard` instance.
|
||||
3. Print the raw JSON, the ``model_dump`` representation and a human‑readable summary.
|
||||
|
||||
Usage examples are provided in the ``__main__`` section – three different raw texts are parsed and printed.
|
||||
The example is intentionally self‑contained – it does not rely on any external files
|
||||
and can be executed with:
|
||||
|
||||
```bash
|
||||
pip install -r requirements.txt
|
||||
python main.py
|
||||
```
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,59 +21,15 @@ from __future__ import annotations
|
||||
import os
|
||||
from typing import List
|
||||
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.prompts import PromptTemplate
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.output_parsers import PydanticOutputParser
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
# Import the model defined in models.py
|
||||
from models import TaskCard
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 1. Define the data model that represents a task card.
|
||||
# ---------------------------------------------------------------------------
|
||||
class TaskCard(BaseModel):
|
||||
"""Structured representation of an assignment description.
|
||||
|
||||
The fields are intentionally generic – they capture the most common pieces of information
|
||||
that appear in the course tasks:
|
||||
|
||||
* ``title`` – short name of the task.
|
||||
* ``subject`` – subject or topic area.
|
||||
* ``deadline_hint`` – free‑form hint about when the task should be finished.
|
||||
* ``deliverable_type`` – what is expected to be submitted (report, code, presentation…).
|
||||
* ``grading_hints`` – list of items that influence grading.
|
||||
"""
|
||||
|
||||
title: str = Field(..., description="Short name of the task")
|
||||
subject: str | None = Field(None, description="Subject or topic area")
|
||||
deadline_hint: str | None = Field(
|
||||
None,
|
||||
description="Free‑form hint about when the task should be finished",
|
||||
)
|
||||
deliverable_type: str | None = Field(
|
||||
None,
|
||||
description="What is expected to be submitted (report, code, presentation…)",
|
||||
)
|
||||
grading_hints: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="List of items that influence grading",
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 2. Build the prompt and parser.
|
||||
# ---------------------------------------------------------------------------
|
||||
parser = PydanticOutputParser(pydantic_object=TaskCard)
|
||||
|
||||
prompt_template = PromptTemplate(
|
||||
template=(
|
||||
"You are an assistant that extracts structured information from a free‑form task description."
|
||||
" Return only the data in JSON format that matches the following schema:\n{format_instructions}\n"
|
||||
"Input: {text}"
|
||||
),
|
||||
input_variables=["text"],
|
||||
partial_variables={"format_instructions": parser.get_format_instructions()},
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 3. Create the LLM instance.
|
||||
# 1. Configure LLM – use BroJS endpoint via environment variable
|
||||
# ---------------------------------------------------------------------------
|
||||
llm = ChatOpenAI(
|
||||
model="openai/gpt-oss-20b:free",
|
||||
@@ -73,39 +39,44 @@ llm = ChatOpenAI(
|
||||
)
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. Helper that runs the chain and returns a TaskCard.
|
||||
# 2. Prepare parser and prompt template
|
||||
# ---------------------------------------------------------------------------
|
||||
async def parse_task(text: str) -> TaskCard:
|
||||
"""Parse *text* into a :class:`TaskCard` using LangChain.
|
||||
parser = PydanticOutputParser(pydantic_object=TaskCard)
|
||||
|
||||
The function is asynchronous because ``ChatOpenAI`` uses an async API. It can be called from
|
||||
synchronous code via ``asyncio.run``.
|
||||
"""
|
||||
prompt_template = PromptTemplate(
|
||||
template="""
|
||||
You are an assistant that extracts structured information from a short informal task description.
|
||||
Return the data in the format specified by the following instructions.
|
||||
|
||||
chain = prompt_template | llm | parser
|
||||
result = await chain.ainvoke({"text": text})
|
||||
return result
|
||||
Input: {input_text}
|
||||
{format_instructions}
|
||||
""",
|
||||
input_variables=["input_text"],
|
||||
partial_variables={"format_instructions": parser.get_format_instructions()},
|
||||
)
|
||||
|
||||
chain = prompt_template | llm | parser
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 5. Demo – three example texts.
|
||||
# 3. Example usage – three different informal descriptions
|
||||
# ---------------------------------------------------------------------------
|
||||
examples: List[str] = [
|
||||
"Сдайте к пятнице мини-отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода.",
|
||||
"На следующей неделе подготовьте презентацию о применении RAG в чат‑ботах. Требуется 10 слайдов, оценка – содержание и дизайн.",
|
||||
"Разработайте скрипт на Python, который парсит CSV и выводит статистику. Срок: до конца месяца. Оценка: корректность кода и комментарии.",
|
||||
]
|
||||
|
||||
for idx, text in enumerate(examples, 1):
|
||||
print(f"\nExample {idx}:\n{text}\n")
|
||||
result = chain.invoke({"input_text": text})
|
||||
# ``result`` is already a TaskCard instance because of the parser.
|
||||
print("Parsed object (model_dump):", result.model_dump())
|
||||
print("Human‑readable summary:\n", str(result))
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 4. If run as script, execute examples
|
||||
# ---------------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
import asyncio
|
||||
|
||||
examples = [
|
||||
"Сдайте к пятнице мини‑отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода.",
|
||||
"На следующей неделе подготовьте презентацию о Qdrant. Должно быть 10 слайдов, включать примеры кода. Оценка по содержанию и дизайну.",
|
||||
"Разработайте скрипт на Python, который генерирует случайный пароль длиной 12 символов. Сдача – код в репозитории. Оценка: корректность и безопасность.",
|
||||
]
|
||||
|
||||
async def demo():
|
||||
for i, txt in enumerate(examples, start=1):
|
||||
card = await parse_task(txt)
|
||||
print(f"\nExample {i}:")
|
||||
print("Raw text:")
|
||||
print(txt)
|
||||
print("\nParsed card: ")
|
||||
# Pretty‑print the model using ``model_dump`` – it returns a dict.
|
||||
print(card.model_dump(indent=2, sort_keys=False))
|
||||
|
||||
asyncio.run(demo())
|
||||
# The loop above already demonstrates the functionality.
|
||||
pass
|
||||
"
|
||||
Reference in New Issue
Block a user