add main.py

This commit is contained in:
2026-05-26 11:45:26 +00:00
parent e3649de283
commit 49cebe958b
+29 -43
View File
@@ -1,51 +1,37 @@
"""
Task: Convert raw task text to flat card using LangChain and Pydantic.
"""
from pydantic import BaseModel, Field
from langchain_core.prompts import PromptTemplate
import os
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import PydanticOutputParser
from langchain_core.messages import HumanMessage
from langchain_output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field
class TaskCard(BaseModel):
title: str = Field(..., description="Task title")
subject: str = Field(..., description="Subject or topic of the task")
deadline_hint: str = Field(..., description="Freeform deadline hint")
deliverable_type: str = Field(..., description="What to submit: report, code, presentation, etc.")
grading_hints: list[str] = Field(..., description="List of grading hints mentioned in the text")
title: str = Field(..., description="Title of the task")
subject: str = Field(..., description="Subject area")
deadline_hint: str | None = Field(None, description="Hint about deadline")
deliverable_type: str = Field(..., description="What to submit (report, code, etc.)")
grading_hints: list[str] = Field(default_factory=list, description="Hints for grading")
# Prompt template
prompt_template = """
You are an assistant that extracts structured information from a natural language task description.
Return the data in the following JSON format:
{format_instructions}
Task description: {task_text}
"""
parser = PydanticOutputParser(pydantic_object=TaskCard)
prompt = PromptTemplate(
template=prompt_template,
input_variables=["task_text"],
partial_variables={"format_instructions": parser.get_format_instructions()},
llm = ChatOpenAI(
model="openai/gpt-oss-20b:free",
base_url="https://openrouter.ai/api/v1",
api_key=os.getenv("OPENAI_API_KEY"),
temperature=0.0,
)
parser = PydanticOutputParser(pydantic_object=TaskCard)
prompt_template = """
You are a task summarizer.
Given the following informal description of an assignment, produce a JSON object matching TaskCard model.
llm = ChatOpenAI(temperature=0)
chain = prompt | llm | parser
Description: {description}
{format_instructions}
"""
prompt = prompt_template | llm | parser
async def main():
description = "Сдайте к пятнице мини-отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода."
result = await prompt.ainvoke({"description": description})
print(result["messages"][-1].content)
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python main.py '<task description>'")
sys.exit(1)
task_text = sys.argv[1]
result = chain.invoke({"task_text": task_text})
print("Parsed card:\n", result.model_dump(indent=2))
# Human readable summary
print("\nSummary:\n")
print(f"Title: {result.title}")
print(f"Subject: {result.subject}")
print(f"Deadline hint: {result.deadline_hint}")
print(f"Deliverable type: {result.deliverable_type}")
print(f"Grading hints: {', '.join(result.grading_hints)}")
"""
import asyncio
asyncio.run(main())