fix(needs_fixes): 1 исправлений, 0 отстояно — main.py

This commit is contained in:
+55 -54
View File
@@ -2,92 +2,93 @@ import os
import asyncio import asyncio
from dotenv import load_dotenv from dotenv import load_dotenv
from langchain_openai import ChatOpenAI from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage
from langchain_core.prompts import PromptTemplate from langchain_core.prompts import PromptTemplate
from langchain_core.output_parsers import PydanticOutputParser from langchain_core.output_parsers import PydanticOutputParser
from pydantic import BaseModel, Field from pydantic import BaseModel, Field
from langchain_core.messages import HumanMessage
from langchain.tools import tool from langchain.tools import tool
from deepagents import create_deep_agent from deepagents import create_deep_agent
from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend from deepagents.backends import CompositeBackend, LocalShellBackend, FilesystemBackend
# Load environment variables (OPENAI_API_KEY) # Load environment variables
load_dotenv() load_dotenv()
# 1. Define the Pydantic model for the task card # ---------- LLM INITIALIZATION ----------
class TaskCard(BaseModel): # Using OpenRouter via langchain-openai as required
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( llm = ChatOpenAI(
model="openai/gpt-oss-20b:free", model_name="gpt-4o-mini", # example model available on OpenRouter
base_url="https://openrouter.ai/api/v1", base_url="https://openrouter.ai/api/v1/chat/completions",
api_key=os.getenv("OPENAI_API_KEY"), api_key=os.getenv("OPENROUTER_API_KEY"),
temperature=0.0, 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 @tool
def parse_task(input_text: str) -> str: def parse_task(task_text: str) -> str:
"""Parse a raw task description into a structured JSON string.""" """Parse a task description into a structured JSON object."""
chain = prompt | llm | parser chain = prompt | llm | parser
result = chain.invoke({"input_text": input_text}) result = chain.invoke({"task_text": task_text})
# parser returns a dict; convert to JSON string for the agent to return # Return the validated object as JSON string for the agent to forward
return result.model_dump_json() return result.model_dump_json()
# 6. Backend for the agent (filesystem + local shell, though not used here) # ---------- BACKEND AND AGENT ----------
backend = CompositeBackend([ backend = CompositeBackend([
LocalShellBackend(workspace_dir="./workspace"), LocalShellBackend(workspace_dir="./workspace"),
FilesystemBackend(), FilesystemBackend(),
]) ])
# 7. Create the deep agent with the parsing tool
agent = create_deep_agent( agent = create_deep_agent(
model=llm, model=llm,
tools=[parse_task], tools=[parse_task],
backend=backend, backend=backend,
system_prompt="You are a taskcard 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(): async def main():
# Example input replace with any user text # Example input single line, no dialogue
user_text = "Сдайте к пятнице миниотчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода." task_description = "Сдайте к пятнице мини-отчёт по LangChain: 2 страницы, упор на агентов. Оценка: за полноту и за пример кода."
result = await agent.ainvoke( result = await agent.ainvoke(
{"messages": [HumanMessage(content=user_text)]}, {"messages": [HumanMessage(content=task_description)]},
{"configurable": {"thread_id": "session-1"}}, {"configurable": {"thread_id": "session-1"}},
) )
# The agent returns the tool output as the last message # The agent will return the tool output as the last message
output = result["messages"][-1].content output_json = result["messages"][-1].content
print("Parsed JSON:") print("\n--- Parsed JSON ---")
print(output) print(output_json)
# Prettyprint the parsed object # Load into Pydantic for pretty printing and summary
card = TaskCard.parse_raw(output) card = TaskCard.parse_raw(output_json)
print("\nHumanreadable summary:") print("\n--- Validated Object ---")
print(f"Title: {card.title}") print(card.model_dump())
print(f"Subject: {card.subject}") print("\n--- Summary ---")
print(f"Deadline hint: {card.deadline_hint}") print(f"Title: {card.title}\nSubject: {card.subject}\nDeadline: {card.deadline_hint}\nDeliverable: {card.deliverable_type}\nGrading: {', '.join(card.grading_hints)}")
print(f"Deliverable type: {card.deliverable_type}")
print(f"Grading hints: {', '.join(card.grading_hints)}")
if __name__ == "__main__": if __name__ == "__main__":
asyncio.run(main()) asyncio.run(main())