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.tools import tool from deepagents import create_deep_agent from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend # Load environment variables (OPENAI_API_KEY) 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 = ChatOpenAI( model="openai/gpt-oss-20b:free", base_url="https://openrouter.ai/api/v1", api_key=os.getenv("OPENAI_API_KEY"), temperature=0.0, ) # 5. Define a tool that performs the parsing chain @tool def parse_task(input_text: str) -> str: """Parse a raw task description into a structured JSON string.""" chain = prompt | llm | parser result = chain.invoke({"input_text": input_text}) # parser returns a dict; convert to JSON string for the agent to return return result.model_dump_json() # 6. Backend for the agent (filesystem + local shell, though not used here) 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.", ) # 8. Main entry point async def main(): # Example input – replace with any user text user_text = "Сдайте к пятнице мини‑отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода." result = await agent.ainvoke( {"messages": [HumanMessage(content=user_text)]}, {"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)}") if __name__ == "__main__": asyncio.run(main())