Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions docs/edge/ar/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -523,6 +523,100 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

تركز بنية نظام الاستمرارية على الدقة التقنية وخيارات التخصيص، مما يتيح للمطورين الحفاظ على التحكم الكامل في إدارة الحالة مع الاستفادة من ميزات الموثوقية المدمجة.

## جمع المدخلات باستخدام `ask()`

يوقف `ask()` طريقة التدفق قيد التنفيذ حتى تصل الإجابة. الافتراضي هو القراءة من الطرفية، وهذا
يزعج في الاختبارات. **مزوّد المدخلات** يستبدل الطرفية: أي كائن يملك
`request_input(message, flow, metadata=None)` يفي بالغرض، فيمكنك ربط واجهة أو طابور أو قائمة
نصية دون تغيير التدفق.

يستطيع المزوّد قراءة `metadata` الخاصة بالطلب، والرد بكائن `InputResponse` يحمل بيانات وصفية
خاصة به. يعيد `ask()` النص دائمًا (أو `None` عند عدم توفر إجابة)، وتُحفظ البيانات الوصفية
للاتجاهين في `flow.input_history`.

```python scripted_input.py
from typing import Any

from crewai.flow import Flow, start
from crewai.flow.input_provider import InputResponse


class ScriptedProvider:
"""مزوّد حتمي: يعيد إجابات معدة مسبقًا ثم يعلن عدم توفر مدخلات."""

def __init__(self, answers: list[str | None]) -> None:
self._answers = list(answers)
self.received_metadata: list[dict[str, Any] | None] = []

def request_input(
self,
message: str,
flow: Flow,
metadata: dict[str, Any] | None = None,
) -> str | None:
self.received_metadata.append(metadata)
if not self._answers:
return None
answer = self._answers.pop(0)
if answer is None:
return None
return InputResponse(
text=answer,
metadata={"source": "script", "prompt": message},
)


provider = ScriptedProvider(["CrewAI", None])


class SurveyFlow(Flow):
input_provider = provider

@start()
def gather(self):
# البيانات الوصفية للطلب تصل إلى المزوّد.
topic = self.ask(
"What topic should we research?",
metadata={"channel": "#research"},
)
print("topic:", topic)

# المزوّد الذي لا يملك إجابة يعيد None، وهذا ليس إجابة.
extra = self.ask("Anything else?")
if extra is None:
print("no further input available, using the fallback")
extra = "(none)"
return f"{topic} / {extra}"


flow = SurveyFlow()
print("result:", flow.kickoff())

for entry in flow.input_history:
print(entry["message"], "->", entry["response"], "|", entry["response_metadata"])
```

عند التشغيل ستظهر النتيجة التالية:

```text
topic: CrewAI
no further input available, using the fallback
result: CrewAI / (none)
What topic should we research? -> CrewAI | {'source': 'script', 'prompt': 'What topic should we research?'}
Anything else? -> None | None
```

هناك أمران يستحقان الانتباه. وصلت البيانات الوصفية للسؤال الثاني إلى المزوّد رغم أنه لم يملك
إجابة، وكل عنصر في `flow.input_history` يحتفظ بـ `message` و`response` و`method_name`
و`timestamp` و`metadata` (الطلب) و`response_metadata` (الإجابة). ويعيد `input_history` نسخة،
فتعديلها لا يغيّر ما سجّله التدفق.

يعالج `ask()` و`handle_turn()` مشكلتين مختلفتين. يوقف `ask()` **خطوة قيد التنفيذ** ويعيد نصًا
إلى تلك الطريقة. أما `handle_turn()` فيبدأ **جولة محادثة** في التدفق: يوجّه الرسالة وينفّذ
المستمعين المطابقين ويضيف إلى سجل المحادثة. استخدم `ask()` لسؤال داخل خطوة في سير عمل،
و`handle_turn()` عندما يكون التدفق كله محادثة. راجع
[التدفقات الحوارية](/ar/guides/flows/conversational-flows) للحالة الثانية.

## التحكم في التدفق

### المنطق الشرطي: `or`
Expand Down
5 changes: 5 additions & 0 deletions docs/edge/ar/guides/flows/conversational-flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ mode: "wide"
| اكتمال الجولة | مع `trace_scope="turn"`: ‏`conversation_turn_completed` و`FlowFinished` لكل جولة ناجحة؛ و`FlowFailed` عند الفشل |
| تتبع الجلسة الكامل | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |

