New We are sorting MAX channels into categories and territories. Read the news
Public channel ID 77024526448052

⚡Первый Хаб⚡

Главный IT-хаб в MAX. Нейросети, гаджеты, код, автоматизация и кибербезопасность — простым языком. Для тех, кто живёт технологиями и хочет быть на шаг впереди. 🚀

Channels in category
4 027
This channel's rank
№ 1 636
Open category →
Russia
Open in MAX

Posts for the period

By reactions

Search and the whole feed — after free registration. Custom dates — with a subscription; the channel owner sees them for free. Sorting by reactions — with a subscription. Sign up

Loading…

🤖 ИИ-агент на Python, часть 2: научим его показывать список задач

В первой части агент сохранял задачу в `tasks.json`. Теперь добавим безопасный инструмент `list_tasks`: модель сможет попросить Python показать этот файл, но не получит произвольный доступ к компьютеру.

1) В `agent.py`, рядом с `save_task`, добавьте функцию:
```python
def list_tasks() -> str:
if not TASKS_FILE.exists():
return "Список задач пока пуст."
tasks = json.loads(TASKS_FILE.read_text(encoding="utf-8"))
if not tasks:
return "Список задач пока пуст."
return "\n".join(f"{i}. {task}" for i, task in enumerate(tasks, start=1))
```
Она читает только `tasks.json` и нумерует строки. Если файл ещё не создан, вернёт понятный ответ.

2) В массив `tools` добавьте описание второй функции:
```python
{
"type": "function",
"name": "list_tasks",
"description": "Показывает все задачи из локального tasks.json.",
"parameters": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": False
},
"strict": True
}
```
Сохраните там же описание `save_task` из первой части.

3) В цикле обработки `response.output` добавьте ветку:
```python
if item.name == "list_tasks":
result = list_tasks()
elif item.name == "save_task":
args = json.loads(item.arguments)
result = save_task(args["title"])
else:
raise RuntimeError(f"Неизвестная функция: {item.name}")

input_items.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": result,
})
```
После цикла передайте `input_items` обратно в Responses API, как в первой части, и выведите `final.output_text`. Проверьте обе команды: «Покажи мои задачи» и «Добавь задачу: проверить список».

Ожидаемый результат: агент вызывает `list_tasks`, Python читает файл и возвращает нумерованный список; модель формулирует ответ. Для пустого файла появится сообщение, что список пуст. Проверьте содержимое `tasks.json` вручную.

Важно: функция доступна только потому, что вы описали её в `tools` и добавили явную ветку в код. Не используйте `eval` и не запускайте полученные от модели команды.

В следующей части добавим отметку задачи как выполненной. Что удобнее: А — номером, Б — текстом задачи? Напишите вариант в комментариях.

Документация по вызову функций: https://developers.openai.com/api/docs/guides/function-calling
Официальный Python SDK: https://github.com/openai/openai-python

#первыйхаб #технологии #ии #python #разработка
Views: 3
Go to post Open in MAX Report an inaccuracy
VKontakte Telegram Odnoklassniki
Favorites at datool.ru

Follow the channel in your account

Sign up at datool.ru to add the channel “⚡Первый Хаб⚡” to favorites and track its metrics.

Sign up
For channel owners

Verify your channel

Sign in or sign up at datool.ru, then add our bot to the channel following the instructions in your account. Once ownership is verified, the lock disappears and channel management becomes available.

Sign in or sign up

Report an inaccuracy

Describe what needs fixing. If you have a source, add a link.

You are leaving datool.ru

The link leads to an external website. datool.ru is not responsible for its content — check the address before entering passwords or payment details.

Redirecting in 10 s

Go