Skip to content
TheChatArchiveThe Chat Archive
chatgpt-4o-latest-20250326· OpenAIHugging Face LMArena Human Preference 140K

объясни простым языком: Running agents You can run agents via the Runner class. You have…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-flash-preview-04-17’s answer.
  1. User

    объясни простым языком:

    Running agents

    You can run agents via the Runner class. You have 3 options:

    Runner.run(), which runs async and returns a RunResult.
    Runner.run_sync(), which is a sync method and just runs .run() under the hood.
    Runner.run_streamed(), which runs async and returns a RunResultStreaming. It calls the LLM in streaming mode, and streams those events to you as they are received.
    

    from agents import Agent, Runner

    async def main(): agent = Agent(name="Assistant", instructions="You are a helpful assistant")

    result = await Runner.run(agent, "Write a haiku about recursion in programming.")
    print(result.final_output)
    # Code within the code,
    # Functions calling themselves,
    # Infinite loop's dance.
    

    Read more in the results guide. The agent loop

    When you use the run method in Runner, you pass in a starting agent and input. The input can either be a string (which is considered a user message), or a list of input items, which are the items in the OpenAI Responses API.

    The runner then runs a loop:

    We call the LLM for the current agent, with the current input.
    The LLM produces its output.
        If the LLM returns a final_output, the loop ends and we return the result.
        If the LLM does a handoff, we update the current agent and input, and re-run the loop.
        If the LLM produces tool calls, we run those tool calls, append the results, and re-run the loop.
    If we exceed the max_turns passed, we raise a MaxTurnsExceeded exception.
    

    Note

    The rule for whether the LLM output is considered as a "final output" is that it produces text output with the desired type, and there are no tool calls. Streaming

    Streaming allows you to additionally receive streaming events as the LLM runs. Once the stream is done, the RunResultStreaming will contain the complete information about the run, including all the new outputs produces. You can call .stream_events() for the streaming events. Read more in the streaming guide. Run config

    The run_config parameter lets you configure some global settings for the agent run:

    model: Allows setting a global LLM model to use, irrespective of what model each Agent has.
    model_provider: A model provider for looking up model names, which defaults to OpenAI.
    model_settings: Overrides agent-specific settings. For example, you can set a global temperature or top_p.
    input_guardrails, output_guardrails: A list of input or output guardrails to include on all runs.
    handoff_input_filter: A global input filter to apply to all handoffs, if the handoff doesn't already have one. The input filter allows you to edit the inputs that are sent to the new agent. See the documentation in Handoff.input_filter for more details.
    tracing_disabled: Allows you to disable tracing for the entire run.
    trace_include_sensitive_data: Configures whether traces will include potentially sensitive data, such as LLM and tool call inputs/outputs.
    workflow_name, trace_id, group_id: Sets the tracing workflow name, trace ID and trace group ID for the run. We recommend at least setting workflow_name. The group ID is an optional field that lets you link traces across multiple runs.
    trace_metadata: Metadata to include on all traces.
    

    Conversations/chat threads

    Calling any of the run methods can result in one or more agents running (and hence one or more LLM calls), but it represents a single logical turn in a chat conversation. For example:

    User turn: user enter text
    Runner run: first agent calls LLM, runs tools, does a handoff to a second agent, second agent runs more tools, and then produces an output.
    

    At the end of the agent run, you can choose what to show to the user. For example, you might show the user every new item generated by the agents, or just the final output. Either way, the user might then ask a followup question, in which case you can call the run method again.

    You can use the base RunResultBase.to_input_list() method to get the inputs for the next turn.

    async def main(): agent = Agent(name="Assistant", instructions="Reply very concisely.")

    with trace(workflow_name="Conversation", group_id=thread_id):
        # First turn
        result = await Runner.run(agent, "What city is the Golden Gate Bridge in?")
        print(result.final_output)
        # San Francisco
    
        # Second turn
        new_input = result.to_input_list() + [{"role": "user", "content": "What state is it in?"}]
        result = await Runner.run(agent, new_input)
        print(result.final_output)
        # California
    

    Exceptions

    The SDK raises exceptions in certain cases. The full list is in agents.exceptions. As an overview:

    AgentsException is the base class for all exceptions raised in the SDK.
    MaxTurnsExceeded is raised when the run exceeds the max_turns passed to the run methods.
    ModelBehaviorError is raised when the model produces invalid outputs, e.g. malformed JSON or using non-existent tools.
    UserError is raised when you (the person writing code using the SDK) make an error using the SDK.
    InputGuardrailTripwireTriggered, OutputGuardrailTripwireTriggered is raised when a guardrail is tripped.
    
  2. Assistant

    Конечно! Давайте разберём всё по-простому и по шагам — что тут происходит, как всё работает и зачем это нужно.


    🚀 Что вообще происходит?

    Речь идет о системе агентов, которая позволяет вам создавать «умных помощников» на основе LLM (моделей вроде GPT), и управлять их поведением. Эти агенты могут:

    • общаться с пользователем,
    • использовать инструменты,
    • передавать задачу другому агенту,
    • и в итоге выдавать результат.

    Для управления этими агентами используется специальный класс — Runner.


    ⚙️ Как запускать агентов?

    Есть 3 способа «запустить» агента:

    1. Runner.run() – асинхронный запуск. Возвращает результат после того, как агент "подумает".
    2. Runner.run_sync() – синхронный вариант (если вы не хотите возиться с async/await).
    3. Runner.run_streamed() – тоже асинхронный, но отвечает «по частям», как стриминговые ответы в GPT.

    Пример использования:

    from agents import Agent, Runner
    
    async def main():
        agent = Agent(name="Assistant", instructions="You are a helpful assistant")
        result = await Runner.run(agent, "Напиши хайку про рекурсию в программировании.")
        print(result.final_output)
    

    🔁 Как работает "цикл агента"?

    Когда вы вызываете Runner.run(), начинается циклический процесс, пока не получится окончательный ответ. Вот как это работает:

    1. Агент получает ввод (например, текст пользователя).
    2. LLM (типа GPT) отвечает.
    3. Варианты поведения:
      • ✅ Если LLM выдал финальный ответ (простой текст) — показываем результат.
      • 🤝 Если модель решила передать задачу другому агенту — делаем это, и повторяем всё по кругу.
      • 🛠️ Если модель решила вызвать инструмент (например, посчитать что-то или залезть в базу), – запускаем его, добавляем результат, и снова повторяем.

    Это может повторяться несколько раз, но если циклов стало больше, чем max_turns, — вылетит ошибка MaxTurnsExceeded.


    🌊 А что такое стриминг?

    Если используешь run_streamed(), то ответ от модели поступает порционно, как "водопад", пока модель думает. Это похоже на то, как GPT в чате пишет строку за строкой. Можно отслеживать поток событий с .stream_events().


    ⚙️ Настройки (run_config)

    Есть параметр run_config, через который можно гибко настроить поведение раннера:

    • model – какую модель использовать (можно указать одну модель на всех агентов).
    • model_settings – изменить параметры вроде temperature, top_p и т.п.
    • guardrails – можно поставить фильтры на вход и выход, чтобы не прошёл "плохой" контент.
    • trace – включить отслеживание всего, что делает агент (например, чтобы потом проанализировать).
    • trace_metadata – добавить дополнительную информацию к отслеживанию.

    💬 Как вести диалог с пользователем?

    Вы можете запускать агента несколько раз, как серии ходов в беседе:

    async def main():
        agent = Agent(name="Assistant", instructions="Отвечай очень кратко.")
        
        # Первый вопрос
        result = await Runner.run(agent, "В каком городе мост Золотые Ворота?")
        print(result.final_output)  # → San Francisco
    
        # Второй вопрос, продолжение беседы
        new_input = result.to_input_list() + [{"role": "user", "content": "А в каком штате?"}]
        result = await Runner.run(agent, new_input)
        print(result.final_output)  # → California
    

    🚨 Обработка ошибок

    Иногда случаются ошибки. В SDK есть предопределенные исключения:

    • AgentsException – базовая ошибка.
    • MaxTurnsExceeded – слишком много циклов, агент не дал финального ответа.
    • ModelBehaviorError – модель выдала некорректный результат (например, сломанный JSON).
    • UserError – ошибка в коде пользователя.
    • InputGuardrailTripwireTriggered / OutputGuardrailTripwireTriggered – нарушены условия входа или выхода (например, текст содержит запрещённые слова).

    🧠 Примерно как это работает внутри

    Можно представить себе, как "работает мыслительный процесс" у агента:

    — пользователь задал вопрос → агент подумал →
    возможно, решил использовать инструмент →
    потом решил передать задачу другому агенту →
    тот подумал → выдал ответ → получаем результат.


    📦 Вывод

    Эта система позволяет строить умных агентов, которые:

    • могут долго и разумно размышлять над задачей,
    • используют инструменты,
    • могут помогать пользователям по-настоящему гибко,
    • и всё это удобно контролировать через Runner.

    Если ты хочешь сделать более интеллектуального чат-бота, или модель, которая умеет размышлять, обращаться к функциям, делить задачи между «субагентами» — этот SDK тебе подойдёт.

    Хочешь — помогу сделать свой первый полноценный пример 😉


    Если нужно объяснить какой-то конкретный момент еще проще — пиши!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.