add agent.py
This commit is contained in:
@@ -1,18 +1,111 @@
|
||||
# Placeholder deep agent implementation
|
||||
import requests, json, os
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
def search(query):
|
||||
# simple Bing API placeholder
|
||||
return f"Results for {query}"
|
||||
"""
|
||||
Пример преобразования неформального описания задания в структурированный объект.
|
||||
|
||||
def create_virtual_file(name, content):
|
||||
with open(name, 'w') as f:
|
||||
f.write(content)
|
||||
Используем:
|
||||
* LangChain (core + OpenAI)
|
||||
* Pydantic для типизации и проверки результата
|
||||
"""
|
||||
|
||||
def main():
|
||||
q="test"
|
||||
res=search(q)
|
||||
create_virtual_file('output.txt',res)
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
from langchain_core.prompts import PromptTemplate
|
||||
from langchain_openai import ChatOpenAI
|
||||
from langchain_core.output_parsers import PydanticOutputParser
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 1. Модель карточки задания (Pydantic)
|
||||
# ------------------------------------------------------------------
|
||||
class AssignmentCard(BaseModel):
|
||||
title: str = Field(..., description="Краткое название задачи")
|
||||
subject: str = Field(
|
||||
..., description="Предмет/тема, к которой относится задание"
|
||||
)
|
||||
deadline_hint: str | None = Field(
|
||||
None,
|
||||
description="Указание дедлайна в свободной форме (например, «к пятнице»)",
|
||||
)
|
||||
deliverable_type: str = Field(
|
||||
...,
|
||||
description=(
|
||||
"Тип сдачи: отчёт, код, презентация и т.п. "
|
||||
"(если однотипное – перечислите без пунктов)"
|
||||
),
|
||||
)
|
||||
grading_hints: list[str] | None = Field(
|
||||
None,
|
||||
description="Ключевые критерии оценки (список строк)",
|
||||
)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 2. Парсер и промпт
|
||||
# ------------------------------------------------------------------
|
||||
parser = PydanticOutputParser(pydantic_object=AssignmentCard)
|
||||
|
||||
prompt_template = """
|
||||
Пожалуйста, преобразуйте следующее описание задания в JSON‑объект,
|
||||
соответствующий схеме:
|
||||
|
||||
{format_instructions}
|
||||
|
||||
Текст задания:
|
||||
"{input_text}"
|
||||
"""
|
||||
|
||||
prompt = PromptTemplate(
|
||||
template=prompt_template,
|
||||
input_variables=["input_text"],
|
||||
partial_variables={"format_instructions": parser.get_format_instructions()},
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 3. Модель LLM
|
||||
# ------------------------------------------------------------------
|
||||
llm = ChatOpenAI(temperature=0, model="gpt-4o-mini") # можно поменять модель
|
||||
|
||||
# Создаём цепочку: Prompt → LLM → Parser
|
||||
chain = prompt | llm | parser
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 4. Функция «обработки» одной строки
|
||||
# ------------------------------------------------------------------
|
||||
def parse_assignment(text: str) -> AssignmentCard:
|
||||
"""Возвращает валидированную модель из текста."""
|
||||
return chain.invoke({"input_text": text})
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# 5. Тестовый пример (можно заменить на любой другой)
|
||||
# ------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
example = (
|
||||
"Сдайте к пятнице мини‑отчёт по LangChain: "
|
||||
"2 страницы, упор на агентов. Оценка: за полноту и за пример кода."
|
||||
)
|
||||
card = parse_assignment(example)
|
||||
|
||||
# Выводим модель в виде JSON
|
||||
print("\n=== Валидация ===")
|
||||
print(card.model_dump(indent=4))
|
||||
|
||||
# Краткая человекочитаемая сводка
|
||||
print("\n=== Сводка ===")
|
||||
print(f"Тема: {card.subject}")
|
||||
print(f"Название: {card.title}")
|
||||
if card.deadline_hint:
|
||||
print(f"Дедлайн: {card.deadline_hint}")
|
||||
print(f"Сдача: {card.deliverable_type}")
|
||||
if card.grading_hints:
|
||||
print("Критерии оценки:")
|
||||
for h in card.grading_hints:
|
||||
print(f" • {h}")
|
||||
|
||||
|
||||
# ────────────────────── End of file ─────────────────────
|
||||
|
||||
Reference in New Issue
Block a user