Логотип Writing Friday Python Agents

Writing Friday Python Agents

Организация
friday-platform
writing-friday-python-agents

Authoring guide for Python user agents (type:"user") on the Friday platform via the friday-agent-sdk. Covers the @agent decorator, AgentContext capabilities (ctx.llm, ctx.http, ctx.tools, ctx.stream), structured input parsing, result types, and the NATS subprocess execution model. Load when an agent.py exists in scope, when imports from friday_agent_sdk are present, when an @agent decorator is being authored or modified, or when upsert_agent was just called with type:user. Do NOT load to decide whether to author a user agent — that decision belongs in the workspace-chat agent_types rules.

Add to TypingMind

Обзор

Издательfriday-platform
Репозиторийfriday-studio
Название навыкаwriting-friday-python-agents
Звёзды
102
Форки
5
Файлы в комплекте
3
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 3

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — friday-platform. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Writing Friday Python Agents в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/friday-platform/friday-studio/tree/main/packages/system/skills/writing-friday-python-agents
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/friday-platform/friday-studio.git /tmp/friday-studio
mkdir -p .claude/skills
cp -r /tmp/friday-studio/packages/system/skills/writing-friday-python-agents .claude/skills/writing-friday-python-agents
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Writing Friday Python Agents в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Writing Friday Python Agents, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Writing Friday Python Agents не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

Writing Friday Python Agents

Friday agents are single-file Python modules that the platform spawns as native subprocesses and communicates with via NATS. The SDK is a normal Python package installed into your environment. There are no compile-time or WASM steps.

The mental model: your Python code runs as a normal process. All I/O that crosses network boundaries or needs credentials routes through host capabilities the platform provides — LLM generation, HTTP requests, MCP tools, and progress streaming. You declare what you need in the @agent decorator, and the platform wires it up at execution time via AgentContext.

Every Agent Looks Like This

python
from friday_agent_sdk import agent, ok, AgentContext, run

@agent(
    id="my-agent",
    version="1.0.0",
    description="What this agent does — the planner reads this to decide when to invoke it",
)
def execute(prompt: str, ctx: AgentContext):
    # Your logic here
    return ok({"result": "data"})

if __name__ == "__main__":
    run()

Three things are non-negotiable:

  1. The @agent decorator with at least id, version, description.
  2. run() in __main__ — this is the NATS entry point. Without it, the process spawns and immediately exits. run() checks FRIDAY_VALIDATE_ID (registration) or FRIDAY_SESSION_ID (execution), connects to NATS, and handles the protocol.
  3. Return ok() or err() — never return raw dicts/strings.

Capabilities Quick Reference

All capabilities live on AgentContext and are always initialized. They may be stubs in test contexts, but never None.