إذا كان تدفقك يحتاج إلى طرح سؤال **داخل** خطوة واحدة بدلًا من بدء جولة، فاستخدم `Flow.ask()`
مع مزوّد مدخلات بدلًا من `handle_turn()`. راجع
[جمع المدخلات باستخدام `ask()`](/ar/concepts/flows#collecting-input-with-ask) لمعرفة الفرق
والحصول على مزوّد قابل للتشغيل.

## واجهات الجولات

استخدم **`flow.handle_turn(message, session_id=...)`** لكل رسالة مستخدم من REST أو WebSocket أو الاختبارات أو الواجهات المخصصة. استخدم **`flow.chat()`** عندما تريد حلقة دردشة محلية في الطرفية لـ `Flow` محادثي.
Expand Down
96 changes: 96 additions & 0 deletions docs/edge/en/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,102 @@ If the supplied `restore_from_state_id` does not match any persisted state, the

The persistence system's architecture emphasizes technical precision and customization options, allowing developers to maintain full control over state management while benefiting from built-in reliability features.

## Collecting Input with `ask()`

`ask()` pauses the running flow method until an answer arrives. By default it reads from the
console, which makes tests awkward. A custom **input provider** replaces the console: any
object with `request_input(message, flow, metadata=None)` works, so you can wire a UI, a
queue, or a scripted list without changing the flow.

The provider can read the request `metadata` and can answer with an `InputResponse` that
carries metadata of its own. `ask()` always returns the text (or `None` when no answer is
available); the metadata of both directions is kept on `flow.input_history`.

```python scripted_input.py
from typing import Any

from crewai.flow import Flow, start
from crewai.flow.input_provider import InputResponse


class ScriptedProvider:
"""Deterministic provider: replays a list of answers, then reports no input."""

def __init__(self, answers: list[str | None]) -> None:
self._answers = list(answers)
self.received_metadata: list[dict[str, Any] | None] = []

def request_input(
self,
message: str,
flow: Flow,
metadata: dict[str, Any] | None = None,
) -> str | None:
self.received_metadata.append(metadata)
if not self._answers:
return None
answer = self._answers.pop(0)
if answer is None:
return None
return InputResponse(
text=answer,
metadata={"source": "script", "prompt": message},
)


provider = ScriptedProvider(["CrewAI", None])


class SurveyFlow(Flow):
input_provider = provider

@start()
def gather(self):
# The request metadata reaches the provider.
topic = self.ask(
"What topic should we research?",
metadata={"channel": "#research"},
)
print("topic:", topic)

# A provider with nothing to say returns None; that is not an answer.
extra = self.ask("Anything else?")
if extra is None:
print("no further input available, using the fallback")
extra = "(none)"
return f"{topic} / {extra}"


flow = SurveyFlow()
print("result:", flow.kickoff())

for entry in flow.input_history:
print(entry["message"], "->", entry["response"], "|", entry["response_metadata"])
```

Run it and you should see:

```text
topic: CrewAI
no further input available, using the fallback
result: CrewAI / (none)
What topic should we research? -> CrewAI | {'source': 'script', 'prompt': 'What topic should we research?'}
Anything else? -> None | None
```

Two things are worth calling out. The provider still received the request metadata for the
second question even though it had no answer, and each entry in `flow.input_history` keeps
`message`, `response`, `method_name`, `timestamp`, `metadata` (request) and
`response_metadata` (answer) — `input_history` returns a copy, so editing it does not change
what the flow recorded.

`ask()` and `handle_turn()` solve different problems. `ask()` blocks a **step that is already
running** and returns a string to that method. `handle_turn()` starts a **conversational
turn** on the Flow: it routes the message, runs the matching listeners, and appends to the
conversation history. Use `ask()` for a question inside a workflow step; use
`handle_turn()` when the whole flow is a chat. See
[Conversational Flows](/en/guides/flows/conversational-flows) for the latter.

## Flow Control

### Conditional Logic: `or`
Expand Down
2 changes: 2 additions & 0 deletions docs/edge/en/guides/flows/conversational-flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ The examples below opt into `ConversationConfig(trace_scope="turn")`. Existing c
| Turn complete | With `trace_scope="turn"`: `conversation_turn_completed` and `FlowFinished` per successful turn; `FlowFailed` on failure |
| Full-session trace | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |

If your flow needs to ask a question **inside** a single step instead of starting a turn, use `Flow.ask()` with an input provider rather than `handle_turn()` — see [Collecting Input with `ask()`](/en/concepts/flows#collecting-input-with-ask) for the difference and a runnable provider.

## Turn APIs

Use **`flow.handle_turn(message, session_id=...)`** for every user message from REST, WebSocket, tests, and custom UIs. Use **`flow.chat()`** when you want a local terminal chat loop for a conversational `Flow`.
Expand Down
94 changes: 94 additions & 0 deletions docs/edge/ko/concepts/flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,100 @@ flow_2.kickoff(restore_from_state_id=flow_1.state.id)

영속성 시스템의 아키텍처는 기술적 정밀성과 맞춤화 옵션을 강조하여, 개발자가 내장된 신뢰성 기능의 이점을 누리면서 상태 관리에 대한 완전한 제어권을 유지할 수 있게 해줍니다.

## `ask()`로 입력 받기

`ask()`는 실행 중인 플로우 메서드를 답이 도착할 때까지 멈춥니다. 기본값은 콘솔 입력이라
테스트에서 다루기 불편합니다. **입력 제공자**를 지정하면 콘솔을 대체합니다.
`request_input(message, flow, metadata=None)`을 가진 객체라면 무엇이든 되므로, 플로우를
바꾸지 않고 UI, 큐, 미리 정한 목록을 연결할 수 있습니다.

제공자는 요청 `metadata`를 읽을 수 있고, 자체 메타데이터를 담은 `InputResponse`로 답할 수
있습니다. `ask()`는 항상 텍스트를 반환하며(답이 없으면 `None`), 양방향 메타데이터는
`flow.input_history`에 남습니다.

```python scripted_input.py
from typing import Any

from crewai.flow import Flow, start
from crewai.flow.input_provider import InputResponse


class ScriptedProvider:
"""결정적 제공자: 정해진 답을 순서대로 재생하고, 없으면 입력 없음을 알립니다."""

def __init__(self, answers: list[str | None]) -> None:
self._answers = list(answers)
self.received_metadata: list[dict[str, Any] | None] = []

def request_input(
self,
message: str,
flow: Flow,
metadata: dict[str, Any] | None = None,
) -> str | None:
self.received_metadata.append(metadata)
if not self._answers:
return None
answer = self._answers.pop(0)
if answer is None:
return None
return InputResponse(
text=answer,
metadata={"source": "script", "prompt": message},
)


provider = ScriptedProvider(["CrewAI", None])


class SurveyFlow(Flow):
input_provider = provider

@start()
def gather(self):
# 요청 메타데이터가 제공자에게 전달됩니다.
topic = self.ask(
"What topic should we research?",
metadata={"channel": "#research"},
)
print("topic:", topic)

# 답할 것이 없는 제공자는 None을 반환하며, 이는 답이 아닙니다.
extra = self.ask("Anything else?")
if extra is None:
print("no further input available, using the fallback")
extra = "(none)"
return f"{topic} / {extra}"


flow = SurveyFlow()
print("result:", flow.kickoff())

for entry in flow.input_history:
print(entry["message"], "->", entry["response"], "|", entry["response_metadata"])
```

실행하면 다음과 같이 출력됩니다:

```text
topic: CrewAI
no further input available, using the fallback
result: CrewAI / (none)
What topic should we research? -> CrewAI | {'source': 'script', 'prompt': 'What topic should we research?'}
Anything else? -> None | None
```

두 가지를 짚어 둘 만합니다. 제공자는 두 번째 질문에 답이 없었는데도 요청 메타데이터를
받았고, `flow.input_history`의 각 항목은 `message`, `response`, `method_name`, `timestamp`,
`metadata`(요청), `response_metadata`(답변)를 유지합니다. `input_history`는 복사본을
반환하므로 수정해도 플로우가 기록한 내용은 바뀌지 않습니다.

`ask()`와 `handle_turn()`은 서로 다른 문제를 풉니다. `ask()`는 **이미 실행 중인 단계**를
블록하고 그 메서드에 문자열을 반환합니다. `handle_turn()`은 플로우에서 **대화 턴**을
시작하여 메시지를 라우팅하고 일치하는 리스너를 실행하며 대화 기록에 추가합니다. 워크플로
단계 안의 질문에는 `ask()`를, 전체 플로우가 채팅이라면 `handle_turn()`을 사용하십시오.
후자는 [대화형 플로우](/ko/guides/flows/conversational-flows)를 참고하십시오.

## 흐름 제어

### 조건부 로직: `or`
Expand Down
4 changes: 4 additions & 0 deletions docs/edge/ko/guides/flows/conversational-flows.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ mode: "wide"
| 턴 완료 | `trace_scope="turn"`일 때 성공한 턴마다 `conversation_turn_completed`와 `FlowFinished`; 실패하면 `FlowFailed` |
| 세션 전체 트레이스 | `ConversationConfig(defer_trace_finalization=True)` + `finalize_session_traces()` |

한 걸음 **내부**에서 질문을 해야 하고 턴을 시작하고 싶지 않다면 `handle_turn()` 대신
입력 제공자와 함께 `Flow.ask()`를 사용하십시오. 차이점과 실행 가능한 제공자는
[`ask()`로 입력 받기](/ko/concepts/flows#collecting-input-with-ask)를 참고하십시오.

## 턴 API

REST, WebSocket, 테스트, 커스텀 UI에서 오는 모든 사용자 메시지에는 **`flow.handle_turn(message, session_id=...)`**를 사용하세요. 대화형 `Flow`를 로컬 터미널 채팅 루프로 실행하고 싶을 때는 **`flow.chat()`**을 사용하세요.
Expand Down
Loading