From 37c7f6691ac35926b127bcfe05bfe4ff5a6a76db Mon Sep 17 00:00:00 2001 From: Danil Parunin 5f1b81b8-4f5d-11e8-9c2d-fa7ae01bbebc Date: Tue, 16 Jun 2026 08:08:01 +0000 Subject: [PATCH] =?UTF-8?q?fix(needs=5Ffixes):=201=20=D0=B8=D1=81=D0=BF?= =?UTF-8?q?=D1=80=D0=B0=D0=B2=D0=BB=D0=B5=D0=BD=D0=B8=D0=B9,=200=20=D0=BE?= =?UTF-8?q?=D1=82=D1=81=D1=82=D0=BE=D1=8F=D0=BD=D0=BE=20=E2=80=94=20main.p?= =?UTF-8?q?y?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main.py | 109 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 55 insertions(+), 54 deletions(-) diff --git a/main.py b/main.py index 4ba12fd..866e636 100644 --- a/main.py +++ b/main.py @@ -2,92 +2,93 @@ import os import asyncio from dotenv import load_dotenv from langchain_openai import ChatOpenAI -from langchain_core.messages import HumanMessage from langchain_core.prompts import PromptTemplate from langchain_core.output_parsers import PydanticOutputParser from pydantic import BaseModel, Field +from langchain_core.messages import HumanMessage from langchain.tools import tool from deepagents import create_deep_agent from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend -# Load environment variables (OPENAI_API_KEY) +# Load environment variables load_dotenv() -# 1. Define the Pydantic model for the task card -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="Список критериев оценки, упомянутых в тексте") - -# 2. Create the parser that will enforce the structure -parser = PydanticOutputParser(pydantic_object=TaskCard) - -# 3. Prompt template that asks the model to output the data in the required format -prompt = PromptTemplate( - template=""" -Ниже приведено описание задания. Ваша задача — извлечь из него следующую информацию и вернуть в формате JSON, соответствующем модели TaskCard: - -{input_text} - -{format_instructions} -""", - input_variables=["input_text"], - partial_variables={"format_instructions": parser.get_format_instructions()}, -) - -# 4. LLM configuration (OpenRouter) +# ---------- LLM INITIALIZATION ---------- +# Using OpenRouter via langchain-openai as required llm = ChatOpenAI( - model="openai/gpt-oss-20b:free", - base_url="https://openrouter.ai/api/v1", - api_key=os.getenv("OPENAI_API_KEY"), + model_name="gpt-4o-mini", # example model available on OpenRouter + base_url="https://openrouter.ai/api/v1/chat/completions", + api_key=os.getenv("OPENROUTER_API_KEY"), temperature=0.0, ) -# 5. Define a tool that performs the parsing chain +# ---------- Pydantic MODEL ---------- +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="Список критериев оценки, упомянутых в тексте") + +# ---------- PROMPT AND PARSER ---------- +parser = PydanticOutputParser(pydantic_object=TaskCard) + +prompt_template = """You are an assistant that extracts structured information from a short task description. + +Input: {task_text} + +Output must be a JSON object with the following fields: +{format_instructions} + +Respond ONLY with the JSON object. +""" + +prompt = PromptTemplate( + template=prompt_template, + input_variables=["task_text"], + partial_variables={"format_instructions": parser.get_format_instructions()}, +) + +# ---------- TOOL THAT RUNS THE CHAIN ---------- @tool -def parse_task(input_text: str) -> str: - """Parse a raw task description into a structured JSON string.""" +def parse_task(task_text: str) -> str: + """Parse a task description into a structured JSON object.""" chain = prompt | llm | parser - result = chain.invoke({"input_text": input_text}) - # parser returns a dict; convert to JSON string for the agent to return + result = chain.invoke({"task_text": task_text}) + # Return the validated object as JSON string for the agent to forward return result.model_dump_json() -# 6. Backend for the agent (filesystem + local shell, though not used here) +# ---------- BACKEND AND AGENT ---------- backend = CompositeBackend([ LocalShellBackend(workspace_dir="./workspace"), FilesystemBackend(), ]) -# 7. Create the deep agent with the parsing tool agent = create_deep_agent( model=llm, tools=[parse_task], backend=backend, - system_prompt="You are a task‑card extractor. Use the provided tool to parse the input and return the JSON string.", + system_prompt="You are a helpful assistant that parses a single task description into structured data using the provided tool.", ) -# 8. Main entry point +# ---------- MAIN EXECUTION ---------- async def main(): - # Example input – replace with any user text - user_text = "Сдайте к пятнице мини‑отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода." + # Example input – single line, no dialogue + task_description = "Сдайте к пятнице мини-отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода." result = await agent.ainvoke( - {"messages": [HumanMessage(content=user_text)]}, + {"messages": [HumanMessage(content=task_description)]}, {"configurable": {"thread_id": "session-1"}}, ) - # The agent returns the tool output as the last message - output = result["messages"][-1].content - print("Parsed JSON:") - print(output) - # Pretty‑print the parsed object - card = TaskCard.parse_raw(output) - print("\nHuman‑readable summary:") - print(f"Title: {card.title}") - print(f"Subject: {card.subject}") - print(f"Deadline hint: {card.deadline_hint}") - print(f"Deliverable type: {card.deliverable_type}") - print(f"Grading hints: {', '.join(card.grading_hints)}") + # The agent will return the tool output as the last message + output_json = result["messages"][-1].content + print("\n--- Parsed JSON ---") + print(output_json) + # Load into Pydantic for pretty printing and summary + card = TaskCard.parse_raw(output_json) + print("\n--- Validated Object ---") + print(card.model_dump()) + print("\n--- Summary ---") + print(f"Title: {card.title}\nSubject: {card.subject}\nDeadline: {card.deadline_hint}\nDeliverable: {card.deliverable_type}\nGrading: {', '.join(card.grading_hints)}") if __name__ == "__main__": asyncio.run(main())