CapabilityAccessWhat it does
LLMctx.llmGenerate text or structured objects via host LLM registry
HTTPctx.httpMake outbound HTTP requests (TLS handled by host)
MCP Toolsctx.toolsCall MCP server tools (GitHub, Jira, databases, etc.)
Inputctx.inputRead inputFrom upstream-step docs (NOT the signal payload — that's in prompt)
Streamingctx.streamEmit progress/intent events to the UI
Environmentctx.envRead environment variables (API keys, config)
Configctx.configAgent-specific configuration from workspace
Sessionctx.sessionSession metadata (id, workspace_id, user_id, datetime)

ctx.llm — LLM Generation

python
# Text generation
response = ctx.llm.generate(
    messages=[{"role": "user", "content": "Summarize this document"}],
    model="anthropic:claude-sonnet-4-6",  # fully qualified
)
print(response.text)  # str

# Structured output — returns response.object (dict), response.text is None
response = ctx.llm.generate_object(
    messages=[{"role": "user", "content": "Extract key facts"}],
    schema={"type": "object", "properties": {"facts": {"type": "array", "items": {"type": "string"}}}},
    model="anthropic:claude-haiku-4-5",
)
print(response.object)  # dict matching schema

Pass a fully qualified model like anthropic:claude-sonnet-4-6, or set defaults in the llm decorator param and omit the per-call model.

Optional params: max_tokens, temperature, provider_options (dict).

ctx.http — Outbound HTTP

python
response = ctx.http.fetch(
    "https://api.example.com/data",
    method="POST",
    headers={"Authorization": f"Bearer {ctx.env['API_KEY']}"},
    body='{"query": "test"}',
    timeout_ms=30000,
)
data = response.json()  # convenience method
# response.status (int), response.headers (dict), response.body (str)

The host handles TLS, audit logging, and rate limits. 5MB response body limit. Note: HTTP status errors (4xx, 5xx) don't raise — check response.status manually.

ctx.tools — MCP Tools

Declare MCP servers in the decorator, then call tools at runtime:

python
@agent(
    id="my-agent", version="1.0.0", description="...",
    mcp={
        "github": {
            "transport": {
                "type": "stdio",
                "command": "npx",
                "args": ["-y", "@modelcontextprotocol/server-github"],
                "env": {"GITHUB_TOKEN": "{{env.GITHUB_TOKEN}}"}
            }
        }
    },
)
def execute(prompt: str, ctx: AgentContext):
    available = ctx.tools.list()  # list[ToolDefinition] — name, description, input_schema
    result = ctx.tools.call("create_issue", {"title": "Bug", "repo": "owner/repo"})

{{env.VARIABLE}} in MCP config references agent environment variables. Currently only stdio transport is supported.

Do not bypass ctx.tools. Python agents must not call local MCP HTTP endpoints such as http://localhost:8002/mcp, hardcode bearer tokens, or guess provider-specific tool names. Use ctx.tools.list() to inspect the runtime tool surface and ctx.tools.call(name, args) to invoke it. Host-side tool calls are credentialed, audited, and recorded in session history; direct HTTP calls are invisible to Friday and commonly fail with unknown-tool or invalid-token errors.

If ctx.tools.call raises ToolCallError("Unknown tool ..."), list tools and fix the workspace/agent config rather than retrying a guessed name.

Platform-injected tools

The host may inject additional tools into ctx.tools beyond what you declared in mcp={...} — workflows like human-input elicitations, memory writes, artifact handling. These are platform features, not SDK features; their names, arg shapes, and semantics belong to whichever platform you're running on. Call ctx.tools.list() at runtime to see what's actually available, and consult the platform's own docs for which tools to call. The SDK contract is just ctx.tools.call(name, args) -> dict and ToolCallError on failure.

ctx.stream — Progress Events

python
ctx.stream.progress("Analyzing document...", tool_name="analysis")
ctx.stream.intent("Switching to code review phase")
ctx.stream.emit("custom-event", {"key": "value"})  # raw event

Emit progress before expensive operations so the UI shows what's happening.

Structured Input Handling

A type: user agent receives input through one of two channels. Pick by how the job is wired, not by preference:

ChannelWhere it arrivesRead withUse for
Signal payloadprompt stringparse_input(prompt, ...)Fields the trigger signal was fired with
Upstream step outputctx.inputctx.input.get("doc-id")outputTo/inputFrom handoff from a prior step

ctx.input does NOT carry the signal payload — a job triggered by a signal with no upstream producer has an empty ctx.input. If you guessed a key for ctx.input.get(...) and got nothing back, you almost certainly wanted the signal payload — read prompt with parse_input instead.

ctx.input — Upstream step output

When the action declares inputFrom, use ctx.input rather than scraping the prompt. Producers may compact bulky outputs into summary + artifact refs; downstream agents dereference those refs through host capabilities instead of asking the producer to inline large payloads.

python
# Compact value (whatever the upstream step put in its outputTo doc)
payload = ctx.input.get("emails-result")

# Or, when the doc carries artifact refs, hydrate the JSON contents
payload = ctx.input.artifact_json("emails-result")
emails = payload.get("emails", [])
return ok({"count": len(emails)})

Useful methods (all take an optional doc-id; omit it to operate on the full raw input):

  • ctx.input.get(name, default=None) — compact input payload for an inputFrom document.
  • ctx.input.require(name) — same, but raises ValueError if missing.
  • ctx.input.artifact_refs(name) — artifact refs attached to the input.
  • ctx.input.artifact_json(name) — fetch via get_artifact and parse JSON contents.

prompt still exists for natural-language task instructions and backwards compatibility, but parse_input(prompt) is not the right abstraction for multi-step outputTo/inputFrom handoffs.

parse_input — Signal-payload extraction

python
from friday_agent_sdk import parse_input

# Raw dict extraction
data = parse_input(prompt)  # returns dict

# Typed extraction with a dataclass schema
@dataclass
class TaskConfig:
    url: str
    max_retries: int = 3

config = parse_input(prompt, TaskConfig)  # returns TaskConfig instance

Extraction strategy (3-level fallback):

  1. Balanced-brace JSON scan (handles nested objects)
  2. Code-fenced ```json blocks
  3. Entire prompt as JSON

Unknown keys are automatically filtered when using a dataclass schema.

parse_operation — Discriminated dispatch

For agents that handle multiple operation types:

python
from friday_agent_sdk import parse_operation
from dataclasses import dataclass

@dataclass
class ViewConfig:
    operation: str
    item_id: str

@dataclass
class SearchConfig:
    operation: str
    query: str
    max_results: int = 50

OPERATIONS = {
    "view": ViewConfig,
    "search": SearchConfig,
}

config = parse_operation(prompt, OPERATIONS)  # dispatches on "operation" field

match config.operation:
    case "view": return handle_view(config, ctx)
    case "search": return handle_search(config, ctx)

Result Types

Always return ok() or err(). Never return raw values.

python
from friday_agent_sdk import ok, err

# Simple success
return ok({"status": "done", "count": 42})

# Error
return err("Jira API returned 403: insufficient permissions")

ok() accepts any JSON-serializable data: dicts, lists, strings, dataclass instances (auto-converted via dataclasses.asdict).

The Execution Model — What You Cannot Do (And Why)

Your agent runs as a normal Python subprocess, so the standard library and most installed packages work. The constraint is not a sandbox — it's that I/O should route through host capabilities so the platform manages credentials, rate limits, and audit logging centrally.

Recommended — use host capabilities for I/O:

  • ctx.http.fetch() instead of requests/httpx — host manages TLS, logging, limits
  • ctx.llm.generate() instead of anthropic/openai — host manages API keys, routing
  • ctx.tools.list() + ctx.tools.call() instead of direct API/MCP HTTP calls — MCP servers run centrally and calls remain observable
  • ctx.stream.progress() instead of print() — UI integration, not stdout
  • ctx.env instead of os.environ — only declared variables are injected

Available — Python standard library and installed packages:

  • json, re, base64, urllib.parse, dataclasses
  • collections, itertools, functools, typing
  • math, datetime, uuid, hashlib
  • pydantic if installed, numpy if installed, etc.

When in doubt: if the operation touches a network boundary or needs credentials, use the host capability. If it's pure data manipulation, standard library or installed packages are fine.

Getting Agents Into a Workspace

The SDK's job ends at the file: a registered @agent function plus run() in __main__. How that file becomes a usable agent on the host is a platform concern (Friday Studio's CLI, an in-tree dev daemon, a deployment pipeline) — see your platform's docs for the registration command, and do not have the agent code shell out to a daemon to register itself.

Once the platform knows about it, reference it in workspace.yml:

yaml
agents:
  - id: my-agent
    type: user

The id matches the id= value from the @agent decorator. The host resolves type: user to the registered Python agent and routes invocations into your execute function over NATS.

The agent process is spawned per invocation by the host; it sets FRIDAY_VALIDATE_ID (registration) or FRIDAY_SESSION_ID (execution) plus NATS_URL, and run() handles the rest. Your code should not open its own NATS connection.

Casing Convention

This is a subtle but real source of bugs:

  • Decorator kwargs: snake_case (Pythonic) — display_name, use_workspace_skills
  • Dict values inside decorator: camelCase (matches host Zod schemas) — linkRef, displayName inside environment dicts
  • MCP config keys: camelCase in transport config
  • Result data: your choice, but snake_case is conventional for Python agents

The bridge layer (_bridge.py) handles converting decorator metadata to camelCase for the host automatically. You don't need to worry about the boundary — just follow the convention above.

References

For deeper dives, read these reference files:

  • references/api.md — Complete API reference: every decorator param, every context field, every method signature and return type
  • references/examples.md — Annotated example agents from simple (echo) to complex (Jira multi-operation, GitHub PR operations)
  • references/constraints.md — Full list of constraints, casing rules, build pipeline details, and common mistakes with fixes

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Writing Friday Python Agents?

Authoring guide for Python user agents (type:"user") on the Friday platform via the friday-agent-sdk. Covers the @agent decorator, AgentContext capabilities (ctx.llm, ctx.http, ctx.tools, ctx.stream), structured input parsing, result types, and the NATS subprocess execution model. Load when an agent.py exists in scope, when imports from friday_agent_sdk are present, when an @agent decorator is being authored or modified, or when upsert_agent was just called with type:user. Do NOT load to decide whether to author a user agent — that decision belongs in the workspace-chat agent_types rules.

Зачем использовать Writing Friday Python Agents в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Writing Friday Python Agents — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Writing Friday Python Agents в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/friday-platform/friday-studio/tree/main/packages/system/skills/writing-friday-python-agents. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Writing Friday Python Agents?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Writing Friday Python Agents?

С любым количеством. В TypingMind вы можете использовать Writing Friday Python Agents с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Writing Friday Python Agents?

Навык опубликован на GitHub. Издатель — friday-platform. Условия лицензии можно найти в репозитории. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Openclaw Debugging

openclaw
ОрганизацияПопулярный

Выясняйте причины сбоев моделей, провайдеров, интерфейсов инструментов, режима кода, потоковой передачи и поведения OpenClaw в live/Crabbox: прежде чем менять код, выбирайте подходящие журналы, проверки и способ подтверждения, в том числе загружайте сохранённые…

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Openclaw Live Updater

openclaw
ОрганизацияПопулярный

Поддерживайте основной рабочий клон OpenClaw, используемый в production, Gateway под управлением macOS LaunchAgent, локальное приложение macOS, CI для точного коммита main и регулярную полную проверку релиза. Используйте этот навык для обновлений fast-forward…

82.2K
391K
Файлы: 2
Открыть
Логотип openclaw

Openclaw Pr Maintainer

openclaw
ОрганизацияПопулярный

Проверяйте и сортируйте по приоритету проблемы OpenClaw и pull request, исправляйте их или вносите изменения в репозиторий, опираясь на актуальные данные исходного кода и стандартный процесс сопровождения.

82.2K
391K
Файлы: 5
Открыть
Логотип openclaw

Openclaw Refactor Docs

openclaw
ОрганизацияПопулярный

Переработайте существующую страницу документации OpenClaw: сохраните подтверждённую источниками информацию, измените структуру и проверьте результат.

82.2K
391K
Инструкции
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