コンテンツにスキップ

APIリファレンス

このページでは、mkdocstringsプラグインを使用してagents_sdk_modelsパッケージのAPIリファレンスを自動生成します。

Agents SDK Models エージェントSDKモデル

AgentPipeline

AgentPipeline class for managing the generation and evaluation of content using OpenAI Agents SDK OpenAI Agents SDKを使用してコンテンツの生成と評価を管理するパイプラインクラス

.. deprecated:: 0.0.22 AgentPipeline is deprecated and will be removed in v0.1.0. Use GenAgent with Flow/Step architecture instead. See migration guide: docs/deprecation_plan.md

This class handles: このクラスは以下を処理します: - Content generation using instructions / instructionsを使用したコンテンツ生成 - Content evaluation with scoring / スコアリングによるコンテンツ評価 - Session history management / セッション履歴の管理 - Output formatting and routing / 出力のフォーマットとルーティング

Preferred alternative: 推奨代替手段: - Use GenAgent for single-step pipeline functionality - Use Flow/Step architecture for complex workflows - See examples/gen_agent_example.py for migration examples

Source code in src\agents_sdk_models\pipeline.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
class AgentPipeline:
    """
    AgentPipeline class for managing the generation and evaluation of content using OpenAI Agents SDK
    OpenAI Agents SDKを使用してコンテンツの生成と評価を管理するパイプラインクラス

    .. deprecated:: 0.0.22
       AgentPipeline is deprecated and will be removed in v0.1.0. 
       Use GenAgent with Flow/Step architecture instead.
       See migration guide: docs/deprecation_plan.md

    This class handles:
    このクラスは以下を処理します:
    - Content generation using instructions / instructionsを使用したコンテンツ生成
    - Content evaluation with scoring / スコアリングによるコンテンツ評価
    - Session history management / セッション履歴の管理
    - Output formatting and routing / 出力のフォーマットとルーティング

    Preferred alternative:
    推奨代替手段:
    - Use GenAgent for single-step pipeline functionality
    - Use Flow/Step architecture for complex workflows
    - See examples/gen_agent_example.py for migration examples
    """

    def __init__(
        self,
        name: str,
        generation_instructions: str,
        evaluation_instructions: Optional[str],
        *,
        input_guardrails: Optional[list] = None,
        output_guardrails: Optional[list] = None,
        output_model: Optional[Type[Any]] = None,
        model: str | None = None,
        evaluation_model: str | None = None,
        generation_tools: Optional[list] = None,
        evaluation_tools: Optional[list] = None,
        routing_func: Optional[Callable[[Any], Any]] = None,
        session_history: Optional[list] = None,
        history_size: int = 10,
        threshold: int = 85,
        retries: int = 3,
        improvement_callback: Optional[Callable[[Any, EvaluationResult], None]] = None,
        dynamic_prompt: Optional[Callable[[str], str]] = None,
        retry_comment_importance: Optional[list[str]] = None,
        locale: str = "en",
    ) -> None:
        """
        Initialize the Pipeline with configuration parameters
        設定パラメータでパイプラインを初期化する

        .. deprecated:: 0.0.22
           AgentPipeline is deprecated and will be removed in v0.1.0. 
           Use GenAgent with Flow/Step architecture instead.
           See migration guide: docs/deprecation_plan.md

        Args:
            name: Pipeline name / パイプライン名
            generation_instructions: System prompt for generation / 生成用システムプロンプト
            evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
            input_guardrails: Guardrails for generation / 生成用ガードレール
            output_guardrails: Guardrails for evaluation / 評価用ガードレール
            output_model: Model for output formatting / 出力フォーマット用モデル
            model: LLM model name / LLMモデル名
            evaluation_model: Optional LLM model name for evaluation; if None, uses model. 日本語: 評価用のLLMモデル名(Noneの場合はmodelを使用)
            generation_tools: Tools for generation / 生成用ツール
            evaluation_tools: Tools for evaluation / 評価用ツール
            routing_func: Function for output routing / 出力ルーティング用関数
            session_history: Session history / セッション履歴
            history_size: Size of history to keep / 保持する履歴サイズ
            threshold: Evaluation score threshold / 評価スコアの閾値
            retries: Number of retry attempts / リトライ試行回数
            improvement_callback: Callback for improvement suggestions / 改善提案用コールバック
            dynamic_prompt: Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)
            retry_comment_importance: Importance levels of comments to include on retry / リトライ時にプロンプトに含めるコメントの重大度レベル(任意)
            locale: Language code for localized messages ("en" or "ja")
        """
        import warnings
        warnings.warn(
            "AgentPipeline is deprecated and will be removed in v0.1.0. "
            "Use GenAgent with Flow/Step architecture instead. "
            "See migration guide: docs/deprecation_plan.md",
            DeprecationWarning,
            stacklevel=2
        )
        self.name = name
        self.generation_instructions = generation_instructions.strip()
        self.evaluation_instructions = evaluation_instructions.strip() if evaluation_instructions else None
        self.output_model = output_model

        self.model = model
        self.evaluation_model = evaluation_model
        self.generation_tools = generation_tools or []
        self.evaluation_tools = evaluation_tools or []
        self.input_guardrails = input_guardrails or []
        self.output_guardrails = output_guardrails or []
        self.routing_func = routing_func
        self.session_history = session_history if session_history is not None else []
        self.history_size = history_size
        self.threshold = threshold
        self.retries = retries
        self.improvement_callback = improvement_callback
        self.dynamic_prompt = dynamic_prompt
        self.retry_comment_importance = retry_comment_importance or []
        # Language code for localized messages ("en" or "ja")
        self.locale = locale

        # English: Get generation LLM instance; default tracing setting applied in get_llm
        # 日本語: 生成用LLMインスタンスを取得します。tracing設定はget_llm側でデフォルト値を使用
        llm = get_llm(model) if model else None
        # English: Determine evaluation LLM instance, fallback to generation model if evaluation_model is None
        # 日本語: 評価用LLMインスタンスを決定。evaluation_modelがNoneの場合は生成モデルを使用
        eval_source = evaluation_model if evaluation_model else model
        llm_eval = get_llm(eval_source) if eval_source else None

        # Agents ---------------------------------------------------------
        self.gen_agent = Agent(
            name=f"{name}_generator",
            model=llm,
            tools=self.generation_tools,
            instructions=self.generation_instructions,
            input_guardrails=self.input_guardrails,
        )

        # Localized evaluation format instructions
        format_header = get_message("eval_output_format_header", self.locale)
        schema_instruction = get_message("eval_json_schema_instruction", self.locale)
        # JSON schema remains unlocalized
        json_schema = textwrap.dedent("""\
        {
            "score": int(0~100),
            "comment": [
                {
                    "importance": "serious" | "normal" | "minor",  # Importance field / 重要度フィールド
                    "content": str  # Comment content / コメント内容
                }
            ]
        }
        """)
        json_instr = "\n".join(["+----", format_header, schema_instruction, json_schema])
        self.eval_agent = (
            Agent(
                name=f"{name}_evaluator",
                model=llm_eval,
                tools=self.evaluation_tools,
                instructions=self.evaluation_instructions + json_instr,
                output_guardrails=self.output_guardrails,
            )
            if self.evaluation_instructions
            else None
        )

        self._runner = Runner()
        self._pipeline_history: List[Dict[str, str]] = []

    # ------------------------------------------------------------------
    # helpers
    # ------------------------------------------------------------------

    def _build_generation_prompt(self, user_input: str) -> str:
        """
        Build the prompt for content generation
        コンテンツ生成用のプロンプトを構築する

        Args:
            user_input: User input text / ユーザー入力テキスト

        Returns:
            str: Formatted prompt for generation / 生成用のフォーマット済みプロンプト
        """
        recent = "\n".join(f"User: {h['input']}\nAI: {h['output']}"
                          for h in self._pipeline_history[-self.history_size:])
        session = "\n".join(self.session_history)
        # Use localized prefix for user input
        prefix = get_message("user_input_prefix", self.locale)
        return "\n".join(filter(None, [session, recent, f"{prefix} {user_input}"]))

    def _build_evaluation_prompt(self, user_input: str, generated_output: str) -> str:
        """
        Build the prompt for content evaluation
        コンテンツ評価用のプロンプトを構築する

        Args:
            user_input: Original user input / 元のユーザー入力
            generated_output: Generated content to evaluate / 評価対象の生成コンテンツ

        Returns:
            str: Formatted prompt for evaluation / 評価用のフォーマット済みプロンプト
        """
        parts = []

        # Add evaluation instructions if provided
        # 評価指示が提供されている場合は追加
        if self.evaluation_instructions:
            parts.append(self.evaluation_instructions)

        parts.extend([
            "----",
            f"ユーザー入力:\n{user_input}",
            "----",
            f"生成結果:\n{generated_output}",
            "上記を JSON で必ず次の形式にしてください"
        ])
        return "\n".join(filter(None, parts)).strip()

    @staticmethod
    def _extract_json(text: str) -> Dict[str, Any]:
        """
        Extract JSON from text
        テキストからJSONを抽出する

        Args:
            text: Text containing JSON / JSONを含むテキスト

        Returns:
            Dict[str, Any]: Extracted JSON data / 抽出されたJSONデータ

        Raises:
            ValueError: If JSON is not found in text / テキスト内にJSONが見つからない場合
        """
        match = re.search(r"\{.*\}", text, re.S)
        if not match:
            raise ValueError("JSON not found in evaluation output")
        return json.loads(match.group(0))

    def _coerce_output(self, text: str):
        """
        Convert output to specified model format
        出力を指定されたモデル形式に変換する

        Args:
            text: Output text to convert / 変換対象の出力テキスト

        Returns:
            Any: Converted output in specified format / 指定された形式の変換済み出力
        """
        if self.output_model is None:
            return text
        try:
            data = json.loads(text)
        except json.JSONDecodeError:
            return text
        try:
            if isinstance(self.output_model, type) and issubclass(self.output_model, BaseModel):
                return self.output_model.model_validate(data)
            if is_dataclass(self.output_model):
                return self.output_model(**data)
            return self.output_model(**data)
        except Exception:
            return text

    def _append_to_session(self, user_input: str, raw_output: str):
        """
        Append interaction to session history
        セッション履歴にインタラクションを追加する

        Args:
            user_input: User input text / ユーザー入力テキスト
            raw_output: Generated output text / 生成された出力テキスト
        """
        if self.session_history is None:
            return
        self.session_history.append(f"User: {user_input}\nAI: {raw_output}")

    def _route(self, parsed_output):
        """
        Route the parsed output through routing function if specified
        指定されている場合、パース済み出力をルーティング関数で処理する

        Args:
            parsed_output: Parsed output to route / ルーティング対象のパース済み出力

        Returns:
            Any: Routed output / ルーティング済み出力
        """
        return self.routing_func(parsed_output) if self.routing_func else parsed_output

    # ------------------------------------------------------------------
    # public
    # ------------------------------------------------------------------

    def run(self, user_input: str):
        """
        Run the pipeline with user input
        ユーザー入力でパイプラインを実行する

        Args:
            user_input: User input text / ユーザー入力テキスト

        Returns:
            Any: Processed output or None if evaluation fails / 処理済み出力、または評価失敗時はNone
        """
        attempt = 0
        last_eval_result: Optional[EvaluationResult] = None  # Store last evaluation result for retry
        while attempt <= self.retries:
            # ---------------- Generation ----------------
            # On retry, include prior evaluation comments if configured
            if attempt > 0 and last_eval_result and self.retry_comment_importance:
                # Filter comments by importance
                try:
                    comments = [c for c in last_eval_result.comment if c.get("importance") in self.retry_comment_importance]
                except Exception:
                    comments = []
                # Format serious comments with header
                # Localized header for evaluation feedback
                feedback_header = get_message("evaluation_feedback_header", self.locale)
                # English: Format each comment line. 日本語: 各コメント行をフォーマット
                formatted_comments = [f"- ({c.get('importance')}) {c.get('content')}" for c in comments]
                # English: Combine header and comment lines. 日本語: ヘッダーとコメント行を結合
                comment_block = "\n".join([feedback_header] + formatted_comments)
            else:
                comment_block = ""
            # Build base prompt
            if attempt > 0 and comment_block:
                if self.dynamic_prompt:
                    # English: Use dynamic prompt if provided. 日本語: dynamic_promptがあればそれを使用
                    gen_prompt = self.dynamic_prompt(user_input)
                else:
                    # Localized header for AI history
                    ai_history_header = get_message("ai_history_header", self.locale)
                    # English: Extract AI outputs from pipeline history, omit user inputs. 日本語: パイプライン履歴からAIの出力のみ取得
                    ai_outputs = "\n".join(h["output"] for h in self._pipeline_history[-self.history_size:])
                    # Localized prefix for user input line
                    prefix = get_message("user_input_prefix", self.locale)
                    # English: Current user input line. 日本語: 現在のユーザー入力行
                    user_input_line = f"{prefix} {user_input}"
                    # English: Combine AI outputs, feedback, and current user input. 日本語: AI出力、フィードバック、現在のユーザー入力を結合
                    gen_prompt = "\n\n".join([ai_history_header, ai_outputs, comment_block, user_input_line])
            else:
                if self.dynamic_prompt:
                    gen_prompt = self.dynamic_prompt(user_input)
                else:
                    gen_prompt = self._build_generation_prompt(user_input)

            gen_result = self._runner.run_sync(self.gen_agent, gen_prompt)
            raw_output_text = getattr(gen_result, "final_output", str(gen_result))
            if hasattr(gen_result, "tool_calls") and gen_result.tool_calls:
                raw_output_text = str(gen_result.tool_calls[0].call())

            parsed_output = self._coerce_output(raw_output_text)
            self._pipeline_history.append({"input": user_input, "output": raw_output_text})

            # ---------------- Evaluation ----------------
            if not self.eval_agent:
                return self._route(parsed_output)

            eval_prompt = self._build_evaluation_prompt(user_input, raw_output_text)

            eval_raw = self._runner.run_sync(self.eval_agent, eval_prompt)
            eval_text = getattr(eval_raw, "final_output", str(eval_raw))
            try:
                eval_dict = self._extract_json(eval_text)
                eval_result = EvaluationResult(**eval_dict)
            except Exception:
                eval_result = EvaluationResult(score=0, comment=[Comment(importance=CommentImportance.SERIOUS, content="評価 JSON の解析に失敗")])

            if eval_result.score >= self.threshold:
                self._append_to_session(user_input, raw_output_text)
                return self._route(parsed_output)

            # Store for next retry
            last_eval_result = eval_result
            attempt += 1

        if self.improvement_callback:
            self.improvement_callback(parsed_output, eval_result)
        return None

__init__(name, generation_instructions, evaluation_instructions, *, input_guardrails=None, output_guardrails=None, output_model=None, model=None, evaluation_model=None, generation_tools=None, evaluation_tools=None, routing_func=None, session_history=None, history_size=10, threshold=85, retries=3, improvement_callback=None, dynamic_prompt=None, retry_comment_importance=None, locale='en')

Initialize the Pipeline with configuration parameters 設定パラメータでパイプラインを初期化する

.. deprecated:: 0.0.22 AgentPipeline is deprecated and will be removed in v0.1.0. Use GenAgent with Flow/Step architecture instead. See migration guide: docs/deprecation_plan.md

Parameters:

Name Type Description Default
name str

Pipeline name / パイプライン名

required
generation_instructions str

System prompt for generation / 生成用システムプロンプト

required
evaluation_instructions Optional[str]

System prompt for evaluation / 評価用システムプロンプト

required
input_guardrails Optional[list]

Guardrails for generation / 生成用ガードレール

None
output_guardrails Optional[list]

Guardrails for evaluation / 評価用ガードレール

None
output_model Optional[Type[Any]]

Model for output formatting / 出力フォーマット用モデル

None
model str | None

LLM model name / LLMモデル名

None
evaluation_model str | None

Optional LLM model name for evaluation; if None, uses model. 日本語: 評価用のLLMモデル名(Noneの場合はmodelを使用)

None
generation_tools Optional[list]

Tools for generation / 生成用ツール

None
evaluation_tools Optional[list]

Tools for evaluation / 評価用ツール

None
routing_func Optional[Callable[[Any], Any]]

Function for output routing / 出力ルーティング用関数

None
session_history Optional[list]

Session history / セッション履歴

None
history_size int

Size of history to keep / 保持する履歴サイズ

10
threshold int

Evaluation score threshold / 評価スコアの閾値

85
retries int

Number of retry attempts / リトライ試行回数

3
improvement_callback Optional[Callable[[Any, EvaluationResult], None]]

Callback for improvement suggestions / 改善提案用コールバック

None
dynamic_prompt Optional[Callable[[str], str]]

Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)

None
retry_comment_importance Optional[list[str]]

Importance levels of comments to include on retry / リトライ時にプロンプトに含めるコメントの重大度レベル(任意)

None
locale str

Language code for localized messages ("en" or "ja")

'en'
Source code in src\agents_sdk_models\pipeline.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def __init__(
    self,
    name: str,
    generation_instructions: str,
    evaluation_instructions: Optional[str],
    *,
    input_guardrails: Optional[list] = None,
    output_guardrails: Optional[list] = None,
    output_model: Optional[Type[Any]] = None,
    model: str | None = None,
    evaluation_model: str | None = None,
    generation_tools: Optional[list] = None,
    evaluation_tools: Optional[list] = None,
    routing_func: Optional[Callable[[Any], Any]] = None,
    session_history: Optional[list] = None,
    history_size: int = 10,
    threshold: int = 85,
    retries: int = 3,
    improvement_callback: Optional[Callable[[Any, EvaluationResult], None]] = None,
    dynamic_prompt: Optional[Callable[[str], str]] = None,
    retry_comment_importance: Optional[list[str]] = None,
    locale: str = "en",
) -> None:
    """
    Initialize the Pipeline with configuration parameters
    設定パラメータでパイプラインを初期化する

    .. deprecated:: 0.0.22
       AgentPipeline is deprecated and will be removed in v0.1.0. 
       Use GenAgent with Flow/Step architecture instead.
       See migration guide: docs/deprecation_plan.md

    Args:
        name: Pipeline name / パイプライン名
        generation_instructions: System prompt for generation / 生成用システムプロンプト
        evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
        input_guardrails: Guardrails for generation / 生成用ガードレール
        output_guardrails: Guardrails for evaluation / 評価用ガードレール
        output_model: Model for output formatting / 出力フォーマット用モデル
        model: LLM model name / LLMモデル名
        evaluation_model: Optional LLM model name for evaluation; if None, uses model. 日本語: 評価用のLLMモデル名(Noneの場合はmodelを使用)
        generation_tools: Tools for generation / 生成用ツール
        evaluation_tools: Tools for evaluation / 評価用ツール
        routing_func: Function for output routing / 出力ルーティング用関数
        session_history: Session history / セッション履歴
        history_size: Size of history to keep / 保持する履歴サイズ
        threshold: Evaluation score threshold / 評価スコアの閾値
        retries: Number of retry attempts / リトライ試行回数
        improvement_callback: Callback for improvement suggestions / 改善提案用コールバック
        dynamic_prompt: Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)
        retry_comment_importance: Importance levels of comments to include on retry / リトライ時にプロンプトに含めるコメントの重大度レベル(任意)
        locale: Language code for localized messages ("en" or "ja")
    """
    import warnings
    warnings.warn(
        "AgentPipeline is deprecated and will be removed in v0.1.0. "
        "Use GenAgent with Flow/Step architecture instead. "
        "See migration guide: docs/deprecation_plan.md",
        DeprecationWarning,
        stacklevel=2
    )
    self.name = name
    self.generation_instructions = generation_instructions.strip()
    self.evaluation_instructions = evaluation_instructions.strip() if evaluation_instructions else None
    self.output_model = output_model

    self.model = model
    self.evaluation_model = evaluation_model
    self.generation_tools = generation_tools or []
    self.evaluation_tools = evaluation_tools or []
    self.input_guardrails = input_guardrails or []
    self.output_guardrails = output_guardrails or []
    self.routing_func = routing_func
    self.session_history = session_history if session_history is not None else []
    self.history_size = history_size
    self.threshold = threshold
    self.retries = retries
    self.improvement_callback = improvement_callback
    self.dynamic_prompt = dynamic_prompt
    self.retry_comment_importance = retry_comment_importance or []
    # Language code for localized messages ("en" or "ja")
    self.locale = locale

    # English: Get generation LLM instance; default tracing setting applied in get_llm
    # 日本語: 生成用LLMインスタンスを取得します。tracing設定はget_llm側でデフォルト値を使用
    llm = get_llm(model) if model else None
    # English: Determine evaluation LLM instance, fallback to generation model if evaluation_model is None
    # 日本語: 評価用LLMインスタンスを決定。evaluation_modelがNoneの場合は生成モデルを使用
    eval_source = evaluation_model if evaluation_model else model
    llm_eval = get_llm(eval_source) if eval_source else None

    # Agents ---------------------------------------------------------
    self.gen_agent = Agent(
        name=f"{name}_generator",
        model=llm,
        tools=self.generation_tools,
        instructions=self.generation_instructions,
        input_guardrails=self.input_guardrails,
    )

    # Localized evaluation format instructions
    format_header = get_message("eval_output_format_header", self.locale)
    schema_instruction = get_message("eval_json_schema_instruction", self.locale)
    # JSON schema remains unlocalized
    json_schema = textwrap.dedent("""\
    {
        "score": int(0~100),
        "comment": [
            {
                "importance": "serious" | "normal" | "minor",  # Importance field / 重要度フィールド
                "content": str  # Comment content / コメント内容
            }
        ]
    }
    """)
    json_instr = "\n".join(["+----", format_header, schema_instruction, json_schema])
    self.eval_agent = (
        Agent(
            name=f"{name}_evaluator",
            model=llm_eval,
            tools=self.evaluation_tools,
            instructions=self.evaluation_instructions + json_instr,
            output_guardrails=self.output_guardrails,
        )
        if self.evaluation_instructions
        else None
    )

    self._runner = Runner()
    self._pipeline_history: List[Dict[str, str]] = []

run(user_input)

Run the pipeline with user input ユーザー入力でパイプラインを実行する

Parameters:

Name Type Description Default
user_input str

User input text / ユーザー入力テキスト

required

Returns:

Name Type Description
Any

Processed output or None if evaluation fails / 処理済み出力、または評価失敗時はNone

Source code in src\agents_sdk_models\pipeline.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
def run(self, user_input: str):
    """
    Run the pipeline with user input
    ユーザー入力でパイプラインを実行する

    Args:
        user_input: User input text / ユーザー入力テキスト

    Returns:
        Any: Processed output or None if evaluation fails / 処理済み出力、または評価失敗時はNone
    """
    attempt = 0
    last_eval_result: Optional[EvaluationResult] = None  # Store last evaluation result for retry
    while attempt <= self.retries:
        # ---------------- Generation ----------------
        # On retry, include prior evaluation comments if configured
        if attempt > 0 and last_eval_result and self.retry_comment_importance:
            # Filter comments by importance
            try:
                comments = [c for c in last_eval_result.comment if c.get("importance") in self.retry_comment_importance]
            except Exception:
                comments = []
            # Format serious comments with header
            # Localized header for evaluation feedback
            feedback_header = get_message("evaluation_feedback_header", self.locale)
            # English: Format each comment line. 日本語: 各コメント行をフォーマット
            formatted_comments = [f"- ({c.get('importance')}) {c.get('content')}" for c in comments]
            # English: Combine header and comment lines. 日本語: ヘッダーとコメント行を結合
            comment_block = "\n".join([feedback_header] + formatted_comments)
        else:
            comment_block = ""
        # Build base prompt
        if attempt > 0 and comment_block:
            if self.dynamic_prompt:
                # English: Use dynamic prompt if provided. 日本語: dynamic_promptがあればそれを使用
                gen_prompt = self.dynamic_prompt(user_input)
            else:
                # Localized header for AI history
                ai_history_header = get_message("ai_history_header", self.locale)
                # English: Extract AI outputs from pipeline history, omit user inputs. 日本語: パイプライン履歴からAIの出力のみ取得
                ai_outputs = "\n".join(h["output"] for h in self._pipeline_history[-self.history_size:])
                # Localized prefix for user input line
                prefix = get_message("user_input_prefix", self.locale)
                # English: Current user input line. 日本語: 現在のユーザー入力行
                user_input_line = f"{prefix} {user_input}"
                # English: Combine AI outputs, feedback, and current user input. 日本語: AI出力、フィードバック、現在のユーザー入力を結合
                gen_prompt = "\n\n".join([ai_history_header, ai_outputs, comment_block, user_input_line])
        else:
            if self.dynamic_prompt:
                gen_prompt = self.dynamic_prompt(user_input)
            else:
                gen_prompt = self._build_generation_prompt(user_input)

        gen_result = self._runner.run_sync(self.gen_agent, gen_prompt)
        raw_output_text = getattr(gen_result, "final_output", str(gen_result))
        if hasattr(gen_result, "tool_calls") and gen_result.tool_calls:
            raw_output_text = str(gen_result.tool_calls[0].call())

        parsed_output = self._coerce_output(raw_output_text)
        self._pipeline_history.append({"input": user_input, "output": raw_output_text})

        # ---------------- Evaluation ----------------
        if not self.eval_agent:
            return self._route(parsed_output)

        eval_prompt = self._build_evaluation_prompt(user_input, raw_output_text)

        eval_raw = self._runner.run_sync(self.eval_agent, eval_prompt)
        eval_text = getattr(eval_raw, "final_output", str(eval_raw))
        try:
            eval_dict = self._extract_json(eval_text)
            eval_result = EvaluationResult(**eval_dict)
        except Exception:
            eval_result = EvaluationResult(score=0, comment=[Comment(importance=CommentImportance.SERIOUS, content="評価 JSON の解析に失敗")])

        if eval_result.score >= self.threshold:
            self._append_to_session(user_input, raw_output_text)
            return self._route(parsed_output)

        # Store for next retry
        last_eval_result = eval_result
        attempt += 1

    if self.improvement_callback:
        self.improvement_callback(parsed_output, eval_result)
    return None

AgentPipelineStep

Bases: Step

Step that wraps AgentPipeline for use in Flow FlowでAgentPipelineを使用するためのラッパーステップ

This step allows using existing AgentPipeline instances as flow steps. このステップは既存のAgentPipelineインスタンスをフローステップとして使用できます。

Source code in src\agents_sdk_models\step.py
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
class AgentPipelineStep(Step):
    """
    Step that wraps AgentPipeline for use in Flow
    FlowでAgentPipelineを使用するためのラッパーステップ

    This step allows using existing AgentPipeline instances as flow steps.
    このステップは既存のAgentPipelineインスタンスをフローステップとして使用できます。
    """

    def __init__(self, name: str, pipeline: Any, next_step: Optional[str] = None):
        """
        Initialize agent pipeline step
        エージェントパイプラインステップを初期化

        Args:
            name: Step name / ステップ名
            pipeline: AgentPipeline instance / AgentPipelineインスタンス
            next_step: Next step after pipeline execution / パイプライン実行後の次ステップ
        """
        super().__init__(name)
        self.pipeline = pipeline
        self.next_step = next_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute agent pipeline step
        エージェントパイプラインステップを実行

        Args:
            user_input: User input / ユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        try:
            # Use the last user input if available
            # 利用可能な場合は最後のユーザー入力を使用
            input_text = user_input or ctx.last_user_input or ""

            # Execute pipeline in thread pool to handle sync methods
            # 同期メソッドを処理するためにスレッドプールでパイプラインを実行
            loop = asyncio.get_event_loop()
            with ThreadPoolExecutor() as executor:
                future = loop.run_in_executor(executor, self.pipeline.run, input_text)
                result = await future

            # Store result in context
            # 結果をコンテキストに保存
            if result is not None:
                ctx.prev_outputs[self.name] = result
                ctx.add_assistant_message(str(result))

        except Exception as e:
            ctx.add_system_message(f"Pipeline execution error in {self.name}: {e}")
            ctx.prev_outputs[self.name] = None

        # Set next step if specified
        # 指定されている場合は次ステップを設定
        if self.next_step:
            ctx.goto(self.next_step)

        return ctx

__init__(name, pipeline, next_step=None)

Initialize agent pipeline step エージェントパイプラインステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
pipeline Any

AgentPipeline instance / AgentPipelineインスタンス

required
next_step Optional[str]

Next step after pipeline execution / パイプライン実行後の次ステップ

None
Source code in src\agents_sdk_models\step.py
359
360
361
362
363
364
365
366
367
368
369
370
371
def __init__(self, name: str, pipeline: Any, next_step: Optional[str] = None):
    """
    Initialize agent pipeline step
    エージェントパイプラインステップを初期化

    Args:
        name: Step name / ステップ名
        pipeline: AgentPipeline instance / AgentPipelineインスタンス
        next_step: Next step after pipeline execution / パイプライン実行後の次ステップ
    """
    super().__init__(name)
    self.pipeline = pipeline
    self.next_step = next_step

run(user_input, ctx) async

Execute agent pipeline step エージェントパイプラインステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input / ユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute agent pipeline step
    エージェントパイプラインステップを実行

    Args:
        user_input: User input / ユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    try:
        # Use the last user input if available
        # 利用可能な場合は最後のユーザー入力を使用
        input_text = user_input or ctx.last_user_input or ""

        # Execute pipeline in thread pool to handle sync methods
        # 同期メソッドを処理するためにスレッドプールでパイプラインを実行
        loop = asyncio.get_event_loop()
        with ThreadPoolExecutor() as executor:
            future = loop.run_in_executor(executor, self.pipeline.run, input_text)
            result = await future

        # Store result in context
        # 結果をコンテキストに保存
        if result is not None:
            ctx.prev_outputs[self.name] = result
            ctx.add_assistant_message(str(result))

    except Exception as e:
        ctx.add_system_message(f"Pipeline execution error in {self.name}: {e}")
        ctx.prev_outputs[self.name] = None

    # Set next step if specified
    # 指定されている場合は次ステップを設定
    if self.next_step:
        ctx.goto(self.next_step)

    return ctx

ClarificationQuestion dataclass

Represents a clarification question from the pipeline パイプラインからの明確化質問を表現するクラス

Attributes:

Name Type Description
question str

The clarification question text / 明確化質問テキスト

turn int

Current turn number / 現在のターン番号

remaining_turns int

Remaining turns / 残りターン数

Source code in src\agents_sdk_models\clearify_pipeline.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
@dataclass
class ClarificationQuestion:
    """
    Represents a clarification question from the pipeline
    パイプラインからの明確化質問を表現するクラス

    Attributes:
        question: The clarification question text / 明確化質問テキスト
        turn: Current turn number / 現在のターン番号
        remaining_turns: Remaining turns / 残りターン数
    """
    question: str  # The clarification question text / 明確化質問テキスト
    turn: int  # Current turn number / 現在のターン番号
    remaining_turns: int  # Remaining turns / 残りターン数

    def __str__(self) -> str:
        """
        String representation of the clarification question
        明確化質問の文字列表現

        Returns:
            str: Formatted question with turn info / ターン情報付きフォーマット済み質問
        """
        return f"[ターン {self.turn}/{self.turn + self.remaining_turns}] {self.question}"

__str__()

String representation of the clarification question 明確化質問の文字列表現

Returns:

Name Type Description
str str

Formatted question with turn info / ターン情報付きフォーマット済み質問

Source code in src\agents_sdk_models\clearify_pipeline.py
73
74
75
76
77
78
79
80
81
def __str__(self) -> str:
    """
    String representation of the clarification question
    明確化質問の文字列表現

    Returns:
        str: Formatted question with turn info / ターン情報付きフォーマット済み質問
    """
    return f"[ターン {self.turn}/{self.turn + self.remaining_turns}] {self.question}"

ClaudeModel

Bases: OpenAIChatCompletionsModel

Anthropic Claude model implementation that extends OpenAI's chat completions model OpenAIのチャット補完モデルを拡張したAnthropic Claudeモデルの実装

Source code in src\agents_sdk_models\anthropic.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class ClaudeModel(OpenAIChatCompletionsModel):
    """
    Anthropic Claude model implementation that extends OpenAI's chat completions model
    OpenAIのチャット補完モデルを拡張したAnthropic Claudeモデルの実装
    """

    def __init__(
        self,
        model: str = "claude-3-5-sonnet-latest",
        temperature: float = 0.3,
        api_key: str = None,
        base_url: str = "https://api.anthropic.com/v1/",
        thinking: bool = False,
        **kwargs: Any,
    ) -> None:
        """
        Initialize the Anthropic Claude model with OpenAI compatible interface
        OpenAI互換インターフェースでAnthropic Claudeモデルを初期化する

        Args:
            model (str): Name of the Claude model to use (e.g. "claude-3-5-sonnet-latest")
                使用するClaudeモデルの名前(例:"claude-3-5-sonnet-latest")
            temperature (float): Sampling temperature between 0 and 1
                サンプリング温度(0から1の間)
            api_key (str): Anthropic API key
                Anthropic APIキー
            base_url (str): Base URL for the Anthropic OpenAI compatibility API
                Anthropic OpenAI互換APIのベースURL
            thinking (bool): Enable extended thinking for complex reasoning
                複雑な推論のための拡張思考を有効にする
            **kwargs: Additional arguments to pass to the OpenAI API
                OpenAI APIに渡す追加の引数
        """
        # get_llm経由で base_url が None の場合はデフォルトの URL を設定
        if base_url == None:
            base_url = "https://api.anthropic.com/v1/"

        # api_key が None の場合は環境変数から取得
        if api_key is None:
            api_key = os.environ.get("ANTHROPIC_API_KEY")
            if api_key is None:
                raise ValueError("Anthropic API key is required. Get one from https://console.anthropic.com/")

        # Create AsyncOpenAI client with Anthropic base URL
        # AnthropicのベースURLでAsyncOpenAIクライアントを作成
        openai_client = AsyncOpenAI(base_url=base_url, api_key=api_key)

        # Store the AsyncOpenAI client on the instance for direct access
        # テストで参照できるよう AsyncOpenAI クライアントをインスタンスに保存する
        self.openai_client = openai_client

        # Store parameters for later use in API calls
        # 後でAPIコールで使用するためにパラメータを保存
        self.temperature = temperature
        self.thinking = thinking
        self.kwargs = kwargs

        # Initialize the parent class with our custom client
        # カスタムクライアントで親クラスを初期化
        super().__init__(
            model=model,
            openai_client=openai_client
        )

    # Override methods that make API calls to include our parameters
    # APIコールを行うメソッドをオーバーライドして、パラメータを含める
    async def _create_chat_completion(self, *args, **kwargs):
        """Override to include temperature, thinking and other parameters"""
        kwargs["temperature"] = self.temperature

        # Add thinking parameter if enabled
        # 拡張思考が有効な場合はthinkingパラメータを追加
        if self.thinking:
            kwargs["thinking"] = True

        # Add any other custom parameters
        # その他のカスタムパラメータを追加
        kwargs.update(self.kwargs)

        return await super()._create_chat_completion(*args, **kwargs)

__init__(model='claude-3-5-sonnet-latest', temperature=0.3, api_key=None, base_url='https://api.anthropic.com/v1/', thinking=False, **kwargs)

Initialize the Anthropic Claude model with OpenAI compatible interface OpenAI互換インターフェースでAnthropic Claudeモデルを初期化する

Parameters:

Name Type Description Default
model str

Name of the Claude model to use (e.g. "claude-3-5-sonnet-latest") 使用するClaudeモデルの名前(例:"claude-3-5-sonnet-latest")

'claude-3-5-sonnet-latest'
temperature float

Sampling temperature between 0 and 1 サンプリング温度(0から1の間)

0.3
api_key str

Anthropic API key Anthropic APIキー

None
base_url str

Base URL for the Anthropic OpenAI compatibility API Anthropic OpenAI互換APIのベースURL

'https://api.anthropic.com/v1/'
thinking bool

Enable extended thinking for complex reasoning 複雑な推論のための拡張思考を有効にする

False
**kwargs Any

Additional arguments to pass to the OpenAI API OpenAI APIに渡す追加の引数

{}
Source code in src\agents_sdk_models\anthropic.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def __init__(
    self,
    model: str = "claude-3-5-sonnet-latest",
    temperature: float = 0.3,
    api_key: str = None,
    base_url: str = "https://api.anthropic.com/v1/",
    thinking: bool = False,
    **kwargs: Any,
) -> None:
    """
    Initialize the Anthropic Claude model with OpenAI compatible interface
    OpenAI互換インターフェースでAnthropic Claudeモデルを初期化する

    Args:
        model (str): Name of the Claude model to use (e.g. "claude-3-5-sonnet-latest")
            使用するClaudeモデルの名前(例:"claude-3-5-sonnet-latest")
        temperature (float): Sampling temperature between 0 and 1
            サンプリング温度(0から1の間)
        api_key (str): Anthropic API key
            Anthropic APIキー
        base_url (str): Base URL for the Anthropic OpenAI compatibility API
            Anthropic OpenAI互換APIのベースURL
        thinking (bool): Enable extended thinking for complex reasoning
            複雑な推論のための拡張思考を有効にする
        **kwargs: Additional arguments to pass to the OpenAI API
            OpenAI APIに渡す追加の引数
    """
    # get_llm経由で base_url が None の場合はデフォルトの URL を設定
    if base_url == None:
        base_url = "https://api.anthropic.com/v1/"

    # api_key が None の場合は環境変数から取得
    if api_key is None:
        api_key = os.environ.get("ANTHROPIC_API_KEY")
        if api_key is None:
            raise ValueError("Anthropic API key is required. Get one from https://console.anthropic.com/")

    # Create AsyncOpenAI client with Anthropic base URL
    # AnthropicのベースURLでAsyncOpenAIクライアントを作成
    openai_client = AsyncOpenAI(base_url=base_url, api_key=api_key)

    # Store the AsyncOpenAI client on the instance for direct access
    # テストで参照できるよう AsyncOpenAI クライアントをインスタンスに保存する
    self.openai_client = openai_client

    # Store parameters for later use in API calls
    # 後でAPIコールで使用するためにパラメータを保存
    self.temperature = temperature
    self.thinking = thinking
    self.kwargs = kwargs

    # Initialize the parent class with our custom client
    # カスタムクライアントで親クラスを初期化
    super().__init__(
        model=model,
        openai_client=openai_client
    )

Clearify

Bases: ClearifyBase

Default clarification output with string user requirement 文字列ユーザー要求を持つデフォルト明確化出力

Attributes:

Name Type Description
clearity bool

True if requirements are confirmed / 要件が確定した場合True

user_requirement Optional[str]

Confirmed user requirement as string / 文字列として確定したユーザー要求

Source code in src\agents_sdk_models\clearify_pipeline.py
46
47
48
49
50
51
52
53
54
55
class Clearify(ClearifyBase):
    """
    Default clarification output with string user requirement
    文字列ユーザー要求を持つデフォルト明確化出力

    Attributes:
        clearity: True if requirements are confirmed / 要件が確定した場合True
        user_requirement: Confirmed user requirement as string / 文字列として確定したユーザー要求
    """
    user_requirement: Optional[str] = None  # Confirmed user requirement as string / 文字列として確定したユーザー要求

ClearifyBase

Bases: BaseModel

Base class for requirement clarification output 要件明確化出力のベースクラス

Attributes:

Name Type Description
clearity bool

True if requirements are confirmed / 要件が確定した場合True

Source code in src\agents_sdk_models\clearify_pipeline.py
25
26
27
28
29
30
31
32
33
class ClearifyBase(BaseModel):
    """
    Base class for requirement clarification output
    要件明確化出力のベースクラス

    Attributes:
        clearity: True if requirements are confirmed / 要件が確定した場合True
    """
    clearity: bool  # True if requirements are confirmed / 要件が確定した場合True

ClearifyPipeline

Bases: AgentPipeline

ClearifyPipeline class for requirements clarification using OpenAI Agents SDK OpenAI Agents SDKを使用した要件明確化パイプラインクラス

This class extends AgentPipeline to handle: このクラスはAgentPipelineを拡張して以下を処理します: - Iterative requirement clarification / 反復的な要件明確化 - Type-safe output wrapping / 型安全な出力ラッピング - Maximum turn control / 最大ターン数制御 - Structured requirement extraction / 構造化された要求抽出

Source code in src\agents_sdk_models\clearify_pipeline.py
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
class ClearifyPipeline(AgentPipeline):
    """
    ClearifyPipeline class for requirements clarification using OpenAI Agents SDK
    OpenAI Agents SDKを使用した要件明確化パイプラインクラス

    This class extends AgentPipeline to handle:
    このクラスはAgentPipelineを拡張して以下を処理します:
    - Iterative requirement clarification / 反復的な要件明確化
    - Type-safe output wrapping / 型安全な出力ラッピング
    - Maximum turn control / 最大ターン数制御
    - Structured requirement extraction / 構造化された要求抽出
    """

    def __init__(
        self,
        name: str,
        generation_instructions: str,
        output_data: Optional[Type[Any]] = None,
        clerify_max_turns: int = 20,
        evaluation_instructions: Optional[str] = None,
        **kwargs
    ) -> None:
        """
        Initialize the ClearifyPipeline with configuration parameters
        設定パラメータでClearifyPipelineを初期化する

        Args:
            name: Pipeline name / パイプライン名
            generation_instructions: System prompt for generation / 生成用システムプロンプト
            output_data: Output data model type / 出力データモデル型
            clerify_max_turns: Maximum number of clarification turns / 最大明確化ターン数
            evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
            **kwargs: Additional arguments for AgentPipeline / AgentPipeline用追加引数
        """

        # English: Store original output data type before wrapping
        # 日本語: ラッピング前の元の出力データ型を保存
        self.original_output_data = output_data
        self.clerify_max_turns = clerify_max_turns
        self._turn_count = 0

        # English: Create wrapped output model based on provided type
        # 日本語: 提供された型に基づいてラップされた出力モデルを作成
        if output_data is not None:
            # English: For typed output, create generic wrapper
            # 日本語: 型付き出力の場合、ジェネリックラッパーを作成
            wrapped_output_model = self._create_wrapped_model(output_data)
        else:
            # English: For untyped output, use default string wrapper
            # 日本語: 型なし出力の場合、デフォルトの文字列ラッパーを使用
            wrapped_output_model = Clearify

        # English: Enhanced generation instructions for clarification
        # 日本語: 明確化用の拡張生成指示
        enhanced_instructions = self._build_clarification_instructions(
            generation_instructions, 
            output_data
        )

        # English: Initialize parent with wrapped output model
        # 日本語: ラップされた出力モデルで親クラスを初期化
        super().__init__(
            name=name,
            generation_instructions=enhanced_instructions,
            evaluation_instructions=evaluation_instructions,
            output_model=wrapped_output_model,
            **kwargs
        )

    def _create_wrapped_model(self, output_data_type: Type[Any]) -> Type[BaseModel]:
        """
        Create a wrapped output model for the given type
        指定された型用のラップされた出力モデルを作成する

        Args:
            output_data_type: Original output data type / 元の出力データ型

        Returns:
            Type[BaseModel]: Wrapped model type / ラップされたモデル型
        """
        # English: Create dynamic Pydantic model that wraps the original type
        # 日本語: 元の型をラップする動的Pydanticモデルを作成

        class WrappedClearify(BaseModel):
            clearity: bool  # True if requirements are confirmed / 要件が確定した場合True
            user_requirement: Optional[output_data_type] = None  # Confirmed user requirement / 確定したユーザー要求

        return WrappedClearify

    def _build_clarification_instructions(
        self, 
        base_instructions: str, 
        output_data_type: Optional[Type[Any]]
    ) -> str:
        """
        Build enhanced instructions for clarification process
        明確化プロセス用の拡張指示を構築する

        Args:
            base_instructions: Base generation instructions / ベース生成指示
            output_data_type: Output data type for schema reference / スキーマ参照用出力データ型

        Returns:
            str: Enhanced instructions / 拡張指示
        """
        schema_info = ""
        if output_data_type is not None:
            try:
                # English: Try to get schema information if available
                # 日本語: 利用可能な場合はスキーマ情報を取得を試行
                if hasattr(output_data_type, 'model_json_schema'):
                    schema = output_data_type.model_json_schema()
                    schema_info = f"\n\n必要な出力形式のスキーマ:\n{json.dumps(schema, indent=2, ensure_ascii=False)}"
                elif hasattr(output_data_type, '__annotations__'):
                    annotations = output_data_type.__annotations__
                    schema_info = f"\n\n必要なフィールド: {list(annotations.keys())}"
            except Exception:
                pass

        enhanced_instructions = f"""{base_instructions}

あなたは要件明確化の専門家です。以下の手順に従ってください:

1. ユーザーの要求を理解し、不明確な点や不足している情報を特定する
2. より良い結果のために必要な追加情報を質問する
3. 要件が十分に明確になった場合は、clearityをtrueに設定する
4. 要件が不十分な場合は、clearityをfalseに設定し、追加の質問を行う

出力形式:
- clearity: 要件が明確で完全な場合はtrue、追加情報が必要な場合はfalse
- user_requirement: clearityがtrueの場合のみ、確定した要件を設定

{schema_info}

最大{self.clerify_max_turns}回のやり取りで要件を明確化してください。
"""

        return enhanced_instructions

    def run(self, user_input: str) -> Any:
        """
        Run the clarification pipeline with user input
        ユーザー入力で明確化パイプラインを実行する

        Args:
            user_input: User input text / ユーザー入力テキスト

        Returns:
            Any: Final clarified requirement, clarification question, or None if failed / 最終的な明確化された要求、明確化質問、または失敗時はNone
        """
        # English: Reset turn count for new session
        # 日本語: 新しいセッション用にターンカウントをリセット
        self._turn_count = 0
        return self._process_input(user_input)

    def continue_clarification(self, user_response: str) -> Any:
        """
        Continue clarification with user response to previous question
        前の質問に対するユーザー回答で明確化を継続する

        Args:
            user_response: User response to clarification question / 明確化質問に対するユーザー回答

        Returns:
            Any: Final clarified requirement, next clarification question, or None if failed / 最終的な明確化された要求、次の明確化質問、または失敗時はNone
        """
        if self._turn_count >= self.clerify_max_turns:
            # English: Maximum turns reached, cannot continue
            # 日本語: 最大ターン数に達した、継続できない
            return None

        return self._process_input(user_response)

    def _process_input(self, user_input: str) -> Any:
        """
        Process user input and return result or next question
        ユーザー入力を処理し、結果または次の質問を返す

        Args:
            user_input: User input text / ユーザー入力テキスト

        Returns:
            Any: Final clarified requirement, clarification question, or None if failed / 最終的な明確化された要求、明確化質問、または失敗時はNone
        """
        # English: Build context with conversation history
        # 日本語: 会話履歴を含むコンテキストを構築
        if self._turn_count > 0:
            # English: For subsequent turns, include conversation history
            # 日本語: 2回目以降のターンでは会話履歴を含める
            conversation_context = self._build_conversation_context()
            full_input = f"{conversation_context}\n\nユーザー: {user_input}"
        else:
            full_input = user_input

        # English: Run parent pipeline
        # 日本語: 親パイプラインを実行
        result = super().run(full_input)

        if result is None:
            # English: Pipeline failed
            # 日本語: パイプライン失敗
            return None

        self._turn_count += 1

        # English: Store this interaction in history
        # 日本語: この対話を履歴に保存
        self._store_interaction(user_input, result)

        # English: Check if clarification is complete
        # 日本語: 明確化が完了しているかチェック
        if hasattr(result, 'clearity') and result.clearity:
            # English: Requirements are clear, extract and return final result
            # 日本語: 要件が明確、最終結果を抽出して返す
            if hasattr(result, 'user_requirement') and result.user_requirement:
                return result.user_requirement
            else:
                return result

        # English: Requirements not clear yet, return the clarification question
        # 日本語: 要件がまだ明確でない、明確化質問を返す
        if hasattr(result, 'user_requirement') and result.user_requirement:
            # English: Return the clarification question/request for more info
            # 日本語: 明確化質問/追加情報の要求を返す
            return ClarificationQuestion(
                question=str(result.user_requirement),
                turn=self._turn_count,
                remaining_turns=self.remaining_turns
            )

        # English: No clear question, return the raw result
        # 日本語: 明確な質問がない、生の結果を返す
        return result

    def _build_conversation_context(self) -> str:
        """
        Build conversation context from history
        履歴から会話コンテキストを構築する

        Returns:
            str: Formatted conversation context / フォーマット済み会話コンテキスト
        """
        if not hasattr(self, '_conversation_history'):
            return ""

        context_lines = []
        for interaction in self._conversation_history:
            context_lines.append(f"ユーザー: {interaction['user_input']}")
            context_lines.append(f"AI: {interaction['ai_response']}")

        return "\n".join(context_lines)

    def _store_interaction(self, user_input: str, ai_result: Any) -> None:
        """
        Store interaction in conversation history
        会話履歴に対話を保存する

        Args:
            user_input: User input / ユーザー入力
            ai_result: AI result / AI結果
        """
        if not hasattr(self, '_conversation_history'):
            self._conversation_history = []

        # English: Extract AI response text
        # 日本語: AI応答テキストを抽出
        if hasattr(ai_result, 'user_requirement') and ai_result.user_requirement:
            ai_response = str(ai_result.user_requirement)
        else:
            ai_response = str(ai_result)

        self._conversation_history.append({
            'user_input': user_input,
            'ai_response': ai_response,
            'turn': self._turn_count
        })

        # English: Keep only recent history to avoid context overflow
        # 日本語: コンテキストオーバーフローを避けるため最近の履歴のみ保持
        max_history = 10
        if len(self._conversation_history) > max_history:
            self._conversation_history = self._conversation_history[-max_history:]

    def reset_turns(self) -> None:
        """
        Reset the turn counter for a new clarification session
        新しい明確化セッション用にターンカウンターをリセットする
        """
        self._turn_count = 0
        if hasattr(self, '_conversation_history'):
            self._conversation_history = []

    def reset_session(self) -> None:
        """
        Reset the entire session including conversation history
        会話履歴を含むセッション全体をリセットする
        """
        self.reset_turns()
        if hasattr(self, '_conversation_history'):
            self._conversation_history = []

    @property
    def is_complete(self) -> bool:
        """
        Check if clarification process is complete (max turns reached)
        明確化プロセスが完了しているかチェック(最大ターン数に達した)

        Returns:
            bool: True if max turns reached / 最大ターン数に達した場合True
        """
        return self._turn_count >= self.clerify_max_turns

    @property
    def conversation_history(self) -> List[Dict[str, Any]]:
        """
        Get the conversation history
        会話履歴を取得する

        Returns:
            List[Dict[str, Any]]: Conversation history / 会話履歴
        """
        if not hasattr(self, '_conversation_history'):
            return []
        return self._conversation_history.copy()

    @property
    def current_turn(self) -> int:
        """
        Get the current turn number
        現在のターン番号を取得する

        Returns:
            int: Current turn number / 現在のターン番号
        """
        return self._turn_count

    @property
    def remaining_turns(self) -> int:
        """
        Get the remaining number of turns
        残りのターン数を取得する

        Returns:
            int: Remaining turns / 残りターン数
        """
        return max(0, self.clerify_max_turns - self._turn_count) 

conversation_history property

Get the conversation history 会話履歴を取得する

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Conversation history / 会話履歴

current_turn property

Get the current turn number 現在のターン番号を取得する

Returns:

Name Type Description
int int

Current turn number / 現在のターン番号

is_complete property

Check if clarification process is complete (max turns reached) 明確化プロセスが完了しているかチェック(最大ターン数に達した)

Returns:

Name Type Description
bool bool

True if max turns reached / 最大ターン数に達した場合True

remaining_turns property

Get the remaining number of turns 残りのターン数を取得する

Returns:

Name Type Description
int int

Remaining turns / 残りターン数

__init__(name, generation_instructions, output_data=None, clerify_max_turns=20, evaluation_instructions=None, **kwargs)

Initialize the ClearifyPipeline with configuration parameters 設定パラメータでClearifyPipelineを初期化する

Parameters:

Name Type Description Default
name str

Pipeline name / パイプライン名

required
generation_instructions str

System prompt for generation / 生成用システムプロンプト

required
output_data Optional[Type[Any]]

Output data model type / 出力データモデル型

None
clerify_max_turns int

Maximum number of clarification turns / 最大明確化ターン数

20
evaluation_instructions Optional[str]

System prompt for evaluation / 評価用システムプロンプト

None
**kwargs

Additional arguments for AgentPipeline / AgentPipeline用追加引数

{}
Source code in src\agents_sdk_models\clearify_pipeline.py
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
def __init__(
    self,
    name: str,
    generation_instructions: str,
    output_data: Optional[Type[Any]] = None,
    clerify_max_turns: int = 20,
    evaluation_instructions: Optional[str] = None,
    **kwargs
) -> None:
    """
    Initialize the ClearifyPipeline with configuration parameters
    設定パラメータでClearifyPipelineを初期化する

    Args:
        name: Pipeline name / パイプライン名
        generation_instructions: System prompt for generation / 生成用システムプロンプト
        output_data: Output data model type / 出力データモデル型
        clerify_max_turns: Maximum number of clarification turns / 最大明確化ターン数
        evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
        **kwargs: Additional arguments for AgentPipeline / AgentPipeline用追加引数
    """

    # English: Store original output data type before wrapping
    # 日本語: ラッピング前の元の出力データ型を保存
    self.original_output_data = output_data
    self.clerify_max_turns = clerify_max_turns
    self._turn_count = 0

    # English: Create wrapped output model based on provided type
    # 日本語: 提供された型に基づいてラップされた出力モデルを作成
    if output_data is not None:
        # English: For typed output, create generic wrapper
        # 日本語: 型付き出力の場合、ジェネリックラッパーを作成
        wrapped_output_model = self._create_wrapped_model(output_data)
    else:
        # English: For untyped output, use default string wrapper
        # 日本語: 型なし出力の場合、デフォルトの文字列ラッパーを使用
        wrapped_output_model = Clearify

    # English: Enhanced generation instructions for clarification
    # 日本語: 明確化用の拡張生成指示
    enhanced_instructions = self._build_clarification_instructions(
        generation_instructions, 
        output_data
    )

    # English: Initialize parent with wrapped output model
    # 日本語: ラップされた出力モデルで親クラスを初期化
    super().__init__(
        name=name,
        generation_instructions=enhanced_instructions,
        evaluation_instructions=evaluation_instructions,
        output_model=wrapped_output_model,
        **kwargs
    )

continue_clarification(user_response)

Continue clarification with user response to previous question 前の質問に対するユーザー回答で明確化を継続する

Parameters:

Name Type Description Default
user_response str

User response to clarification question / 明確化質問に対するユーザー回答

required

Returns:

Name Type Description
Any Any

Final clarified requirement, next clarification question, or None if failed / 最終的な明確化された要求、次の明確化質問、または失敗時はNone

Source code in src\agents_sdk_models\clearify_pipeline.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
def continue_clarification(self, user_response: str) -> Any:
    """
    Continue clarification with user response to previous question
    前の質問に対するユーザー回答で明確化を継続する

    Args:
        user_response: User response to clarification question / 明確化質問に対するユーザー回答

    Returns:
        Any: Final clarified requirement, next clarification question, or None if failed / 最終的な明確化された要求、次の明確化質問、または失敗時はNone
    """
    if self._turn_count >= self.clerify_max_turns:
        # English: Maximum turns reached, cannot continue
        # 日本語: 最大ターン数に達した、継続できない
        return None

    return self._process_input(user_response)

reset_session()

Reset the entire session including conversation history 会話履歴を含むセッション全体をリセットする

Source code in src\agents_sdk_models\clearify_pipeline.py
376
377
378
379
380
381
382
383
def reset_session(self) -> None:
    """
    Reset the entire session including conversation history
    会話履歴を含むセッション全体をリセットする
    """
    self.reset_turns()
    if hasattr(self, '_conversation_history'):
        self._conversation_history = []

reset_turns()

Reset the turn counter for a new clarification session 新しい明確化セッション用にターンカウンターをリセットする

Source code in src\agents_sdk_models\clearify_pipeline.py
367
368
369
370
371
372
373
374
def reset_turns(self) -> None:
    """
    Reset the turn counter for a new clarification session
    新しい明確化セッション用にターンカウンターをリセットする
    """
    self._turn_count = 0
    if hasattr(self, '_conversation_history'):
        self._conversation_history = []

run(user_input)

Run the clarification pipeline with user input ユーザー入力で明確化パイプラインを実行する

Parameters:

Name Type Description Default
user_input str

User input text / ユーザー入力テキスト

required

Returns:

Name Type Description
Any Any

Final clarified requirement, clarification question, or None if failed / 最終的な明確化された要求、明確化質問、または失敗時はNone

Source code in src\agents_sdk_models\clearify_pipeline.py
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
def run(self, user_input: str) -> Any:
    """
    Run the clarification pipeline with user input
    ユーザー入力で明確化パイプラインを実行する

    Args:
        user_input: User input text / ユーザー入力テキスト

    Returns:
        Any: Final clarified requirement, clarification question, or None if failed / 最終的な明確化された要求、明確化質問、または失敗時はNone
    """
    # English: Reset turn count for new session
    # 日本語: 新しいセッション用にターンカウントをリセット
    self._turn_count = 0
    return self._process_input(user_input)

ConditionStep

Bases: Step

Step that performs conditional routing 条件付きルーティングを実行するステップ

This step evaluates a condition and routes to different steps based on the result. このステップは条件を評価し、結果に基づいて異なるステップにルーティングします。

Source code in src\agents_sdk_models\step.py
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
class ConditionStep(Step):
    """
    Step that performs conditional routing
    条件付きルーティングを実行するステップ

    This step evaluates a condition and routes to different steps based on the result.
    このステップは条件を評価し、結果に基づいて異なるステップにルーティングします。
    """

    def __init__(
        self, 
        name: str, 
        condition: Callable[[Context], Union[bool, Awaitable[bool]]], 
        if_true: str, 
        if_false: str
    ):
        """
        Initialize condition step
        条件ステップを初期化

        Args:
            name: Step name / ステップ名
            condition: Condition function / 条件関数
            if_true: Step to go if condition is True / 条件がTrueの場合のステップ
            if_false: Step to go if condition is False / 条件がFalseの場合のステップ
        """
        super().__init__(name)
        self.condition = condition
        self.if_true = if_true
        self.if_false = if_false

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute condition step
        条件ステップを実行

        Args:
            user_input: User input (not used) / ユーザー入力(使用されない)
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context with routing / ルーティング付き更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        # Evaluate condition (may be async)
        # 条件を評価(非同期の可能性あり)
        try:
            result = self.condition(ctx)
            if asyncio.iscoroutine(result):
                result = await result
        except Exception as e:
            # On error, go to false branch
            # エラー時はfalseブランチに進む
            ctx.add_system_message(f"Condition evaluation error: {e}")
            result = False

        # Route based on condition result
        # 条件結果に基づいてルーティング
        next_step = self.if_true if result else self.if_false
        ctx.goto(next_step)

        return ctx

__init__(name, condition, if_true, if_false)

Initialize condition step 条件ステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
condition Callable[[Context], Union[bool, Awaitable[bool]]]

Condition function / 条件関数

required
if_true str

Step to go if condition is True / 条件がTrueの場合のステップ

required
if_false str

Step to go if condition is False / 条件がFalseの場合のステップ

required
Source code in src\agents_sdk_models\step.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
def __init__(
    self, 
    name: str, 
    condition: Callable[[Context], Union[bool, Awaitable[bool]]], 
    if_true: str, 
    if_false: str
):
    """
    Initialize condition step
    条件ステップを初期化

    Args:
        name: Step name / ステップ名
        condition: Condition function / 条件関数
        if_true: Step to go if condition is True / 条件がTrueの場合のステップ
        if_false: Step to go if condition is False / 条件がFalseの場合のステップ
    """
    super().__init__(name)
    self.condition = condition
    self.if_true = if_true
    self.if_false = if_false

run(user_input, ctx) async

Execute condition step 条件ステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input (not used) / ユーザー入力(使用されない)

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context with routing / ルーティング付き更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute condition step
    条件ステップを実行

    Args:
        user_input: User input (not used) / ユーザー入力(使用されない)
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context with routing / ルーティング付き更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    # Evaluate condition (may be async)
    # 条件を評価(非同期の可能性あり)
    try:
        result = self.condition(ctx)
        if asyncio.iscoroutine(result):
            result = await result
    except Exception as e:
        # On error, go to false branch
        # エラー時はfalseブランチに進む
        ctx.add_system_message(f"Condition evaluation error: {e}")
        result = False

    # Route based on condition result
    # 条件結果に基づいてルーティング
    next_step = self.if_true if result else self.if_false
    ctx.goto(next_step)

    return ctx

Context

Bases: BaseModel

Context class for Flow/Step workflow state management フロー/ステップワークフロー状態管理用コンテキストクラス

This class provides: このクラスは以下を提供します: - Type-safe shared state / 型安全な共有状態 - Conversation history management / 会話履歴管理 - Step routing control / ステップルーティング制御 - LangChain LCEL compatibility / LangChain LCEL互換性 - User input/output coordination / ユーザー入出力調整

Source code in src\agents_sdk_models\context.py
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
class Context(BaseModel):
    """
    Context class for Flow/Step workflow state management
    フロー/ステップワークフロー状態管理用コンテキストクラス

    This class provides:
    このクラスは以下を提供します:
    - Type-safe shared state / 型安全な共有状態
    - Conversation history management / 会話履歴管理
    - Step routing control / ステップルーティング制御
    - LangChain LCEL compatibility / LangChain LCEL互換性
    - User input/output coordination / ユーザー入出力調整
    """

    # Core state / コア状態
    last_user_input: Optional[str] = None  # Most recent user input / 直近のユーザー入力
    messages: List[Message] = Field(default_factory=list)  # Conversation history / 会話履歴

    # External data / 外部データ
    knowledge: Dict[str, Any] = Field(default_factory=dict)  # External knowledge (RAG, etc.) / 外部知識(RAGなど)
    prev_outputs: Dict[str, Any] = Field(default_factory=dict)  # Previous step outputs / 前ステップの出力

    # Flow control / フロー制御
    next_label: Optional[str] = None  # Next step routing instruction / 次ステップのルーティング指示
    current_step: Optional[str] = None  # Current step name / 現在のステップ名

    # Results / 結果
    artifacts: Dict[str, Any] = Field(default_factory=dict)  # Flow-wide artifacts / フロー全体の成果物
    shared_state: Dict[str, Any] = Field(default_factory=dict)  # Arbitrary shared values / 任意の共有値

    # User interaction / ユーザー対話
    awaiting_prompt: Optional[str] = None  # Prompt waiting for user input / ユーザー入力待ちのプロンプト
    awaiting_user_input: bool = False  # Flag indicating waiting for user input / ユーザー入力待ちフラグ

    # Execution metadata / 実行メタデータ
    trace_id: Optional[str] = None  # Trace ID for observability / オブザーバビリティ用トレースID
    start_time: datetime = Field(default_factory=datetime.now)  # Flow start time / フロー開始時刻
    step_count: int = 0  # Number of steps executed / 実行されたステップ数

    # Internal async coordination (private attributes) / 内部非同期調整(プライベート属性)
    _user_input_event: Optional[asyncio.Event] = PrivateAttr(default=None)
    _awaiting_prompt_event: Optional[asyncio.Event] = PrivateAttr(default=None)

    def __init__(self, **data):
        """
        Initialize Context with async events
        非同期イベントでContextを初期化
        """
        super().__init__(**data)
        self._user_input_event = asyncio.Event()
        self._awaiting_prompt_event = asyncio.Event()

    def add_user_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
        """
        Add user message to conversation history
        ユーザーメッセージを会話履歴に追加

        Args:
            content: Message content / メッセージ内容
            metadata: Additional metadata / 追加メタデータ
        """
        message = Message(
            role="user",
            content=content,
            metadata=metadata or {}
        )
        self.messages.append(message)
        self.last_user_input = content

    def add_assistant_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
        """
        Add assistant message to conversation history
        アシスタントメッセージを会話履歴に追加

        Args:
            content: Message content / メッセージ内容
            metadata: Additional metadata / 追加メタデータ
        """
        message = Message(
            role="assistant",
            content=content,
            metadata=metadata or {}
        )
        self.messages.append(message)

    def add_system_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
        """
        Add system message to conversation history
        システムメッセージを会話履歴に追加

        Args:
            content: Message content / メッセージ内容
            metadata: Additional metadata / 追加メタデータ
        """
        message = Message(
            role="system",
            content=content,
            metadata=metadata or {}
        )
        self.messages.append(message)

    def set_waiting_for_user_input(self, prompt: str) -> None:
        """
        Set context to wait for user input with a prompt
        プロンプトでユーザー入力待ち状態に設定

        Args:
            prompt: Prompt to display to user / ユーザーに表示するプロンプト
        """
        self.awaiting_prompt = prompt
        self.awaiting_user_input = True
        if self._awaiting_prompt_event:
            self._awaiting_prompt_event.set()

    def provide_user_input(self, user_input: str) -> None:
        """
        Provide user input and clear waiting state
        ユーザー入力を提供し、待ち状態をクリア

        Args:
            user_input: User input text / ユーザー入力テキスト
        """
        self.add_user_message(user_input)
        self.awaiting_prompt = None
        self.awaiting_user_input = False
        if self._user_input_event:
            self._user_input_event.set()

    def clear_prompt(self) -> Optional[str]:
        """
        Clear and return the current prompt
        現在のプロンプトをクリアして返す

        Returns:
            str | None: The prompt if one was waiting / 待機中だったプロンプト
        """
        prompt = self.awaiting_prompt
        self.awaiting_prompt = None
        if self._awaiting_prompt_event:
            self._awaiting_prompt_event.clear()
        return prompt

    async def wait_for_user_input(self) -> str:
        """
        Async wait for user input
        ユーザー入力を非同期で待機

        Returns:
            str: User input / ユーザー入力
        """
        if self._user_input_event:
            await self._user_input_event.wait()
            self._user_input_event.clear()
        return self.last_user_input or ""

    async def wait_for_prompt_event(self) -> str:
        """
        Async wait for prompt event
        プロンプトイベントを非同期で待機

        Returns:
            str: Prompt waiting for user / ユーザー待ちのプロンプト
        """
        if self._awaiting_prompt_event:
            await self._awaiting_prompt_event.wait()
        return self.awaiting_prompt or ""

    def goto(self, label: str) -> None:
        """
        Set next step routing
        次ステップのルーティングを設定

        Args:
            label: Next step label / 次ステップのラベル
        """
        self.next_label = label

    def finish(self) -> None:
        """
        Mark flow as finished
        フローを完了としてマーク
        """
        self.next_label = None

    def is_finished(self) -> bool:
        """
        Check if flow is finished
        フローが完了しているかチェック

        Returns:
            bool: True if finished / 完了している場合True
        """
        return self.next_label is None

    def as_dict(self) -> Dict[str, Any]:
        """
        Convert to dictionary for LangChain LCEL compatibility
        LangChain LCEL互換性のために辞書に変換

        Returns:
            Dict[str, Any]: Dictionary representation / 辞書表現
        """
        data = self.dict()
        # Convert messages to LangChain format
        # メッセージをLangChain形式に変換
        data["history"] = [
            {"role": msg.role, "content": msg.content, "metadata": msg.metadata}
            for msg in self.messages
        ]
        data.pop("messages", None)
        return data

    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> "Context":
        """
        Create Context from dictionary (LangChain LCEL compatibility)
        辞書からContextを作成(LangChain LCEL互換性)

        Args:
            data: Dictionary data / 辞書データ

        Returns:
            Context: New context instance / 新しいコンテキストインスタンス
        """
        data = data.copy()
        # Convert history to messages
        # 履歴をメッセージに変換
        history = data.pop("history", [])
        messages = []
        for msg_data in history:
            if isinstance(msg_data, dict):
                messages.append(Message(
                    role=msg_data.get("role", "user"),
                    content=msg_data.get("content", ""),
                    metadata=msg_data.get("metadata", {})
                ))
        data["messages"] = messages
        return cls(**data)

    def get_conversation_text(self, include_system: bool = False) -> str:
        """
        Get conversation as formatted text
        会話をフォーマット済みテキストとして取得

        Args:
            include_system: Include system messages / システムメッセージを含める

        Returns:
            str: Formatted conversation / フォーマット済み会話
        """
        lines = []
        for msg in self.messages:
            if not include_system and msg.role == "system":
                continue
            role_label = {"user": "👤", "assistant": "🤖", "system": "⚙️"}.get(msg.role, msg.role)
            lines.append(f"{role_label} {msg.content}")
        return "\n".join(lines)

    def get_last_messages(self, n: int = 10) -> List[Message]:
        """
        Get last N messages
        最後のNメッセージを取得

        Args:
            n: Number of messages / メッセージ数

        Returns:
            List[Message]: Last N messages / 最後のNメッセージ
        """
        return self.messages[-n:] if len(self.messages) > n else self.messages.copy()

    def update_step_info(self, step_name: str) -> None:
        """
        Update current step information
        現在のステップ情報を更新

        Args:
            step_name: Current step name / 現在のステップ名
        """
        self.current_step = step_name
        self.step_count += 1

    def set_artifact(self, key: str, value: Any) -> None:
        """
        Set artifact value
        成果物の値を設定

        Args:
            key: Artifact key / 成果物キー
            value: Artifact value / 成果物値
        """
        self.artifacts[key] = value

    def get_artifact(self, key: str, default: Any = None) -> Any:
        """
        Get artifact value
        成果物の値を取得

        Args:
            key: Artifact key / 成果物キー
            default: Default value if not found / 見つからない場合のデフォルト値

        Returns:
            Any: Artifact value / 成果物値
        """
        return self.artifacts.get(key, default)

    class Config:
        # Allow arbitrary types for flexibility
        # 柔軟性のために任意の型を許可
        arbitrary_types_allowed = True 

__init__(**data)

Initialize Context with async events 非同期イベントでContextを初期化

Source code in src\agents_sdk_models\context.py
81
82
83
84
85
86
87
88
def __init__(self, **data):
    """
    Initialize Context with async events
    非同期イベントでContextを初期化
    """
    super().__init__(**data)
    self._user_input_event = asyncio.Event()
    self._awaiting_prompt_event = asyncio.Event()

add_assistant_message(content, metadata=None)

Add assistant message to conversation history アシスタントメッセージを会話履歴に追加

Parameters:

Name Type Description Default
content str

Message content / メッセージ内容

required
metadata Optional[Dict[str, Any]]

Additional metadata / 追加メタデータ

None
Source code in src\agents_sdk_models\context.py
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
def add_assistant_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
    """
    Add assistant message to conversation history
    アシスタントメッセージを会話履歴に追加

    Args:
        content: Message content / メッセージ内容
        metadata: Additional metadata / 追加メタデータ
    """
    message = Message(
        role="assistant",
        content=content,
        metadata=metadata or {}
    )
    self.messages.append(message)

add_system_message(content, metadata=None)

Add system message to conversation history システムメッセージを会話履歴に追加

Parameters:

Name Type Description Default
content str

Message content / メッセージ内容

required
metadata Optional[Dict[str, Any]]

Additional metadata / 追加メタデータ

None
Source code in src\agents_sdk_models\context.py
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
def add_system_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
    """
    Add system message to conversation history
    システムメッセージを会話履歴に追加

    Args:
        content: Message content / メッセージ内容
        metadata: Additional metadata / 追加メタデータ
    """
    message = Message(
        role="system",
        content=content,
        metadata=metadata or {}
    )
    self.messages.append(message)

add_user_message(content, metadata=None)

Add user message to conversation history ユーザーメッセージを会話履歴に追加

Parameters:

Name Type Description Default
content str

Message content / メッセージ内容

required
metadata Optional[Dict[str, Any]]

Additional metadata / 追加メタデータ

None
Source code in src\agents_sdk_models\context.py
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def add_user_message(self, content: str, metadata: Optional[Dict[str, Any]] = None) -> None:
    """
    Add user message to conversation history
    ユーザーメッセージを会話履歴に追加

    Args:
        content: Message content / メッセージ内容
        metadata: Additional metadata / 追加メタデータ
    """
    message = Message(
        role="user",
        content=content,
        metadata=metadata or {}
    )
    self.messages.append(message)
    self.last_user_input = content

as_dict()

Convert to dictionary for LangChain LCEL compatibility LangChain LCEL互換性のために辞書に変換

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Dictionary representation / 辞書表現

Source code in src\agents_sdk_models\context.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
def as_dict(self) -> Dict[str, Any]:
    """
    Convert to dictionary for LangChain LCEL compatibility
    LangChain LCEL互換性のために辞書に変換

    Returns:
        Dict[str, Any]: Dictionary representation / 辞書表現
    """
    data = self.dict()
    # Convert messages to LangChain format
    # メッセージをLangChain形式に変換
    data["history"] = [
        {"role": msg.role, "content": msg.content, "metadata": msg.metadata}
        for msg in self.messages
    ]
    data.pop("messages", None)
    return data

clear_prompt()

Clear and return the current prompt 現在のプロンプトをクリアして返す

Returns:

Type Description
Optional[str]

str | None: The prompt if one was waiting / 待機中だったプロンプト

Source code in src\agents_sdk_models\context.py
166
167
168
169
170
171
172
173
174
175
176
177
178
def clear_prompt(self) -> Optional[str]:
    """
    Clear and return the current prompt
    現在のプロンプトをクリアして返す

    Returns:
        str | None: The prompt if one was waiting / 待機中だったプロンプト
    """
    prompt = self.awaiting_prompt
    self.awaiting_prompt = None
    if self._awaiting_prompt_event:
        self._awaiting_prompt_event.clear()
    return prompt

finish()

Mark flow as finished フローを完了としてマーク

Source code in src\agents_sdk_models\context.py
215
216
217
218
219
220
def finish(self) -> None:
    """
    Mark flow as finished
    フローを完了としてマーク
    """
    self.next_label = None

from_dict(data) classmethod

Create Context from dictionary (LangChain LCEL compatibility) 辞書からContextを作成(LangChain LCEL互換性)

Parameters:

Name Type Description Default
data Dict[str, Any]

Dictionary data / 辞書データ

required

Returns:

Name Type Description
Context 'Context'

New context instance / 新しいコンテキストインスタンス

Source code in src\agents_sdk_models\context.py
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
@classmethod
def from_dict(cls, data: Dict[str, Any]) -> "Context":
    """
    Create Context from dictionary (LangChain LCEL compatibility)
    辞書からContextを作成(LangChain LCEL互換性)

    Args:
        data: Dictionary data / 辞書データ

    Returns:
        Context: New context instance / 新しいコンテキストインスタンス
    """
    data = data.copy()
    # Convert history to messages
    # 履歴をメッセージに変換
    history = data.pop("history", [])
    messages = []
    for msg_data in history:
        if isinstance(msg_data, dict):
            messages.append(Message(
                role=msg_data.get("role", "user"),
                content=msg_data.get("content", ""),
                metadata=msg_data.get("metadata", {})
            ))
    data["messages"] = messages
    return cls(**data)

get_artifact(key, default=None)

Get artifact value 成果物の値を取得

Parameters:

Name Type Description Default
key str

Artifact key / 成果物キー

required
default Any

Default value if not found / 見つからない場合のデフォルト値

None

Returns:

Name Type Description
Any Any

Artifact value / 成果物値

Source code in src\agents_sdk_models\context.py
331
332
333
334
335
336
337
338
339
340
341
342
343
def get_artifact(self, key: str, default: Any = None) -> Any:
    """
    Get artifact value
    成果物の値を取得

    Args:
        key: Artifact key / 成果物キー
        default: Default value if not found / 見つからない場合のデフォルト値

    Returns:
        Any: Artifact value / 成果物値
    """
    return self.artifacts.get(key, default)

get_conversation_text(include_system=False)

Get conversation as formatted text 会話をフォーマット済みテキストとして取得

Parameters:

Name Type Description Default
include_system bool

Include system messages / システムメッセージを含める

False

Returns:

Name Type Description
str str

Formatted conversation / フォーマット済み会話

Source code in src\agents_sdk_models\context.py
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
def get_conversation_text(self, include_system: bool = False) -> str:
    """
    Get conversation as formatted text
    会話をフォーマット済みテキストとして取得

    Args:
        include_system: Include system messages / システムメッセージを含める

    Returns:
        str: Formatted conversation / フォーマット済み会話
    """
    lines = []
    for msg in self.messages:
        if not include_system and msg.role == "system":
            continue
        role_label = {"user": "👤", "assistant": "🤖", "system": "⚙️"}.get(msg.role, msg.role)
        lines.append(f"{role_label} {msg.content}")
    return "\n".join(lines)

get_last_messages(n=10)

Get last N messages 最後のNメッセージを取得

Parameters:

Name Type Description Default
n int

Number of messages / メッセージ数

10

Returns:

Type Description
List[Message]

List[Message]: Last N messages / 最後のNメッセージ

Source code in src\agents_sdk_models\context.py
296
297
298
299
300
301
302
303
304
305
306
307
def get_last_messages(self, n: int = 10) -> List[Message]:
    """
    Get last N messages
    最後のNメッセージを取得

    Args:
        n: Number of messages / メッセージ数

    Returns:
        List[Message]: Last N messages / 最後のNメッセージ
    """
    return self.messages[-n:] if len(self.messages) > n else self.messages.copy()

goto(label)

Set next step routing 次ステップのルーティングを設定

Parameters:

Name Type Description Default
label str

Next step label / 次ステップのラベル

required
Source code in src\agents_sdk_models\context.py
205
206
207
208
209
210
211
212
213
def goto(self, label: str) -> None:
    """
    Set next step routing
    次ステップのルーティングを設定

    Args:
        label: Next step label / 次ステップのラベル
    """
    self.next_label = label

is_finished()

Check if flow is finished フローが完了しているかチェック

Returns:

Name Type Description
bool bool

True if finished / 完了している場合True

Source code in src\agents_sdk_models\context.py
222
223
224
225
226
227
228
229
230
def is_finished(self) -> bool:
    """
    Check if flow is finished
    フローが完了しているかチェック

    Returns:
        bool: True if finished / 完了している場合True
    """
    return self.next_label is None

provide_user_input(user_input)

Provide user input and clear waiting state ユーザー入力を提供し、待ち状態をクリア

Parameters:

Name Type Description Default
user_input str

User input text / ユーザー入力テキスト

required
Source code in src\agents_sdk_models\context.py
152
153
154
155
156
157
158
159
160
161
162
163
164
def provide_user_input(self, user_input: str) -> None:
    """
    Provide user input and clear waiting state
    ユーザー入力を提供し、待ち状態をクリア

    Args:
        user_input: User input text / ユーザー入力テキスト
    """
    self.add_user_message(user_input)
    self.awaiting_prompt = None
    self.awaiting_user_input = False
    if self._user_input_event:
        self._user_input_event.set()

set_artifact(key, value)

Set artifact value 成果物の値を設定

Parameters:

Name Type Description Default
key str

Artifact key / 成果物キー

required
value Any

Artifact value / 成果物値

required
Source code in src\agents_sdk_models\context.py
320
321
322
323
324
325
326
327
328
329
def set_artifact(self, key: str, value: Any) -> None:
    """
    Set artifact value
    成果物の値を設定

    Args:
        key: Artifact key / 成果物キー
        value: Artifact value / 成果物値
    """
    self.artifacts[key] = value

set_waiting_for_user_input(prompt)

Set context to wait for user input with a prompt プロンプトでユーザー入力待ち状態に設定

Parameters:

Name Type Description Default
prompt str

Prompt to display to user / ユーザーに表示するプロンプト

required
Source code in src\agents_sdk_models\context.py
139
140
141
142
143
144
145
146
147
148
149
150
def set_waiting_for_user_input(self, prompt: str) -> None:
    """
    Set context to wait for user input with a prompt
    プロンプトでユーザー入力待ち状態に設定

    Args:
        prompt: Prompt to display to user / ユーザーに表示するプロンプト
    """
    self.awaiting_prompt = prompt
    self.awaiting_user_input = True
    if self._awaiting_prompt_event:
        self._awaiting_prompt_event.set()

update_step_info(step_name)

Update current step information 現在のステップ情報を更新

Parameters:

Name Type Description Default
step_name str

Current step name / 現在のステップ名

required
Source code in src\agents_sdk_models\context.py
309
310
311
312
313
314
315
316
317
318
def update_step_info(self, step_name: str) -> None:
    """
    Update current step information
    現在のステップ情報を更新

    Args:
        step_name: Current step name / 現在のステップ名
    """
    self.current_step = step_name
    self.step_count += 1

wait_for_prompt_event() async

Async wait for prompt event プロンプトイベントを非同期で待機

Returns:

Name Type Description
str str

Prompt waiting for user / ユーザー待ちのプロンプト

Source code in src\agents_sdk_models\context.py
193
194
195
196
197
198
199
200
201
202
203
async def wait_for_prompt_event(self) -> str:
    """
    Async wait for prompt event
    プロンプトイベントを非同期で待機

    Returns:
        str: Prompt waiting for user / ユーザー待ちのプロンプト
    """
    if self._awaiting_prompt_event:
        await self._awaiting_prompt_event.wait()
    return self.awaiting_prompt or ""

wait_for_user_input() async

Async wait for user input ユーザー入力を非同期で待機

Returns:

Name Type Description
str str

User input / ユーザー入力

Source code in src\agents_sdk_models\context.py
180
181
182
183
184
185
186
187
188
189
190
191
async def wait_for_user_input(self) -> str:
    """
    Async wait for user input
    ユーザー入力を非同期で待機

    Returns:
        str: User input / ユーザー入力
    """
    if self._user_input_event:
        await self._user_input_event.wait()
        self._user_input_event.clear()
    return self.last_user_input or ""

DebugStep

Bases: Step

Step for debugging and logging デバッグとログ用ステップ

This step prints or logs context information for debugging purposes. このステップはデバッグ目的でコンテキスト情報を印刷またはログ出力します。

Source code in src\agents_sdk_models\step.py
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
class DebugStep(Step):
    """
    Step for debugging and logging
    デバッグとログ用ステップ

    This step prints or logs context information for debugging purposes.
    このステップはデバッグ目的でコンテキスト情報を印刷またはログ出力します。
    """

    def __init__(self, name: str, message: str = "", print_context: bool = False, next_step: Optional[str] = None):
        """
        Initialize debug step
        デバッグステップを初期化

        Args:
            name: Step name / ステップ名
            message: Debug message / デバッグメッセージ
            print_context: Whether to print full context / 完全なコンテキストを印刷するか
            next_step: Next step / 次ステップ
        """
        super().__init__(name)
        self.message = message
        self.print_context = print_context
        self.next_step = next_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute debug step
        デバッグステップを実行

        Args:
            user_input: User input / ユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        # Print debug information
        # デバッグ情報を印刷
        print(f"🐛 DEBUG [{self.name}]: {self.message}")
        if user_input:
            print(f"   User Input: {user_input}")
        print(f"   Step Count: {ctx.step_count}")
        print(f"   Next Label: {ctx.next_label}")

        if self.print_context:
            print(f"   Context: {ctx.dict()}")

        # Add debug message to system messages
        # デバッグメッセージをシステムメッセージに追加
        ctx.add_system_message(f"DEBUG {self.name}: {self.message}")

        # Set next step if specified
        # 指定されている場合は次ステップを設定
        if self.next_step:
            ctx.goto(self.next_step)

        return ctx

__init__(name, message='', print_context=False, next_step=None)

Initialize debug step デバッグステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
message str

Debug message / デバッグメッセージ

''
print_context bool

Whether to print full context / 完全なコンテキストを印刷するか

False
next_step Optional[str]

Next step / 次ステップ

None
Source code in src\agents_sdk_models\step.py
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def __init__(self, name: str, message: str = "", print_context: bool = False, next_step: Optional[str] = None):
    """
    Initialize debug step
    デバッグステップを初期化

    Args:
        name: Step name / ステップ名
        message: Debug message / デバッグメッセージ
        print_context: Whether to print full context / 完全なコンテキストを印刷するか
        next_step: Next step / 次ステップ
    """
    super().__init__(name)
    self.message = message
    self.print_context = print_context
    self.next_step = next_step

run(user_input, ctx) async

Execute debug step デバッグステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input / ユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute debug step
    デバッグステップを実行

    Args:
        user_input: User input / ユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    # Print debug information
    # デバッグ情報を印刷
    print(f"🐛 DEBUG [{self.name}]: {self.message}")
    if user_input:
        print(f"   User Input: {user_input}")
    print(f"   Step Count: {ctx.step_count}")
    print(f"   Next Label: {ctx.next_label}")

    if self.print_context:
        print(f"   Context: {ctx.dict()}")

    # Add debug message to system messages
    # デバッグメッセージをシステムメッセージに追加
    ctx.add_system_message(f"DEBUG {self.name}: {self.message}")

    # Set next step if specified
    # 指定されている場合は次ステップを設定
    if self.next_step:
        ctx.goto(self.next_step)

    return ctx

EvaluationResult dataclass

Result of evaluation for generated content 生成されたコンテンツの評価結果を保持するクラス

Attributes:

Name Type Description
score int

Evaluation score (0-100) / 評価スコア(0-100)

comment List[Comment]

List of Comment instances containing importance and content / 重要度と内容を持つCommentクラスのリスト

Source code in src\agents_sdk_models\pipeline.py
46
47
48
49
50
51
52
53
54
55
56
57
@dataclass
class EvaluationResult:
    """
    Result of evaluation for generated content
    生成されたコンテンツの評価結果を保持するクラス

    Attributes:
        score: Evaluation score (0-100) / 評価スコア(0-100)
        comment: List of Comment instances containing importance and content / 重要度と内容を持つCommentクラスのリスト
    """
    score: int  # Evaluation score (0-100) / 評価スコア(0-100)
    comment: List[Comment]  # List of evaluation comments / 評価コメントのリスト

Flow

Flow orchestration engine for Step-based workflows ステップベースワークフロー用フローオーケストレーションエンジン

This class provides: このクラスは以下を提供します: - Declarative step-based workflow definition / 宣言的ステップベースワークフロー定義 - Synchronous and asynchronous execution modes / 同期・非同期実行モード - User input coordination for interactive workflows / 対話的ワークフロー用ユーザー入力調整 - Error handling and observability / エラーハンドリングとオブザーバビリティ

Source code in src\agents_sdk_models\flow.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
class Flow:
    """
    Flow orchestration engine for Step-based workflows
    ステップベースワークフロー用フローオーケストレーションエンジン

    This class provides:
    このクラスは以下を提供します:
    - Declarative step-based workflow definition / 宣言的ステップベースワークフロー定義
    - Synchronous and asynchronous execution modes / 同期・非同期実行モード
    - User input coordination for interactive workflows / 対話的ワークフロー用ユーザー入力調整
    - Error handling and observability / エラーハンドリングとオブザーバビリティ
    """

    def __init__(
        self, 
        start: Optional[str] = None, 
        steps: Optional[Union[Dict[str, Step], List[Step], Step]] = None, 
        context: Optional[Context] = None,
        max_steps: int = 1000,
        trace_id: Optional[str] = None
    ):
        """
        Initialize Flow with flexible step definitions
        柔軟なステップ定義でFlowを初期化

        This constructor now supports three ways to define steps:
        このコンストラクタは3つの方法でステップを定義できます:
        1. Traditional: start step name + Dict[str, Step]
        2. Sequential: List[Step] (creates sequential workflow)
        3. Single: Single Step (creates single-step workflow)

        Args:
            start: Start step label (optional for List/Single mode) / 開始ステップラベル(List/Singleモードでは省略可)
            steps: Step definitions - Dict[str, Step], List[Step], or Step / ステップ定義 - Dict[str, Step]、List[Step]、またはStep
            context: Initial context (optional) / 初期コンテキスト(オプション)
            max_steps: Maximum number of steps to prevent infinite loops / 無限ループ防止のための最大ステップ数
            trace_id: Trace ID for observability / オブザーバビリティ用トレースID
        """
        # Handle flexible step definitions
        # 柔軟なステップ定義を処理
        if isinstance(steps, dict):
            # Traditional mode: Dict[str, Step]
            # 従来モード: Dict[str, Step]
            if start is None:
                raise ValueError("start parameter is required when steps is a dictionary")
            self.start = start
            self.steps = steps
        elif isinstance(steps, list):
            # Sequential mode: List[Step] 
            # シーケンシャルモード: List[Step]
            if not steps:
                raise ValueError("Steps list cannot be empty")
            self.steps = {}
            prev_step_name = None

            for i, step in enumerate(steps):
                if not hasattr(step, 'name'):
                    raise ValueError(f"Step at index {i} must have a 'name' attribute")

                step_name = step.name
                self.steps[step_name] = step

                # Set sequential flow: each step goes to next step
                # シーケンシャルフロー設定: 各ステップが次のステップに進む
                if prev_step_name is not None and hasattr(self.steps[prev_step_name], 'next_step'):
                    if self.steps[prev_step_name].next_step is None:
                        self.steps[prev_step_name].next_step = step_name

                prev_step_name = step_name

            # Start with first step
            # 最初のステップから開始
            self.start = steps[0].name

        elif steps is not None:
            # Check if it's a Step instance
            # Stepインスタンスかどうかをチェック
            if isinstance(steps, Step):
                # Single step mode: Step
                # 単一ステップモード: Step
                if not hasattr(steps, 'name'):
                    raise ValueError("Step must have a 'name' attribute")

                step_name = steps.name
                self.start = step_name
                self.steps = {step_name: steps}
            else:
                # Not a valid type
                # 有効なタイプではない
                raise ValueError("steps must be Dict[str, Step], List[Step], or Step")
        else:
            raise ValueError("steps parameter cannot be None")

        self.context = context or Context()
        self.max_steps = max_steps
        self.trace_id = trace_id or f"flow_{datetime.now().strftime('%Y%m%d_%H%M%S')}"

        # Initialize context
        # コンテキストを初期化
        self.context.trace_id = self.trace_id
        self.context.next_label = self.start

        # Execution state
        # 実行状態
        self._running = False
        self._run_loop_task: Optional[asyncio.Task] = None
        self._execution_lock = asyncio.Lock()

        # Hooks for observability
        # オブザーバビリティ用フック
        self.before_step_hooks: List[Callable[[str, Context], None]] = []
        self.after_step_hooks: List[Callable[[str, Context, Any], None]] = []
        self.error_hooks: List[Callable[[str, Context, Exception], None]] = []

    @property
    def finished(self) -> bool:
        """
        Check if flow is finished
        フローが完了しているかチェック

        Returns:
            bool: True if finished / 完了している場合True
        """
        return self.context.is_finished()

    @property
    def current_step_name(self) -> Optional[str]:
        """
        Get current step name
        現在のステップ名を取得

        Returns:
            str | None: Current step name / 現在のステップ名
        """
        return self.context.current_step

    @property
    def next_step_name(self) -> Optional[str]:
        """
        Get next step name
        次のステップ名を取得

        Returns:
            str | None: Next step name / 次のステップ名
        """
        return self.context.next_label

    async def run(self, input_data: Optional[str] = None, initial_input: Optional[str] = None) -> Context:
        """
        Run flow to completion without user input coordination
        ユーザー入力調整なしでフローを完了まで実行

        This is for non-interactive workflows that don't require user input.
        これはユーザー入力が不要な非対話的ワークフロー用です。

        Args:
            input_data: Input data to the flow (preferred parameter name) / フローへの入力データ(推奨パラメータ名)
            initial_input: Initial input to the flow (deprecated, use input_data) / フローへの初期入力(非推奨、input_dataを使用)

        Returns:
            Context: Final context / 最終コンテキスト

        Raises:
            FlowExecutionError: If execution fails / 実行失敗時
        """
        async with self._execution_lock:
            try:
                self._running = True

                # Reset context for new execution
                # 新しい実行用にコンテキストをリセット
                if self.context.step_count > 0:
                    self.context = Context(trace_id=self.trace_id)
                    self.context.next_label = self.start

                # Determine input to use (input_data takes precedence)
                # 使用する入力を決定(input_dataが優先)
                effective_input = input_data or initial_input

                # Add input if provided
                # 入力が提供されている場合は追加
                if effective_input:
                    self.context.add_user_message(effective_input)

                current_input = effective_input
                step_count = 0

                while not self.finished and step_count < self.max_steps:
                    step_name = self.context.next_label
                    if not step_name or step_name not in self.steps:
                        break

                    step = self.steps[step_name]

                    # Execute step
                    # ステップを実行
                    try:
                        await self._execute_step(step, current_input)
                        current_input = None  # Only use initial input for first step
                        step_count += 1

                        # If step is waiting for user input, break
                        # ステップがユーザー入力を待機している場合、中断
                        if self.context.awaiting_user_input:
                            break

                    except Exception as e:
                        logger.error(f"Error executing step {step_name}: {e}")
                        self._handle_step_error(step_name, e)
                        break

                # Check for infinite loop
                # 無限ループのチェック
                if step_count >= self.max_steps:
                    raise FlowExecutionError(f"Flow exceeded maximum steps ({self.max_steps})")

                return self.context

            finally:
                self._running = False

    async def run_loop(self) -> None:
        """
        Run flow as background task with user input coordination
        ユーザー入力調整を含むバックグラウンドタスクとしてフローを実行

        This method runs the flow continuously, pausing when user input is needed.
        このメソッドはフローを継続的に実行し、ユーザー入力が必要な時に一時停止します。
        Use feed() to provide user input when the flow is waiting.
        フローが待機している時はfeed()を使用してユーザー入力を提供してください。
        """
        async with self._execution_lock:
            try:
                self._running = True

                # Reset context for new execution
                # 新しい実行用にコンテキストをリセット
                if self.context.step_count > 0:
                    self.context = Context(trace_id=self.trace_id)
                    self.context.next_label = self.start

                step_count = 0
                current_input = None

                while not self.finished and step_count < self.max_steps:
                    step_name = self.context.next_label
                    if not step_name or step_name not in self.steps:
                        break

                    step = self.steps[step_name]

                    # Execute step
                    # ステップを実行
                    try:
                        await self._execute_step(step, current_input)
                        current_input = None
                        step_count += 1

                        # If step is waiting for user input, wait for feed()
                        # ステップがユーザー入力を待機している場合、feed()を待つ
                        if self.context.awaiting_user_input:
                            await self.context.wait_for_user_input()
                            # After receiving input, continue with the same step
                            # 入力受信後、同じステップで継続
                            current_input = self.context.last_user_input
                            continue

                    except Exception as e:
                        logger.error(f"Error executing step {step_name}: {e}")
                        self._handle_step_error(step_name, e)
                        break

                # Check for infinite loop
                # 無限ループのチェック
                if step_count >= self.max_steps:
                    raise FlowExecutionError(f"Flow exceeded maximum steps ({self.max_steps})")

            finally:
                self._running = False

    def next_prompt(self) -> Optional[str]:
        """
        Get next prompt for synchronous CLI usage
        同期CLI使用用の次のプロンプトを取得

        Returns:
            str | None: Prompt if waiting for user input / ユーザー入力待ちの場合のプロンプト
        """
        return self.context.clear_prompt()

    def feed(self, user_input: str) -> None:
        """
        Provide user input to the flow
        フローにユーザー入力を提供

        Args:
            user_input: User input text / ユーザー入力テキスト
        """
        self.context.provide_user_input(user_input)

    def step(self) -> None:
        """
        Execute one step synchronously
        1ステップを同期的に実行

        This method executes one step and returns immediately.
        このメソッドは1ステップを実行してすぐに返ります。
        Use for synchronous CLI applications.
        同期CLIアプリケーション用に使用してください。
        """
        if self.finished:
            return

        step_name = self.context.next_label
        if not step_name or step_name not in self.steps:
            self.context.finish()
            return

        step = self.steps[step_name]

        # Run step in event loop
        # イベントループでステップを実行
        try:
            loop = asyncio.get_event_loop()
            if loop.is_running():
                # If loop is running, create a task
                # ループが実行中の場合、タスクを作成
                task = asyncio.create_task(self._execute_step(step, None))
                # This is a synchronous method, so we can't await
                # これは同期メソッドなので、awaitできない
                # The task will run in the background
                # タスクはバックグラウンドで実行される
            else:
                # If no loop is running, run until complete
                # ループが実行されていない場合、完了まで実行
                loop.run_until_complete(self._execute_step(step, None))
        except Exception as e:
            logger.error(f"Error executing step {step_name}: {e}")
            self._handle_step_error(step_name, e)

    async def _execute_step(self, step: Step, user_input: Optional[str]) -> None:
        """
        Execute a single step with hooks and error handling
        フックとエラーハンドリングで単一ステップを実行

        Args:
            step: Step to execute / 実行するステップ
            user_input: User input if any / ユーザー入力(あれば)
        """
        step_name = step.name

        # Before step hooks
        # ステップ前フック
        for hook in self.before_step_hooks:
            try:
                hook(step_name, self.context)
            except Exception as e:
                logger.warning(f"Before step hook error: {e}")

        start_time = datetime.now()
        result = None
        error = None

        try:
            # Execute step
            # ステップを実行
            result = await step.run(user_input, self.context)
            if result != self.context:
                # Step returned a new context, use it
                # ステップが新しいコンテキストを返した場合、それを使用
                self.context = result

            logger.debug(f"Step {step_name} completed in {datetime.now() - start_time}")

        except Exception as e:
            error = e
            logger.error(f"Step {step_name} failed: {e}")
            logger.debug(traceback.format_exc())

            # Add error to context
            # エラーをコンテキストに追加
            self.context.add_system_message(f"Step {step_name} failed: {str(e)}")

            # Call error hooks
            # エラーフックを呼び出し
            for hook in self.error_hooks:
                try:
                    hook(step_name, self.context, e)
                except Exception as hook_error:
                    logger.warning(f"Error hook failed: {hook_error}")

            raise e

        finally:
            # After step hooks
            # ステップ後フック
            for hook in self.after_step_hooks:
                try:
                    hook(step_name, self.context, result)
                except Exception as e:
                    logger.warning(f"After step hook error: {e}")

    def _handle_step_error(self, step_name: str, error: Exception) -> None:
        """
        Handle step execution error
        ステップ実行エラーを処理

        Args:
            step_name: Name of the failed step / 失敗したステップの名前
            error: The error that occurred / 発生したエラー
        """
        # Mark flow as finished on error
        # エラー時はフローを完了としてマーク
        self.context.finish()
        self.context.set_artifact("error", {
            "step": step_name,
            "error": str(error),
            "type": type(error).__name__
        })

    def add_hook(
        self, 
        hook_type: str, 
        callback: Callable
    ) -> None:
        """
        Add observability hook
        オブザーバビリティフックを追加

        Args:
            hook_type: Type of hook ("before_step", "after_step", "error") / フックタイプ
            callback: Callback function / コールバック関数
        """
        if hook_type == "before_step":
            self.before_step_hooks.append(callback)
        elif hook_type == "after_step":
            self.after_step_hooks.append(callback)
        elif hook_type == "error":
            self.error_hooks.append(callback)
        else:
            raise ValueError(f"Unknown hook type: {hook_type}")

    def get_step_history(self) -> List[Dict[str, Any]]:
        """
        Get execution history
        実行履歴を取得

        Returns:
            List[Dict[str, Any]]: Step execution history / ステップ実行履歴
        """
        history = []
        for msg in self.context.messages:
            if msg.role == "system" and "Step" in msg.content:
                history.append({
                    "timestamp": msg.timestamp,
                    "message": msg.content,
                    "metadata": msg.metadata
                })
        return history

    def get_flow_summary(self) -> Dict[str, Any]:
        """
        Get flow execution summary
        フロー実行サマリーを取得

        Returns:
            Dict[str, Any]: Flow summary / フローサマリー
        """
        return {
            "trace_id": self.trace_id,
            "start_step": self.start,
            "current_step": self.current_step_name,
            "next_step": self.next_step_name,
            "step_count": self.context.step_count,
            "finished": self.finished,
            "start_time": self.context.start_time,
            "artifacts": self.context.artifacts,
            "message_count": len(self.context.messages)
        }

    def reset(self) -> None:
        """
        Reset flow to initial state
        フローを初期状態にリセット
        """
        self.context = Context(trace_id=self.trace_id)
        self.context.next_label = self.start
        self._running = False
        if self._run_loop_task:
            self._run_loop_task.cancel()
            self._run_loop_task = None

    def stop(self) -> None:
        """
        Stop flow execution
        フロー実行を停止
        """
        self._running = False
        self.context.finish()
        if self._run_loop_task:
            self._run_loop_task.cancel()
            self._run_loop_task = None

    async def start_background_task(self) -> asyncio.Task:
        """
        Start flow as background task
        フローをバックグラウンドタスクとして開始

        Returns:
            asyncio.Task: Background task / バックグラウンドタスク
        """
        if self._run_loop_task and not self._run_loop_task.done():
            raise RuntimeError("Flow is already running as background task")

        self._run_loop_task = asyncio.create_task(self.run_loop())
        return self._run_loop_task

    def __str__(self) -> str:
        """String representation of flow"""
        return f"Flow(start={self.start}, steps={len(self.steps)}, finished={self.finished})"

    def __repr__(self) -> str:
        return self.__str__()

current_step_name property

Get current step name 現在のステップ名を取得

Returns:

Type Description
Optional[str]

str | None: Current step name / 現在のステップ名

finished property

Check if flow is finished フローが完了しているかチェック

Returns:

Name Type Description
bool bool

True if finished / 完了している場合True

next_step_name property

Get next step name 次のステップ名を取得

Returns:

Type Description
Optional[str]

str | None: Next step name / 次のステップ名

__init__(start=None, steps=None, context=None, max_steps=1000, trace_id=None)

Initialize Flow with flexible step definitions 柔軟なステップ定義でFlowを初期化

This constructor now supports three ways to define steps: このコンストラクタは3つの方法でステップを定義できます: 1. Traditional: start step name + Dict[str, Step] 2. Sequential: List[Step] (creates sequential workflow) 3. Single: Single Step (creates single-step workflow)

Parameters:

Name Type Description Default
start Optional[str]

Start step label (optional for List/Single mode) / 開始ステップラベル(List/Singleモードでは省略可)

None
steps Optional[Union[Dict[str, Step], List[Step], Step]]

Step definitions - Dict[str, Step], List[Step], or Step / ステップ定義 - Dict[str, Step]、List[Step]、またはStep

None
context Optional[Context]

Initial context (optional) / 初期コンテキスト(オプション)

None
max_steps int

Maximum number of steps to prevent infinite loops / 無限ループ防止のための最大ステップ数

1000
trace_id Optional[str]

Trace ID for observability / オブザーバビリティ用トレースID

None
Source code in src\agents_sdk_models\flow.py
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def __init__(
    self, 
    start: Optional[str] = None, 
    steps: Optional[Union[Dict[str, Step], List[Step], Step]] = None, 
    context: Optional[Context] = None,
    max_steps: int = 1000,
    trace_id: Optional[str] = None
):
    """
    Initialize Flow with flexible step definitions
    柔軟なステップ定義でFlowを初期化

    This constructor now supports three ways to define steps:
    このコンストラクタは3つの方法でステップを定義できます:
    1. Traditional: start step name + Dict[str, Step]
    2. Sequential: List[Step] (creates sequential workflow)
    3. Single: Single Step (creates single-step workflow)

    Args:
        start: Start step label (optional for List/Single mode) / 開始ステップラベル(List/Singleモードでは省略可)
        steps: Step definitions - Dict[str, Step], List[Step], or Step / ステップ定義 - Dict[str, Step]、List[Step]、またはStep
        context: Initial context (optional) / 初期コンテキスト(オプション)
        max_steps: Maximum number of steps to prevent infinite loops / 無限ループ防止のための最大ステップ数
        trace_id: Trace ID for observability / オブザーバビリティ用トレースID
    """
    # Handle flexible step definitions
    # 柔軟なステップ定義を処理
    if isinstance(steps, dict):
        # Traditional mode: Dict[str, Step]
        # 従来モード: Dict[str, Step]
        if start is None:
            raise ValueError("start parameter is required when steps is a dictionary")
        self.start = start
        self.steps = steps
    elif isinstance(steps, list):
        # Sequential mode: List[Step] 
        # シーケンシャルモード: List[Step]
        if not steps:
            raise ValueError("Steps list cannot be empty")
        self.steps = {}
        prev_step_name = None

        for i, step in enumerate(steps):
            if not hasattr(step, 'name'):
                raise ValueError(f"Step at index {i} must have a 'name' attribute")

            step_name = step.name
            self.steps[step_name] = step

            # Set sequential flow: each step goes to next step
            # シーケンシャルフロー設定: 各ステップが次のステップに進む
            if prev_step_name is not None and hasattr(self.steps[prev_step_name], 'next_step'):
                if self.steps[prev_step_name].next_step is None:
                    self.steps[prev_step_name].next_step = step_name

            prev_step_name = step_name

        # Start with first step
        # 最初のステップから開始
        self.start = steps[0].name

    elif steps is not None:
        # Check if it's a Step instance
        # Stepインスタンスかどうかをチェック
        if isinstance(steps, Step):
            # Single step mode: Step
            # 単一ステップモード: Step
            if not hasattr(steps, 'name'):
                raise ValueError("Step must have a 'name' attribute")

            step_name = steps.name
            self.start = step_name
            self.steps = {step_name: steps}
        else:
            # Not a valid type
            # 有効なタイプではない
            raise ValueError("steps must be Dict[str, Step], List[Step], or Step")
    else:
        raise ValueError("steps parameter cannot be None")

    self.context = context or Context()
    self.max_steps = max_steps
    self.trace_id = trace_id or f"flow_{datetime.now().strftime('%Y%m%d_%H%M%S')}"

    # Initialize context
    # コンテキストを初期化
    self.context.trace_id = self.trace_id
    self.context.next_label = self.start

    # Execution state
    # 実行状態
    self._running = False
    self._run_loop_task: Optional[asyncio.Task] = None
    self._execution_lock = asyncio.Lock()

    # Hooks for observability
    # オブザーバビリティ用フック
    self.before_step_hooks: List[Callable[[str, Context], None]] = []
    self.after_step_hooks: List[Callable[[str, Context, Any], None]] = []
    self.error_hooks: List[Callable[[str, Context, Exception], None]] = []

__str__()

String representation of flow

Source code in src\agents_sdk_models\flow.py
547
548
549
def __str__(self) -> str:
    """String representation of flow"""
    return f"Flow(start={self.start}, steps={len(self.steps)}, finished={self.finished})"

add_hook(hook_type, callback)

Add observability hook オブザーバビリティフックを追加

Parameters:

Name Type Description Default
hook_type str

Type of hook ("before_step", "after_step", "error") / フックタイプ

required
callback Callable

Callback function / コールバック関数

required
Source code in src\agents_sdk_models\flow.py
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
def add_hook(
    self, 
    hook_type: str, 
    callback: Callable
) -> None:
    """
    Add observability hook
    オブザーバビリティフックを追加

    Args:
        hook_type: Type of hook ("before_step", "after_step", "error") / フックタイプ
        callback: Callback function / コールバック関数
    """
    if hook_type == "before_step":
        self.before_step_hooks.append(callback)
    elif hook_type == "after_step":
        self.after_step_hooks.append(callback)
    elif hook_type == "error":
        self.error_hooks.append(callback)
    else:
        raise ValueError(f"Unknown hook type: {hook_type}")

feed(user_input)

Provide user input to the flow フローにユーザー入力を提供

Parameters:

Name Type Description Default
user_input str

User input text / ユーザー入力テキスト

required
Source code in src\agents_sdk_models\flow.py
320
321
322
323
324
325
326
327
328
def feed(self, user_input: str) -> None:
    """
    Provide user input to the flow
    フローにユーザー入力を提供

    Args:
        user_input: User input text / ユーザー入力テキスト
    """
    self.context.provide_user_input(user_input)

get_flow_summary()

Get flow execution summary フロー実行サマリーを取得

Returns:

Type Description
Dict[str, Any]

Dict[str, Any]: Flow summary / フローサマリー

Source code in src\agents_sdk_models\flow.py
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
def get_flow_summary(self) -> Dict[str, Any]:
    """
    Get flow execution summary
    フロー実行サマリーを取得

    Returns:
        Dict[str, Any]: Flow summary / フローサマリー
    """
    return {
        "trace_id": self.trace_id,
        "start_step": self.start,
        "current_step": self.current_step_name,
        "next_step": self.next_step_name,
        "step_count": self.context.step_count,
        "finished": self.finished,
        "start_time": self.context.start_time,
        "artifacts": self.context.artifacts,
        "message_count": len(self.context.messages)
    }

get_step_history()

Get execution history 実行履歴を取得

Returns:

Type Description
List[Dict[str, Any]]

List[Dict[str, Any]]: Step execution history / ステップ実行履歴

Source code in src\agents_sdk_models\flow.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
def get_step_history(self) -> List[Dict[str, Any]]:
    """
    Get execution history
    実行履歴を取得

    Returns:
        List[Dict[str, Any]]: Step execution history / ステップ実行履歴
    """
    history = []
    for msg in self.context.messages:
        if msg.role == "system" and "Step" in msg.content:
            history.append({
                "timestamp": msg.timestamp,
                "message": msg.content,
                "metadata": msg.metadata
            })
    return history

next_prompt()

Get next prompt for synchronous CLI usage 同期CLI使用用の次のプロンプトを取得

Returns:

Type Description
Optional[str]

str | None: Prompt if waiting for user input / ユーザー入力待ちの場合のプロンプト

Source code in src\agents_sdk_models\flow.py
310
311
312
313
314
315
316
317
318
def next_prompt(self) -> Optional[str]:
    """
    Get next prompt for synchronous CLI usage
    同期CLI使用用の次のプロンプトを取得

    Returns:
        str | None: Prompt if waiting for user input / ユーザー入力待ちの場合のプロンプト
    """
    return self.context.clear_prompt()

reset()

Reset flow to initial state フローを初期状態にリセット

Source code in src\agents_sdk_models\flow.py
510
511
512
513
514
515
516
517
518
519
520
def reset(self) -> None:
    """
    Reset flow to initial state
    フローを初期状態にリセット
    """
    self.context = Context(trace_id=self.trace_id)
    self.context.next_label = self.start
    self._running = False
    if self._run_loop_task:
        self._run_loop_task.cancel()
        self._run_loop_task = None

run(input_data=None, initial_input=None) async

Run flow to completion without user input coordination ユーザー入力調整なしでフローを完了まで実行

This is for non-interactive workflows that don't require user input. これはユーザー入力が不要な非対話的ワークフロー用です。

Parameters:

Name Type Description Default
input_data Optional[str]

Input data to the flow (preferred parameter name) / フローへの入力データ(推奨パラメータ名)

None
initial_input Optional[str]

Initial input to the flow (deprecated, use input_data) / フローへの初期入力(非推奨、input_dataを使用)

None

Returns:

Name Type Description
Context Context

Final context / 最終コンテキスト

Raises:

Type Description
FlowExecutionError

If execution fails / 実行失敗時

Source code in src\agents_sdk_models\flow.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
async def run(self, input_data: Optional[str] = None, initial_input: Optional[str] = None) -> Context:
    """
    Run flow to completion without user input coordination
    ユーザー入力調整なしでフローを完了まで実行

    This is for non-interactive workflows that don't require user input.
    これはユーザー入力が不要な非対話的ワークフロー用です。

    Args:
        input_data: Input data to the flow (preferred parameter name) / フローへの入力データ(推奨パラメータ名)
        initial_input: Initial input to the flow (deprecated, use input_data) / フローへの初期入力(非推奨、input_dataを使用)

    Returns:
        Context: Final context / 最終コンテキスト

    Raises:
        FlowExecutionError: If execution fails / 実行失敗時
    """
    async with self._execution_lock:
        try:
            self._running = True

            # Reset context for new execution
            # 新しい実行用にコンテキストをリセット
            if self.context.step_count > 0:
                self.context = Context(trace_id=self.trace_id)
                self.context.next_label = self.start

            # Determine input to use (input_data takes precedence)
            # 使用する入力を決定(input_dataが優先)
            effective_input = input_data or initial_input

            # Add input if provided
            # 入力が提供されている場合は追加
            if effective_input:
                self.context.add_user_message(effective_input)

            current_input = effective_input
            step_count = 0

            while not self.finished and step_count < self.max_steps:
                step_name = self.context.next_label
                if not step_name or step_name not in self.steps:
                    break

                step = self.steps[step_name]

                # Execute step
                # ステップを実行
                try:
                    await self._execute_step(step, current_input)
                    current_input = None  # Only use initial input for first step
                    step_count += 1

                    # If step is waiting for user input, break
                    # ステップがユーザー入力を待機している場合、中断
                    if self.context.awaiting_user_input:
                        break

                except Exception as e:
                    logger.error(f"Error executing step {step_name}: {e}")
                    self._handle_step_error(step_name, e)
                    break

            # Check for infinite loop
            # 無限ループのチェック
            if step_count >= self.max_steps:
                raise FlowExecutionError(f"Flow exceeded maximum steps ({self.max_steps})")

            return self.context

        finally:
            self._running = False

run_loop() async

Run flow as background task with user input coordination ユーザー入力調整を含むバックグラウンドタスクとしてフローを実行

This method runs the flow continuously, pausing when user input is needed. このメソッドはフローを継続的に実行し、ユーザー入力が必要な時に一時停止します。 Use feed() to provide user input when the flow is waiting. フローが待機している時はfeed()を使用してユーザー入力を提供してください。

Source code in src\agents_sdk_models\flow.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
async def run_loop(self) -> None:
    """
    Run flow as background task with user input coordination
    ユーザー入力調整を含むバックグラウンドタスクとしてフローを実行

    This method runs the flow continuously, pausing when user input is needed.
    このメソッドはフローを継続的に実行し、ユーザー入力が必要な時に一時停止します。
    Use feed() to provide user input when the flow is waiting.
    フローが待機している時はfeed()を使用してユーザー入力を提供してください。
    """
    async with self._execution_lock:
        try:
            self._running = True

            # Reset context for new execution
            # 新しい実行用にコンテキストをリセット
            if self.context.step_count > 0:
                self.context = Context(trace_id=self.trace_id)
                self.context.next_label = self.start

            step_count = 0
            current_input = None

            while not self.finished and step_count < self.max_steps:
                step_name = self.context.next_label
                if not step_name or step_name not in self.steps:
                    break

                step = self.steps[step_name]

                # Execute step
                # ステップを実行
                try:
                    await self._execute_step(step, current_input)
                    current_input = None
                    step_count += 1

                    # If step is waiting for user input, wait for feed()
                    # ステップがユーザー入力を待機している場合、feed()を待つ
                    if self.context.awaiting_user_input:
                        await self.context.wait_for_user_input()
                        # After receiving input, continue with the same step
                        # 入力受信後、同じステップで継続
                        current_input = self.context.last_user_input
                        continue

                except Exception as e:
                    logger.error(f"Error executing step {step_name}: {e}")
                    self._handle_step_error(step_name, e)
                    break

            # Check for infinite loop
            # 無限ループのチェック
            if step_count >= self.max_steps:
                raise FlowExecutionError(f"Flow exceeded maximum steps ({self.max_steps})")

        finally:
            self._running = False

start_background_task() async

Start flow as background task フローをバックグラウンドタスクとして開始

Returns:

Type Description
Task

asyncio.Task: Background task / バックグラウンドタスク

Source code in src\agents_sdk_models\flow.py
533
534
535
536
537
538
539
540
541
542
543
544
545
async def start_background_task(self) -> asyncio.Task:
    """
    Start flow as background task
    フローをバックグラウンドタスクとして開始

    Returns:
        asyncio.Task: Background task / バックグラウンドタスク
    """
    if self._run_loop_task and not self._run_loop_task.done():
        raise RuntimeError("Flow is already running as background task")

    self._run_loop_task = asyncio.create_task(self.run_loop())
    return self._run_loop_task

step()

Execute one step synchronously 1ステップを同期的に実行

This method executes one step and returns immediately. このメソッドは1ステップを実行してすぐに返ります。 Use for synchronous CLI applications. 同期CLIアプリケーション用に使用してください。

Source code in src\agents_sdk_models\flow.py
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def step(self) -> None:
    """
    Execute one step synchronously
    1ステップを同期的に実行

    This method executes one step and returns immediately.
    このメソッドは1ステップを実行してすぐに返ります。
    Use for synchronous CLI applications.
    同期CLIアプリケーション用に使用してください。
    """
    if self.finished:
        return

    step_name = self.context.next_label
    if not step_name or step_name not in self.steps:
        self.context.finish()
        return

    step = self.steps[step_name]

    # Run step in event loop
    # イベントループでステップを実行
    try:
        loop = asyncio.get_event_loop()
        if loop.is_running():
            # If loop is running, create a task
            # ループが実行中の場合、タスクを作成
            task = asyncio.create_task(self._execute_step(step, None))
            # This is a synchronous method, so we can't await
            # これは同期メソッドなので、awaitできない
            # The task will run in the background
            # タスクはバックグラウンドで実行される
        else:
            # If no loop is running, run until complete
            # ループが実行されていない場合、完了まで実行
            loop.run_until_complete(self._execute_step(step, None))
    except Exception as e:
        logger.error(f"Error executing step {step_name}: {e}")
        self._handle_step_error(step_name, e)

stop()

Stop flow execution フロー実行を停止

Source code in src\agents_sdk_models\flow.py
522
523
524
525
526
527
528
529
530
531
def stop(self) -> None:
    """
    Stop flow execution
    フロー実行を停止
    """
    self._running = False
    self.context.finish()
    if self._run_loop_task:
        self._run_loop_task.cancel()
        self._run_loop_task = None

FlowExecutionError

Bases: Exception

Exception raised during flow execution フロー実行中に発生する例外

Source code in src\agents_sdk_models\flow.py
22
23
24
25
26
27
class FlowExecutionError(Exception):
    """
    Exception raised during flow execution
    フロー実行中に発生する例外
    """
    pass

ForkStep

Bases: Step

Step that executes multiple branches in parallel 複数のブランチを並列実行するステップ

This step starts multiple sub-flows concurrently and collects their results. このステップは複数のサブフローを同時に開始し、結果を収集します。

Source code in src\agents_sdk_models\step.py
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
class ForkStep(Step):
    """
    Step that executes multiple branches in parallel
    複数のブランチを並列実行するステップ

    This step starts multiple sub-flows concurrently and collects their results.
    このステップは複数のサブフローを同時に開始し、結果を収集します。
    """

    def __init__(self, name: str, branches: List[str], join_step: str):
        """
        Initialize fork step
        フォークステップを初期化

        Args:
            name: Step name / ステップ名
            branches: List of branch step names to execute in parallel / 並列実行するブランチステップ名のリスト
            join_step: Step to join results / 結果を結合するステップ
        """
        super().__init__(name)
        self.branches = branches
        self.join_step = join_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute fork step
        フォークステップを実行

        Args:
            user_input: User input / ユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        # Store branch information for join step
        # ジョインステップ用にブランチ情報を保存
        ctx.shared_state[f"{self.name}_branches"] = self.branches
        ctx.shared_state[f"{self.name}_started"] = True

        # For now, just route to the join step
        # 現在のところ、ジョインステップにルーティングするだけ
        # In a full implementation, this would start parallel execution
        # 完全な実装では、これは並列実行を開始する
        ctx.goto(self.join_step)

        return ctx

__init__(name, branches, join_step)

Initialize fork step フォークステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
branches List[str]

List of branch step names to execute in parallel / 並列実行するブランチステップ名のリスト

required
join_step str

Step to join results / 結果を結合するステップ

required
Source code in src\agents_sdk_models\step.py
251
252
253
254
255
256
257
258
259
260
261
262
263
def __init__(self, name: str, branches: List[str], join_step: str):
    """
    Initialize fork step
    フォークステップを初期化

    Args:
        name: Step name / ステップ名
        branches: List of branch step names to execute in parallel / 並列実行するブランチステップ名のリスト
        join_step: Step to join results / 結果を結合するステップ
    """
    super().__init__(name)
    self.branches = branches
    self.join_step = join_step

run(user_input, ctx) async

Execute fork step フォークステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input / ユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute fork step
    フォークステップを実行

    Args:
        user_input: User input / ユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    # Store branch information for join step
    # ジョインステップ用にブランチ情報を保存
    ctx.shared_state[f"{self.name}_branches"] = self.branches
    ctx.shared_state[f"{self.name}_started"] = True

    # For now, just route to the join step
    # 現在のところ、ジョインステップにルーティングするだけ
    # In a full implementation, this would start parallel execution
    # 完全な実装では、これは並列実行を開始する
    ctx.goto(self.join_step)

    return ctx

FunctionStep

Bases: Step

Step that executes a custom function カスタム関数を実行するステップ

This step allows executing arbitrary code within the workflow. このステップはワークフロー内で任意のコードを実行できます。

Source code in src\agents_sdk_models\step.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
class FunctionStep(Step):
    """
    Step that executes a custom function
    カスタム関数を実行するステップ

    This step allows executing arbitrary code within the workflow.
    このステップはワークフロー内で任意のコードを実行できます。
    """

    def __init__(
        self, 
        name: str, 
        function: Callable[[Optional[str], Context], Union[Context, Awaitable[Context]]], 
        next_step: Optional[str] = None
    ):
        """
        Initialize function step
        関数ステップを初期化

        Args:
            name: Step name / ステップ名
            function: Function to execute / 実行する関数
            next_step: Next step after execution / 実行後の次ステップ
        """
        super().__init__(name)
        self.function = function
        self.next_step = next_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute function step
        関数ステップを実行

        Args:
            user_input: User input / ユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        try:
            # Execute the function (may be async)
            # 関数を実行(非同期の可能性あり)
            result = self.function(user_input, ctx)
            if asyncio.iscoroutine(result):
                ctx = await result
            else:
                ctx = result
        except Exception as e:
            ctx.add_system_message(f"Function execution error in {self.name}: {e}")

        # Set next step if specified
        # 指定されている場合は次ステップを設定
        if self.next_step:
            ctx.goto(self.next_step)

        return ctx

__init__(name, function, next_step=None)

Initialize function step 関数ステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
function Callable[[Optional[str], Context], Union[Context, Awaitable[Context]]]

Function to execute / 実行する関数

required
next_step Optional[str]

Next step after execution / 実行後の次ステップ

None
Source code in src\agents_sdk_models\step.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
def __init__(
    self, 
    name: str, 
    function: Callable[[Optional[str], Context], Union[Context, Awaitable[Context]]], 
    next_step: Optional[str] = None
):
    """
    Initialize function step
    関数ステップを初期化

    Args:
        name: Step name / ステップ名
        function: Function to execute / 実行する関数
        next_step: Next step after execution / 実行後の次ステップ
    """
    super().__init__(name)
    self.function = function
    self.next_step = next_step

run(user_input, ctx) async

Execute function step 関数ステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input / ユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute function step
    関数ステップを実行

    Args:
        user_input: User input / ユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    try:
        # Execute the function (may be async)
        # 関数を実行(非同期の可能性あり)
        result = self.function(user_input, ctx)
        if asyncio.iscoroutine(result):
            ctx = await result
        else:
            ctx = result
    except Exception as e:
        ctx.add_system_message(f"Function execution error in {self.name}: {e}")

    # Set next step if specified
    # 指定されている場合は次ステップを設定
    if self.next_step:
        ctx.goto(self.next_step)

    return ctx

GeminiModel

Bases: OpenAIChatCompletionsModel

Gemini model implementation that extends OpenAI's chat completions model OpenAIのチャット補完モデルを拡張したGeminiモデルの実装

Source code in src\agents_sdk_models\gemini.py
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
class GeminiModel(OpenAIChatCompletionsModel):
    """
    Gemini model implementation that extends OpenAI's chat completions model
    OpenAIのチャット補完モデルを拡張したGeminiモデルの実装
    """

    def __init__(
        self,
        model: str = "gemini-2.0-flash",
        temperature: float = 0.3,
        api_key: str = None,
        base_url: str = "https://generativelanguage.googleapis.com/v1beta/openai/",
        **kwargs: Any,
    ) -> None:
        """
        Initialize the Gemini model with OpenAI compatible interface
        OpenAI互換インターフェースでGeminiモデルを初期化する

        Args:
            model (str): Name of the Gemini model to use (e.g. "gemini-2.0-flash")
                使用するGeminiモデルの名前(例:"gemini-2.0-flash")
            temperature (float): Sampling temperature between 0 and 1
                サンプリング温度(0から1の間)
            api_key (str): Gemini API key
                Gemini APIキー
            base_url (str): Base URL for the Gemini API
                Gemini APIのベースURL
            **kwargs: Additional arguments to pass to the OpenAI API
                OpenAI APIに渡す追加の引数
        """
        if base_url == None:
            base_url = "https://generativelanguage.googleapis.com/v1beta/openai/"

        # api_key が None の場合は環境変数から取得
        if api_key is None:
            api_key = os.environ.get("GOOGLE_API_KEY")
            if api_key is None:
                raise ValueError("Google API key is required. Get one from https://ai.google.dev/")

        # Create AsyncOpenAI client with Gemini base URL
        # GeminiのベースURLでAsyncOpenAIクライアントを作成
        openai_client = AsyncOpenAI(base_url=base_url, api_key=api_key)

        # Store parameters for later use in API calls
        # 後でAPIコールで使用するためにパラメータを保存
        self.temperature = temperature
        self.kwargs = kwargs

        # Initialize the parent class with our custom client
        # カスタムクライアントで親クラスを初期化
        super().__init__(
            model=model,
            openai_client=openai_client
        )

    # Override methods that make API calls to include our parameters
    # APIコールを行うメソッドをオーバーライドして、パラメータを含める
    async def _create_chat_completion(self, *args, **kwargs):
        """Override to include temperature and other parameters"""
        kwargs["temperature"] = self.temperature
        kwargs.update(self.kwargs)
        return await super()._create_chat_completion(*args, **kwargs)

__init__(model='gemini-2.0-flash', temperature=0.3, api_key=None, base_url='https://generativelanguage.googleapis.com/v1beta/openai/', **kwargs)

Initialize the Gemini model with OpenAI compatible interface OpenAI互換インターフェースでGeminiモデルを初期化する

Parameters:

Name Type Description Default
model str

Name of the Gemini model to use (e.g. "gemini-2.0-flash") 使用するGeminiモデルの名前(例:"gemini-2.0-flash")

'gemini-2.0-flash'
temperature float

Sampling temperature between 0 and 1 サンプリング温度(0から1の間)

0.3
api_key str

Gemini API key Gemini APIキー

None
base_url str

Base URL for the Gemini API Gemini APIのベースURL

'https://generativelanguage.googleapis.com/v1beta/openai/'
**kwargs Any

Additional arguments to pass to the OpenAI API OpenAI APIに渡す追加の引数

{}
Source code in src\agents_sdk_models\gemini.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
def __init__(
    self,
    model: str = "gemini-2.0-flash",
    temperature: float = 0.3,
    api_key: str = None,
    base_url: str = "https://generativelanguage.googleapis.com/v1beta/openai/",
    **kwargs: Any,
) -> None:
    """
    Initialize the Gemini model with OpenAI compatible interface
    OpenAI互換インターフェースでGeminiモデルを初期化する

    Args:
        model (str): Name of the Gemini model to use (e.g. "gemini-2.0-flash")
            使用するGeminiモデルの名前(例:"gemini-2.0-flash")
        temperature (float): Sampling temperature between 0 and 1
            サンプリング温度(0から1の間)
        api_key (str): Gemini API key
            Gemini APIキー
        base_url (str): Base URL for the Gemini API
            Gemini APIのベースURL
        **kwargs: Additional arguments to pass to the OpenAI API
            OpenAI APIに渡す追加の引数
    """
    if base_url == None:
        base_url = "https://generativelanguage.googleapis.com/v1beta/openai/"

    # api_key が None の場合は環境変数から取得
    if api_key is None:
        api_key = os.environ.get("GOOGLE_API_KEY")
        if api_key is None:
            raise ValueError("Google API key is required. Get one from https://ai.google.dev/")

    # Create AsyncOpenAI client with Gemini base URL
    # GeminiのベースURLでAsyncOpenAIクライアントを作成
    openai_client = AsyncOpenAI(base_url=base_url, api_key=api_key)

    # Store parameters for later use in API calls
    # 後でAPIコールで使用するためにパラメータを保存
    self.temperature = temperature
    self.kwargs = kwargs

    # Initialize the parent class with our custom client
    # カスタムクライアントで親クラスを初期化
    super().__init__(
        model=model,
        openai_client=openai_client
    )

GenAgent

Bases: Step

Step implementation that wraps AgentPipeline functionality AgentPipeline機能をラップするStep実装

This class allows using AgentPipeline directly as a Step in Flow workflows, providing generation, evaluation, and retry capabilities within a workflow context. このクラスはAgentPipelineをFlowワークフロー内で直接Stepとして使用できるようにし、 ワークフローコンテキスト内で生成、評価、リトライ機能を提供します。

Source code in src\agents_sdk_models\gen_agent.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
class GenAgent(Step):
    """
    Step implementation that wraps AgentPipeline functionality
    AgentPipeline機能をラップするStep実装

    This class allows using AgentPipeline directly as a Step in Flow workflows,
    providing generation, evaluation, and retry capabilities within a workflow context.
    このクラスはAgentPipelineをFlowワークフロー内で直接Stepとして使用できるようにし、
    ワークフローコンテキスト内で生成、評価、リトライ機能を提供します。
    """

    def __init__(
        self,
        name: str,
        generation_instructions: str,
        evaluation_instructions: Optional[str] = None,
        *,
        input_guardrails: Optional[list] = None,
        output_guardrails: Optional[list] = None,
        output_model: Optional[Type[Any]] = None,
        model: str | None = None,
        evaluation_model: str | None = None,
        generation_tools: Optional[list] = None,
        evaluation_tools: Optional[list] = None,
        routing_func: Optional[Callable[[Any], Any]] = None,
        session_history: Optional[list] = None,
        history_size: int = 10,
        threshold: int = 85,
        retries: int = 3,
        improvement_callback: Optional[Callable[[Any, EvaluationResult], None]] = None,
        dynamic_prompt: Optional[Callable[[str], str]] = None,
        retry_comment_importance: Optional[list[str]] = None,
        locale: str = "en",
        next_step: Optional[str] = None,
        store_result_key: Optional[str] = None,
    ) -> None:
        """
        Initialize GenAgent with AgentPipeline configuration
        AgentPipeline設定でGenAgentを初期化する

        Args:
            name: Step name / ステップ名
            generation_instructions: System prompt for generation / 生成用システムプロンプト
            evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
            input_guardrails: Guardrails for generation / 生成用ガードレール
            output_guardrails: Guardrails for evaluation / 評価用ガードレール
            output_model: Model for output formatting / 出力フォーマット用モデル
            model: LLM model name / LLMモデル名
            evaluation_model: Optional LLM model name for evaluation / 評価用LLMモデル名(任意)
            generation_tools: Tools for generation / 生成用ツール
            evaluation_tools: Tools for evaluation / 評価用ツール
            routing_func: Function for output routing / 出力ルーティング用関数
            session_history: Session history / セッション履歴
            history_size: Size of history to keep / 保持する履歴サイズ
            threshold: Evaluation score threshold / 評価スコア閾値
            retries: Number of retry attempts / リトライ試行回数
            improvement_callback: Callback for improvement suggestions / 改善提案用コールバック
            dynamic_prompt: Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)
            retry_comment_importance: Importance levels of comments to include on retry / リトライ時コメント重要度レベル
            locale: Language code for localized messages / ローカライズメッセージ用言語コード
            next_step: Next step after pipeline execution / パイプライン実行後の次ステップ
            store_result_key: Key to store result in context shared_state / コンテキスト共有状態に結果を格納するキー
        """
        # Initialize Step base class
        # Step基底クラスを初期化
        super().__init__(name)

        # Store flow-specific configuration
        # フロー固有の設定を保存
        self.next_step = next_step
        self.store_result_key = store_result_key or f"{name}_result"

        # Create internal AgentPipeline instance
        # 内部AgentPipelineインスタンスを作成
        self.pipeline = AgentPipeline(
            name=f"{name}_pipeline",
            generation_instructions=generation_instructions,
            evaluation_instructions=evaluation_instructions,
            input_guardrails=input_guardrails,
            output_guardrails=output_guardrails,
            output_model=output_model,
            model=model,
            evaluation_model=evaluation_model,
            generation_tools=generation_tools,
            evaluation_tools=evaluation_tools,
            routing_func=routing_func,
            session_history=session_history,
            history_size=history_size,
            threshold=threshold,
            retries=retries,
            improvement_callback=improvement_callback,
            dynamic_prompt=dynamic_prompt,
            retry_comment_importance=retry_comment_importance,
            locale=locale,
        )

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute GenAgent step using AgentPipeline
        AgentPipelineを使用してGenAgentステップを実行する

        Args:
            user_input: User input for the pipeline / パイプライン用ユーザー入力
            ctx: Current workflow context / 現在のワークフローコンテキスト

        Returns:
            Context: Updated context with pipeline results / パイプライン結果付き更新済みコンテキスト
        """
        # English: Update step information in context
        # 日本語: コンテキストのステップ情報を更新
        ctx.update_step_info(self.name)

        try:
            # English: Determine input text for pipeline
            # 日本語: パイプライン用入力テキストを決定
            input_text = user_input or ctx.last_user_input or ""

            if not input_text:
                # English: If no input available, add system message and continue
                # 日本語: 入力がない場合、システムメッセージを追加して続行
                ctx.add_system_message(f"GenAgent {self.name}: No input available, skipping pipeline execution")
                result = None
            else:
                # English: Execute pipeline in thread pool to handle sync methods
                # 日本語: 同期メソッドを処理するためにスレッドプールでパイプラインを実行
                loop = asyncio.get_event_loop()
                with ThreadPoolExecutor() as executor:
                    future = loop.run_in_executor(executor, self.pipeline.run, input_text)
                    result = await future

            # English: Store result in context
            # 日本語: 結果をコンテキストに保存
            if result is not None:
                # English: Store in shared state for other steps to access
                # 日本語: 他のステップがアクセスできるよう共有状態に保存
                ctx.shared_state[self.store_result_key] = result
                ctx.prev_outputs[self.name] = result

                # English: Add result as assistant message
                # 日本語: 結果をアシスタントメッセージとして追加
                ctx.add_assistant_message(str(result))

                # English: Add success system message
                # 日本語: 成功システムメッセージを追加
                ctx.add_system_message(f"GenAgent {self.name}: Pipeline executed successfully")
            else:
                # English: Handle case where pipeline returned None (evaluation failed)
                # 日本語: パイプラインがNoneを返した場合(評価失敗)を処理
                ctx.shared_state[self.store_result_key] = None
                ctx.prev_outputs[self.name] = None

                # English: Add failure system message
                # 日本語: 失敗システムメッセージを追加
                ctx.add_system_message(f"GenAgent {self.name}: Pipeline execution failed (evaluation threshold not met)")

        except Exception as e:
            # English: Handle execution errors
            # 日本語: 実行エラーを処理
            error_msg = f"GenAgent {self.name} execution error: {str(e)}"
            ctx.add_system_message(error_msg)
            ctx.shared_state[self.store_result_key] = None
            ctx.prev_outputs[self.name] = None

            # English: Log error for debugging
            # 日本語: デバッグ用エラーログ
            print(f"🚨 {error_msg}")

        # English: Set next step if specified
        # 日本語: 指定されている場合は次ステップを設定
        if self.next_step:
            ctx.goto(self.next_step)

        return ctx

    def get_pipeline_history(self) -> List[Dict[str, str]]:
        """
        Get the internal pipeline history
        内部パイプライン履歴を取得する

        Returns:
            List[Dict[str, str]]: Pipeline history / パイプライン履歴
        """
        return self.pipeline._pipeline_history

    def get_session_history(self) -> Optional[List[str]]:
        """
        Get the session history
        セッション履歴を取得する

        Returns:
            Optional[List[str]]: Session history / セッション履歴
        """
        return self.pipeline.session_history

    def update_instructions(
        self, 
        generation_instructions: Optional[str] = None,
        evaluation_instructions: Optional[str] = None
    ) -> None:
        """
        Update pipeline instructions
        パイプライン指示を更新する

        Args:
            generation_instructions: New generation instructions / 新しい生成指示
            evaluation_instructions: New evaluation instructions / 新しい評価指示
        """
        if generation_instructions is not None:
            self.pipeline.generation_instructions = generation_instructions.strip()
            # English: Update the agent instructions
            # 日本語: エージェント指示を更新
            self.pipeline.gen_agent.instructions = generation_instructions.strip()

        if evaluation_instructions is not None:
            self.pipeline.evaluation_instructions = evaluation_instructions.strip() if evaluation_instructions else None
            # English: Update evaluation agent if it exists
            # 日本語: 評価エージェントが存在する場合は更新
            if self.pipeline.eval_agent and evaluation_instructions:
                self.pipeline.eval_agent.instructions = evaluation_instructions.strip()

    def clear_history(self) -> None:
        """
        Clear both pipeline and session history
        パイプライン履歴とセッション履歴の両方をクリア
        """
        self.pipeline._pipeline_history.clear()
        if self.pipeline.session_history:
            self.pipeline.session_history.clear()

    def set_threshold(self, threshold: int) -> None:
        """
        Update evaluation threshold
        評価閾値を更新する

        Args:
            threshold: New threshold value (0-100) / 新しい閾値(0-100)
        """
        if 0 <= threshold <= 100:
            self.pipeline.threshold = threshold
        else:
            raise ValueError("Threshold must be between 0 and 100")

    def __str__(self) -> str:
        return f"GenAgent({self.name}, model={self.pipeline.model})"

    def __repr__(self) -> str:
        return self.__str__()

__init__(name, generation_instructions, evaluation_instructions=None, *, input_guardrails=None, output_guardrails=None, output_model=None, model=None, evaluation_model=None, generation_tools=None, evaluation_tools=None, routing_func=None, session_history=None, history_size=10, threshold=85, retries=3, improvement_callback=None, dynamic_prompt=None, retry_comment_importance=None, locale='en', next_step=None, store_result_key=None)

Initialize GenAgent with AgentPipeline configuration AgentPipeline設定でGenAgentを初期化する

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
generation_instructions str

System prompt for generation / 生成用システムプロンプト

required
evaluation_instructions Optional[str]

System prompt for evaluation / 評価用システムプロンプト

None
input_guardrails Optional[list]

Guardrails for generation / 生成用ガードレール

None
output_guardrails Optional[list]

Guardrails for evaluation / 評価用ガードレール

None
output_model Optional[Type[Any]]

Model for output formatting / 出力フォーマット用モデル

None
model str | None

LLM model name / LLMモデル名

None
evaluation_model str | None

Optional LLM model name for evaluation / 評価用LLMモデル名(任意)

None
generation_tools Optional[list]

Tools for generation / 生成用ツール

None
evaluation_tools Optional[list]

Tools for evaluation / 評価用ツール

None
routing_func Optional[Callable[[Any], Any]]

Function for output routing / 出力ルーティング用関数

None
session_history Optional[list]

Session history / セッション履歴

None
history_size int

Size of history to keep / 保持する履歴サイズ

10
threshold int

Evaluation score threshold / 評価スコア閾値

85
retries int

Number of retry attempts / リトライ試行回数

3
improvement_callback Optional[Callable[[Any, EvaluationResult], None]]

Callback for improvement suggestions / 改善提案用コールバック

None
dynamic_prompt Optional[Callable[[str], str]]

Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)

None
retry_comment_importance Optional[list[str]]

Importance levels of comments to include on retry / リトライ時コメント重要度レベル

None
locale str

Language code for localized messages / ローカライズメッセージ用言語コード

'en'
next_step Optional[str]

Next step after pipeline execution / パイプライン実行後の次ステップ

None
store_result_key Optional[str]

Key to store result in context shared_state / コンテキスト共有状態に結果を格納するキー

None
Source code in src\agents_sdk_models\gen_agent.py
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
def __init__(
    self,
    name: str,
    generation_instructions: str,
    evaluation_instructions: Optional[str] = None,
    *,
    input_guardrails: Optional[list] = None,
    output_guardrails: Optional[list] = None,
    output_model: Optional[Type[Any]] = None,
    model: str | None = None,
    evaluation_model: str | None = None,
    generation_tools: Optional[list] = None,
    evaluation_tools: Optional[list] = None,
    routing_func: Optional[Callable[[Any], Any]] = None,
    session_history: Optional[list] = None,
    history_size: int = 10,
    threshold: int = 85,
    retries: int = 3,
    improvement_callback: Optional[Callable[[Any, EvaluationResult], None]] = None,
    dynamic_prompt: Optional[Callable[[str], str]] = None,
    retry_comment_importance: Optional[list[str]] = None,
    locale: str = "en",
    next_step: Optional[str] = None,
    store_result_key: Optional[str] = None,
) -> None:
    """
    Initialize GenAgent with AgentPipeline configuration
    AgentPipeline設定でGenAgentを初期化する

    Args:
        name: Step name / ステップ名
        generation_instructions: System prompt for generation / 生成用システムプロンプト
        evaluation_instructions: System prompt for evaluation / 評価用システムプロンプト
        input_guardrails: Guardrails for generation / 生成用ガードレール
        output_guardrails: Guardrails for evaluation / 評価用ガードレール
        output_model: Model for output formatting / 出力フォーマット用モデル
        model: LLM model name / LLMモデル名
        evaluation_model: Optional LLM model name for evaluation / 評価用LLMモデル名(任意)
        generation_tools: Tools for generation / 生成用ツール
        evaluation_tools: Tools for evaluation / 評価用ツール
        routing_func: Function for output routing / 出力ルーティング用関数
        session_history: Session history / セッション履歴
        history_size: Size of history to keep / 保持する履歴サイズ
        threshold: Evaluation score threshold / 評価スコア閾値
        retries: Number of retry attempts / リトライ試行回数
        improvement_callback: Callback for improvement suggestions / 改善提案用コールバック
        dynamic_prompt: Optional function to dynamically build prompt / 動的プロンプト生成関数(任意)
        retry_comment_importance: Importance levels of comments to include on retry / リトライ時コメント重要度レベル
        locale: Language code for localized messages / ローカライズメッセージ用言語コード
        next_step: Next step after pipeline execution / パイプライン実行後の次ステップ
        store_result_key: Key to store result in context shared_state / コンテキスト共有状態に結果を格納するキー
    """
    # Initialize Step base class
    # Step基底クラスを初期化
    super().__init__(name)

    # Store flow-specific configuration
    # フロー固有の設定を保存
    self.next_step = next_step
    self.store_result_key = store_result_key or f"{name}_result"

    # Create internal AgentPipeline instance
    # 内部AgentPipelineインスタンスを作成
    self.pipeline = AgentPipeline(
        name=f"{name}_pipeline",
        generation_instructions=generation_instructions,
        evaluation_instructions=evaluation_instructions,
        input_guardrails=input_guardrails,
        output_guardrails=output_guardrails,
        output_model=output_model,
        model=model,
        evaluation_model=evaluation_model,
        generation_tools=generation_tools,
        evaluation_tools=evaluation_tools,
        routing_func=routing_func,
        session_history=session_history,
        history_size=history_size,
        threshold=threshold,
        retries=retries,
        improvement_callback=improvement_callback,
        dynamic_prompt=dynamic_prompt,
        retry_comment_importance=retry_comment_importance,
        locale=locale,
    )

clear_history()

Clear both pipeline and session history パイプライン履歴とセッション履歴の両方をクリア

Source code in src\agents_sdk_models\gen_agent.py
238
239
240
241
242
243
244
245
def clear_history(self) -> None:
    """
    Clear both pipeline and session history
    パイプライン履歴とセッション履歴の両方をクリア
    """
    self.pipeline._pipeline_history.clear()
    if self.pipeline.session_history:
        self.pipeline.session_history.clear()

get_pipeline_history()

Get the internal pipeline history 内部パイプライン履歴を取得する

Returns:

Type Description
List[Dict[str, str]]

List[Dict[str, str]]: Pipeline history / パイプライン履歴

Source code in src\agents_sdk_models\gen_agent.py
192
193
194
195
196
197
198
199
200
def get_pipeline_history(self) -> List[Dict[str, str]]:
    """
    Get the internal pipeline history
    内部パイプライン履歴を取得する

    Returns:
        List[Dict[str, str]]: Pipeline history / パイプライン履歴
    """
    return self.pipeline._pipeline_history

get_session_history()

Get the session history セッション履歴を取得する

Returns:

Type Description
Optional[List[str]]

Optional[List[str]]: Session history / セッション履歴

Source code in src\agents_sdk_models\gen_agent.py
202
203
204
205
206
207
208
209
210
def get_session_history(self) -> Optional[List[str]]:
    """
    Get the session history
    セッション履歴を取得する

    Returns:
        Optional[List[str]]: Session history / セッション履歴
    """
    return self.pipeline.session_history

run(user_input, ctx) async

Execute GenAgent step using AgentPipeline AgentPipelineを使用してGenAgentステップを実行する

Parameters:

Name Type Description Default
user_input Optional[str]

User input for the pipeline / パイプライン用ユーザー入力

required
ctx Context

Current workflow context / 現在のワークフローコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context with pipeline results / パイプライン結果付き更新済みコンテキスト

Source code in src\agents_sdk_models\gen_agent.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute GenAgent step using AgentPipeline
    AgentPipelineを使用してGenAgentステップを実行する

    Args:
        user_input: User input for the pipeline / パイプライン用ユーザー入力
        ctx: Current workflow context / 現在のワークフローコンテキスト

    Returns:
        Context: Updated context with pipeline results / パイプライン結果付き更新済みコンテキスト
    """
    # English: Update step information in context
    # 日本語: コンテキストのステップ情報を更新
    ctx.update_step_info(self.name)

    try:
        # English: Determine input text for pipeline
        # 日本語: パイプライン用入力テキストを決定
        input_text = user_input or ctx.last_user_input or ""

        if not input_text:
            # English: If no input available, add system message and continue
            # 日本語: 入力がない場合、システムメッセージを追加して続行
            ctx.add_system_message(f"GenAgent {self.name}: No input available, skipping pipeline execution")
            result = None
        else:
            # English: Execute pipeline in thread pool to handle sync methods
            # 日本語: 同期メソッドを処理するためにスレッドプールでパイプラインを実行
            loop = asyncio.get_event_loop()
            with ThreadPoolExecutor() as executor:
                future = loop.run_in_executor(executor, self.pipeline.run, input_text)
                result = await future

        # English: Store result in context
        # 日本語: 結果をコンテキストに保存
        if result is not None:
            # English: Store in shared state for other steps to access
            # 日本語: 他のステップがアクセスできるよう共有状態に保存
            ctx.shared_state[self.store_result_key] = result
            ctx.prev_outputs[self.name] = result

            # English: Add result as assistant message
            # 日本語: 結果をアシスタントメッセージとして追加
            ctx.add_assistant_message(str(result))

            # English: Add success system message
            # 日本語: 成功システムメッセージを追加
            ctx.add_system_message(f"GenAgent {self.name}: Pipeline executed successfully")
        else:
            # English: Handle case where pipeline returned None (evaluation failed)
            # 日本語: パイプラインがNoneを返した場合(評価失敗)を処理
            ctx.shared_state[self.store_result_key] = None
            ctx.prev_outputs[self.name] = None

            # English: Add failure system message
            # 日本語: 失敗システムメッセージを追加
            ctx.add_system_message(f"GenAgent {self.name}: Pipeline execution failed (evaluation threshold not met)")

    except Exception as e:
        # English: Handle execution errors
        # 日本語: 実行エラーを処理
        error_msg = f"GenAgent {self.name} execution error: {str(e)}"
        ctx.add_system_message(error_msg)
        ctx.shared_state[self.store_result_key] = None
        ctx.prev_outputs[self.name] = None

        # English: Log error for debugging
        # 日本語: デバッグ用エラーログ
        print(f"🚨 {error_msg}")

    # English: Set next step if specified
    # 日本語: 指定されている場合は次ステップを設定
    if self.next_step:
        ctx.goto(self.next_step)

    return ctx

set_threshold(threshold)

Update evaluation threshold 評価閾値を更新する

Parameters:

Name Type Description Default
threshold int

New threshold value (0-100) / 新しい閾値(0-100)

required
Source code in src\agents_sdk_models\gen_agent.py
247
248
249
250
251
252
253
254
255
256
257
258
def set_threshold(self, threshold: int) -> None:
    """
    Update evaluation threshold
    評価閾値を更新する

    Args:
        threshold: New threshold value (0-100) / 新しい閾値(0-100)
    """
    if 0 <= threshold <= 100:
        self.pipeline.threshold = threshold
    else:
        raise ValueError("Threshold must be between 0 and 100")

update_instructions(generation_instructions=None, evaluation_instructions=None)

Update pipeline instructions パイプライン指示を更新する

Parameters:

Name Type Description Default
generation_instructions Optional[str]

New generation instructions / 新しい生成指示

None
evaluation_instructions Optional[str]

New evaluation instructions / 新しい評価指示

None
Source code in src\agents_sdk_models\gen_agent.py
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
def update_instructions(
    self, 
    generation_instructions: Optional[str] = None,
    evaluation_instructions: Optional[str] = None
) -> None:
    """
    Update pipeline instructions
    パイプライン指示を更新する

    Args:
        generation_instructions: New generation instructions / 新しい生成指示
        evaluation_instructions: New evaluation instructions / 新しい評価指示
    """
    if generation_instructions is not None:
        self.pipeline.generation_instructions = generation_instructions.strip()
        # English: Update the agent instructions
        # 日本語: エージェント指示を更新
        self.pipeline.gen_agent.instructions = generation_instructions.strip()

    if evaluation_instructions is not None:
        self.pipeline.evaluation_instructions = evaluation_instructions.strip() if evaluation_instructions else None
        # English: Update evaluation agent if it exists
        # 日本語: 評価エージェントが存在する場合は更新
        if self.pipeline.eval_agent and evaluation_instructions:
            self.pipeline.eval_agent.instructions = evaluation_instructions.strip()

JoinStep

Bases: Step

Step that joins results from parallel branches 並列ブランチからの結果を結合するステップ

This step waits for parallel branches to complete and merges their results. このステップは並列ブランチの完了を待機し、結果をマージします。

Source code in src\agents_sdk_models\step.py
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
class JoinStep(Step):
    """
    Step that joins results from parallel branches
    並列ブランチからの結果を結合するステップ

    This step waits for parallel branches to complete and merges their results.
    このステップは並列ブランチの完了を待機し、結果をマージします。
    """

    def __init__(self, name: str, fork_step: str, join_type: str = "all", next_step: Optional[str] = None):
        """
        Initialize join step
        ジョインステップを初期化

        Args:
            name: Step name / ステップ名
            fork_step: Associated fork step name / 関連するフォークステップ名
            join_type: Join type ("all" or "any") / ジョインタイプ("all"または"any")
            next_step: Next step after join / ジョイン後の次ステップ
        """
        super().__init__(name)
        self.fork_step = fork_step
        self.join_type = join_type
        self.next_step = next_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute join step
        ジョインステップを実行

        Args:
            user_input: User input / ユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        # Get branch information from shared state
        # 共有状態からブランチ情報を取得
        branches = ctx.shared_state.get(f"{self.fork_step}_branches", [])

        # For now, just mark as completed
        # 現在のところ、完了としてマークするだけ
        # In a full implementation, this would wait for and merge branch results
        # 完全な実装では、これはブランチ結果を待機してマージする
        ctx.add_system_message(f"Joined {len(branches)} branches using {self.join_type} strategy")

        # Set next step if specified
        # 指定されている場合は次ステップを設定
        if self.next_step:
            ctx.goto(self.next_step)

        return ctx

__init__(name, fork_step, join_type='all', next_step=None)

Initialize join step ジョインステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
fork_step str

Associated fork step name / 関連するフォークステップ名

required
join_type str

Join type ("all" or "any") / ジョインタイプ("all"または"any")

'all'
next_step Optional[str]

Next step after join / ジョイン後の次ステップ

None
Source code in src\agents_sdk_models\step.py
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
def __init__(self, name: str, fork_step: str, join_type: str = "all", next_step: Optional[str] = None):
    """
    Initialize join step
    ジョインステップを初期化

    Args:
        name: Step name / ステップ名
        fork_step: Associated fork step name / 関連するフォークステップ名
        join_type: Join type ("all" or "any") / ジョインタイプ("all"または"any")
        next_step: Next step after join / ジョイン後の次ステップ
    """
    super().__init__(name)
    self.fork_step = fork_step
    self.join_type = join_type
    self.next_step = next_step

run(user_input, ctx) async

Execute join step ジョインステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input / ユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute join step
    ジョインステップを実行

    Args:
        user_input: User input / ユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    # Get branch information from shared state
    # 共有状態からブランチ情報を取得
    branches = ctx.shared_state.get(f"{self.fork_step}_branches", [])

    # For now, just mark as completed
    # 現在のところ、完了としてマークするだけ
    # In a full implementation, this would wait for and merge branch results
    # 完全な実装では、これはブランチ結果を待機してマージする
    ctx.add_system_message(f"Joined {len(branches)} branches using {self.join_type} strategy")

    # Set next step if specified
    # 指定されている場合は次ステップを設定
    if self.next_step:
        ctx.goto(self.next_step)

    return ctx

Message

Bases: BaseModel

Message class for conversation history 会話履歴用メッセージクラス

Attributes:

Name Type Description
role str

Message role (user, assistant, system) / メッセージの役割

content str

Message content / メッセージ内容

timestamp datetime

Message timestamp / メッセージのタイムスタンプ

metadata Dict[str, Any]

Additional metadata / 追加メタデータ

Source code in src\agents_sdk_models\context.py
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Message(BaseModel):
    """
    Message class for conversation history
    会話履歴用メッセージクラス

    Attributes:
        role: Message role (user, assistant, system) / メッセージの役割
        content: Message content / メッセージ内容
        timestamp: Message timestamp / メッセージのタイムスタンプ
        metadata: Additional metadata / 追加メタデータ
    """
    role: str  # Message role (user, assistant, system) / メッセージの役割
    content: str  # Message content / メッセージ内容
    timestamp: datetime = Field(default_factory=datetime.now)  # Message timestamp / メッセージのタイムスタンプ
    metadata: Dict[str, Any] = Field(default_factory=dict)  # Additional metadata / 追加メタデータ

OllamaModel

Bases: OpenAIChatCompletionsModel

Ollama model implementation that extends OpenAI's chat completions model OpenAIのチャット補完モデルを拡張したOllamaモデルの実装

Source code in src\agents_sdk_models\ollama.py
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
class OllamaModel(OpenAIChatCompletionsModel):
    """
    Ollama model implementation that extends OpenAI's chat completions model
    OpenAIのチャット補完モデルを拡張したOllamaモデルの実装
    """

    def __init__(
        self,
        model: str = "phi4-mini:latest",
        temperature: float = 0.3,
        base_url: str = None, # デフォルトのURL
        **kwargs: Any,
    ) -> None:
        """
        Initialize the Ollama model with OpenAI compatible interface
        OpenAI互換インターフェースでOllamaモデルを初期化する

        Args:
            model (str): Name of the Ollama model to use (e.g. "phi4-mini")
                使用するOllamaモデルの名前(例:"phi4-mini")
            temperature (float): Sampling temperature between 0 and 1
                サンプリング温度(0から1の間)
            base_url (str): Base URL for the Ollama API
                Ollama APIのベースURL
            **kwargs: Additional arguments to pass to the OpenAI API
                OpenAI APIに渡す追加の引数
        """
        # get_llm経由で base_url が None の場合はデフォルトの URL を設定
        if base_url == None:
            base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")

        base_url = base_url.rstrip("/")
        if not base_url.endswith("v1"):
            base_url = base_url + "/v1"

        # Create AsyncOpenAI client with Ollama base URL
        # OllamaのベースURLでAsyncOpenAIクライアントを作成
        openai_client = AsyncOpenAI(base_url=base_url, api_key="ollama")

        # Store the AsyncOpenAI client on the instance for direct access
        # テストで参照できるよう AsyncOpenAI クライアントをインスタンスに保存する
        self.openai_client = openai_client

        # Store parameters for later use in API calls
        # 後でAPIコールで使用するためにパラメータを保存
        self.temperature = temperature
        self.kwargs = kwargs

        # Initialize the parent class with our custom client
        # カスタムクライアントで親クラスを初期化
        super().__init__(
            model=model,
            openai_client=openai_client
        )

    # Override methods that make API calls to include our parameters
    # APIコールを行うメソッドをオーバーライドして、パラメータを含める
    async def _create_chat_completion(self, *args, **kwargs):
        """Override to include temperature and other parameters"""
        kwargs["temperature"] = self.temperature
        kwargs.update(self.kwargs)
        return await super()._create_chat_completion(*args, **kwargs)

__init__(model='phi4-mini:latest', temperature=0.3, base_url=None, **kwargs)

Initialize the Ollama model with OpenAI compatible interface OpenAI互換インターフェースでOllamaモデルを初期化する

Parameters:

Name Type Description Default
model str

Name of the Ollama model to use (e.g. "phi4-mini") 使用するOllamaモデルの名前(例:"phi4-mini")

'phi4-mini:latest'
temperature float

Sampling temperature between 0 and 1 サンプリング温度(0から1の間)

0.3
base_url str

Base URL for the Ollama API Ollama APIのベースURL

None
**kwargs Any

Additional arguments to pass to the OpenAI API OpenAI APIに渡す追加の引数

{}
Source code in src\agents_sdk_models\ollama.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
def __init__(
    self,
    model: str = "phi4-mini:latest",
    temperature: float = 0.3,
    base_url: str = None, # デフォルトのURL
    **kwargs: Any,
) -> None:
    """
    Initialize the Ollama model with OpenAI compatible interface
    OpenAI互換インターフェースでOllamaモデルを初期化する

    Args:
        model (str): Name of the Ollama model to use (e.g. "phi4-mini")
            使用するOllamaモデルの名前(例:"phi4-mini")
        temperature (float): Sampling temperature between 0 and 1
            サンプリング温度(0から1の間)
        base_url (str): Base URL for the Ollama API
            Ollama APIのベースURL
        **kwargs: Additional arguments to pass to the OpenAI API
            OpenAI APIに渡す追加の引数
    """
    # get_llm経由で base_url が None の場合はデフォルトの URL を設定
    if base_url == None:
        base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")

    base_url = base_url.rstrip("/")
    if not base_url.endswith("v1"):
        base_url = base_url + "/v1"

    # Create AsyncOpenAI client with Ollama base URL
    # OllamaのベースURLでAsyncOpenAIクライアントを作成
    openai_client = AsyncOpenAI(base_url=base_url, api_key="ollama")

    # Store the AsyncOpenAI client on the instance for direct access
    # テストで参照できるよう AsyncOpenAI クライアントをインスタンスに保存する
    self.openai_client = openai_client

    # Store parameters for later use in API calls
    # 後でAPIコールで使用するためにパラメータを保存
    self.temperature = temperature
    self.kwargs = kwargs

    # Initialize the parent class with our custom client
    # カスタムクライアントで親クラスを初期化
    super().__init__(
        model=model,
        openai_client=openai_client
    )

Step

Bases: ABC

Abstract base class for workflow steps ワークフローステップの抽象基底クラス

All step implementations must provide: 全てのステップ実装は以下を提供する必要があります: - name: Step identifier for DSL reference / DSL参照用ステップ識別子 - run: Async execution method / 非同期実行メソッド

Source code in src\agents_sdk_models\step.py
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
class Step(ABC):
    """
    Abstract base class for workflow steps
    ワークフローステップの抽象基底クラス

    All step implementations must provide:
    全てのステップ実装は以下を提供する必要があります:
    - name: Step identifier for DSL reference / DSL参照用ステップ識別子
    - run: Async execution method / 非同期実行メソッド
    """

    def __init__(self, name: str):
        """
        Initialize step with name
        名前でステップを初期化

        Args:
            name: Step name / ステップ名
        """
        self.name = name

    @abstractmethod
    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute step and return updated context
        ステップを実行し、更新されたコンテキストを返す

        Args:
            user_input: User input if any / ユーザー入力(あれば)
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context with next_label set / next_labelが設定された更新済みコンテキスト
        """
        pass

    def __str__(self) -> str:
        return f"{self.__class__.__name__}({self.name})"

    def __repr__(self) -> str:
        return self.__str__()

__init__(name)

Initialize step with name 名前でステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
Source code in src\agents_sdk_models\step.py
29
30
31
32
33
34
35
36
37
def __init__(self, name: str):
    """
    Initialize step with name
    名前でステップを初期化

    Args:
        name: Step name / ステップ名
    """
    self.name = name

run(user_input, ctx) abstractmethod async

Execute step and return updated context ステップを実行し、更新されたコンテキストを返す

Parameters:

Name Type Description Default
user_input Optional[str]

User input if any / ユーザー入力(あれば)

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context with next_label set / next_labelが設定された更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@abstractmethod
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute step and return updated context
    ステップを実行し、更新されたコンテキストを返す

    Args:
        user_input: User input if any / ユーザー入力(あれば)
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context with next_label set / next_labelが設定された更新済みコンテキスト
    """
    pass

UserInputStep

Bases: Step

Step that waits for user input ユーザー入力を待機するステップ

This step displays a prompt and waits for user response. このステップはプロンプトを表示し、ユーザー応答を待機します。 It sets the context to waiting state and returns without advancing. コンテキストを待機状態に設定し、進行せずに返します。

Source code in src\agents_sdk_models\step.py
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
class UserInputStep(Step):
    """
    Step that waits for user input
    ユーザー入力を待機するステップ

    This step displays a prompt and waits for user response.
    このステップはプロンプトを表示し、ユーザー応答を待機します。
    It sets the context to waiting state and returns without advancing.
    コンテキストを待機状態に設定し、進行せずに返します。
    """

    def __init__(self, name: str, prompt: str, next_step: Optional[str] = None):
        """
        Initialize user input step
        ユーザー入力ステップを初期化

        Args:
            name: Step name / ステップ名
            prompt: Prompt to display to user / ユーザーに表示するプロンプト
            next_step: Next step after input (optional) / 入力後の次ステップ(オプション)
        """
        super().__init__(name)
        self.prompt = prompt
        self.next_step = next_step

    async def run(self, user_input: Optional[str], ctx: Context) -> Context:
        """
        Execute user input step
        ユーザー入力ステップを実行

        Args:
            user_input: User input if available / 利用可能なユーザー入力
            ctx: Current context / 現在のコンテキスト

        Returns:
            Context: Updated context / 更新済みコンテキスト
        """
        ctx.update_step_info(self.name)

        # If user input is provided, process it
        # ユーザー入力が提供されている場合、処理する
        if user_input is not None:
            ctx.provide_user_input(user_input)
            if self.next_step:
                ctx.goto(self.next_step)
            # Note: If next_step is None, flow will end
            # 注:next_stepがNoneの場合、フローは終了
        else:
            # Set waiting state for user input
            # ユーザー入力の待機状態を設定
            ctx.set_waiting_for_user_input(self.prompt)

        return ctx

__init__(name, prompt, next_step=None)

Initialize user input step ユーザー入力ステップを初期化

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
prompt str

Prompt to display to user / ユーザーに表示するプロンプト

required
next_step Optional[str]

Next step after input (optional) / 入力後の次ステップ(オプション)

None
Source code in src\agents_sdk_models\step.py
72
73
74
75
76
77
78
79
80
81
82
83
84
def __init__(self, name: str, prompt: str, next_step: Optional[str] = None):
    """
    Initialize user input step
    ユーザー入力ステップを初期化

    Args:
        name: Step name / ステップ名
        prompt: Prompt to display to user / ユーザーに表示するプロンプト
        next_step: Next step after input (optional) / 入力後の次ステップ(オプション)
    """
    super().__init__(name)
    self.prompt = prompt
    self.next_step = next_step

run(user_input, ctx) async

Execute user input step ユーザー入力ステップを実行

Parameters:

Name Type Description Default
user_input Optional[str]

User input if available / 利用可能なユーザー入力

required
ctx Context

Current context / 現在のコンテキスト

required

Returns:

Name Type Description
Context Context

Updated context / 更新済みコンテキスト

Source code in src\agents_sdk_models\step.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
async def run(self, user_input: Optional[str], ctx: Context) -> Context:
    """
    Execute user input step
    ユーザー入力ステップを実行

    Args:
        user_input: User input if available / 利用可能なユーザー入力
        ctx: Current context / 現在のコンテキスト

    Returns:
        Context: Updated context / 更新済みコンテキスト
    """
    ctx.update_step_info(self.name)

    # If user input is provided, process it
    # ユーザー入力が提供されている場合、処理する
    if user_input is not None:
        ctx.provide_user_input(user_input)
        if self.next_step:
            ctx.goto(self.next_step)
        # Note: If next_step is None, flow will end
        # 注:next_stepがNoneの場合、フローは終了
    else:
        # Set waiting state for user input
        # ユーザー入力の待機状態を設定
        ctx.set_waiting_for_user_input(self.prompt)

    return ctx

create_conditional_flow(initial_step, condition_step, true_branch, false_branch, context=None)

Create a conditional flow with true/false branches true/falseブランチを持つ条件付きフローを作成

Parameters:

Name Type Description Default
initial_step Step

Initial step / 初期ステップ

required
condition_step Step

Condition step / 条件ステップ

required
true_branch List[Step]

Steps for true branch / trueブランチのステップ

required
false_branch List[Step]

Steps for false branch / falseブランチのステップ

required
context Optional[Context]

Initial context / 初期コンテキスト

None

Returns:

Name Type Description
Flow Flow

Created flow / 作成されたフロー

Source code in src\agents_sdk_models\flow.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
def create_conditional_flow(
    initial_step: Step,
    condition_step: Step,
    true_branch: List[Step],
    false_branch: List[Step],
    context: Optional[Context] = None
) -> Flow:
    """
    Create a conditional flow with true/false branches
    true/falseブランチを持つ条件付きフローを作成

    Args:
        initial_step: Initial step / 初期ステップ
        condition_step: Condition step / 条件ステップ
        true_branch: Steps for true branch / trueブランチのステップ
        false_branch: Steps for false branch / falseブランチのステップ
        context: Initial context / 初期コンテキスト

    Returns:
        Flow: Created flow / 作成されたフロー
    """
    steps = {
        "start": initial_step,
        "condition": condition_step
    }

    # Add true branch steps
    # trueブランチステップを追加
    for i, step in enumerate(true_branch):
        step_name = f"true_{i}"
        steps[step_name] = step
        if i == 0 and hasattr(condition_step, 'if_true'):
            condition_step.if_true = step_name

    # Add false branch steps
    # falseブランチステップを追加
    for i, step in enumerate(false_branch):
        step_name = f"false_{i}"
        steps[step_name] = step
        if i == 0 and hasattr(condition_step, 'if_false'):
            condition_step.if_false = step_name

    # Connect initial step to condition
    # 初期ステップを条件に接続
    if hasattr(initial_step, 'next_step'):
        initial_step.next_step = "condition"

    return Flow(
        start="start",
        steps=steps,
        context=context
    ) 

create_evaluated_gen_agent(name, generation_instructions, evaluation_instructions, model=None, evaluation_model=None, next_step=None, threshold=85, retries=3)

Create a GenAgent with both generation and evaluation 生成と評価の両方を持つGenAgentを作成

Parameters:

Name Type Description Default
name str

Agent name / エージェント名

required
generation_instructions str

Generation instructions / 生成指示

required
evaluation_instructions str

Evaluation instructions / 評価指示

required
model Optional[str]

LLM model name / LLMモデル名

None
evaluation_model Optional[str]

Evaluation model name / 評価モデル名

None
next_step Optional[str]

Next step after execution / 実行後の次ステップ

None
threshold int

Evaluation threshold / 評価閾値

85
retries int

Number of retries / リトライ回数

3

Returns:

Name Type Description
GenAgent GenAgent

Configured GenAgent instance / 設定済みGenAgentインスタンス

Source code in src\agents_sdk_models\gen_agent.py
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
def create_evaluated_gen_agent(
    name: str,
    generation_instructions: str,
    evaluation_instructions: str,
    model: Optional[str] = None,
    evaluation_model: Optional[str] = None,
    next_step: Optional[str] = None,
    threshold: int = 85,
    retries: int = 3
) -> GenAgent:
    """
    Create a GenAgent with both generation and evaluation
    生成と評価の両方を持つGenAgentを作成

    Args:
        name: Agent name / エージェント名
        generation_instructions: Generation instructions / 生成指示
        evaluation_instructions: Evaluation instructions / 評価指示
        model: LLM model name / LLMモデル名
        evaluation_model: Evaluation model name / 評価モデル名
        next_step: Next step after execution / 実行後の次ステップ
        threshold: Evaluation threshold / 評価閾値
        retries: Number of retries / リトライ回数

    Returns:
        GenAgent: Configured GenAgent instance / 設定済みGenAgentインスタンス
    """
    return GenAgent(
        name=name,
        generation_instructions=generation_instructions,
        evaluation_instructions=evaluation_instructions,
        model=model,
        evaluation_model=evaluation_model,
        next_step=next_step,
        threshold=threshold,
        retries=retries
    ) 

create_lambda_step(name, func, next_step=None)

Create a simple function step from a lambda ラムダから簡単な関数ステップを作成

Parameters:

Name Type Description Default
name str

Step name / ステップ名

required
func Callable[[Context], Any]

Function to execute / 実行する関数

required
next_step Optional[str]

Next step / 次ステップ

None

Returns:

Name Type Description
FunctionStep FunctionStep

Function step / 関数ステップ

Source code in src\agents_sdk_models\step.py
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
def create_lambda_step(name: str, func: Callable[[Context], Any], next_step: Optional[str] = None) -> FunctionStep:
    """
    Create a simple function step from a lambda
    ラムダから簡単な関数ステップを作成

    Args:
        name: Step name / ステップ名
        func: Function to execute / 実行する関数
        next_step: Next step / 次ステップ

    Returns:
        FunctionStep: Function step / 関数ステップ
    """
    def wrapper(user_input: Optional[str], ctx: Context) -> Context:
        func(ctx)
        return ctx

    return FunctionStep(name, wrapper, next_step) 

create_simple_condition(field_path, expected_value)

Create a simple condition function that checks a field value フィールド値をチェックする簡単な条件関数を作成

Parameters:

Name Type Description Default
field_path str

Dot-separated path to field (e.g., "shared_state.status") / フィールドへのドット区切りパス

required
expected_value Any

Expected value / 期待値

required

Returns:

Type Description
Callable[[Context], bool]

Callable[[Context], bool]: Condition function / 条件関数

Source code in src\agents_sdk_models\step.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
def create_simple_condition(field_path: str, expected_value: Any) -> Callable[[Context], bool]:
    """
    Create a simple condition function that checks a field value
    フィールド値をチェックする簡単な条件関数を作成

    Args:
        field_path: Dot-separated path to field (e.g., "shared_state.status") / フィールドへのドット区切りパス
        expected_value: Expected value / 期待値

    Returns:
        Callable[[Context], bool]: Condition function / 条件関数
    """
    def condition(ctx: Context) -> bool:
        try:
            # Navigate to the field using dot notation
            # ドット記法を使用してフィールドに移動
            obj = ctx
            for part in field_path.split('.'):
                if hasattr(obj, part):
                    obj = getattr(obj, part)
                elif isinstance(obj, dict) and part in obj:
                    obj = obj[part]
                else:
                    return False
            return obj == expected_value
        except Exception:
            return False

    return condition

create_simple_flow(steps, context=None)

Create a simple linear flow from a list of steps ステップのリストから簡単な線形フローを作成

Parameters:

Name Type Description Default
steps List[tuple[str, Step]]

List of (name, step) tuples / (名前, ステップ)タプルのリスト

required
context Optional[Context]

Initial context / 初期コンテキスト

None

Returns:

Name Type Description
Flow Flow

Created flow / 作成されたフロー

Source code in src\agents_sdk_models\flow.py
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
def create_simple_flow(
    steps: List[tuple[str, Step]], 
    context: Optional[Context] = None
) -> Flow:
    """
    Create a simple linear flow from a list of steps
    ステップのリストから簡単な線形フローを作成

    Args:
        steps: List of (name, step) tuples / (名前, ステップ)タプルのリスト
        context: Initial context / 初期コンテキスト

    Returns:
        Flow: Created flow / 作成されたフロー
    """
    if not steps:
        raise ValueError("At least one step is required")

    step_dict = {}
    for i, (name, step) in enumerate(steps):
        # Set next step for each step
        # 各ステップの次ステップを設定
        if hasattr(step, 'next_step') and step.next_step is None:
            if i < len(steps) - 1:
                step.next_step = steps[i + 1][0]
        step_dict[name] = step

    return Flow(
        start=steps[0][0],
        steps=step_dict,
        context=context
    )

create_simple_gen_agent(name, instructions, model=None, next_step=None, threshold=85, retries=3)

Create a simple GenAgent with basic configuration 基本設定でシンプルなGenAgentを作成

Parameters:

Name Type Description Default
name str

Agent name / エージェント名

required
instructions str

Generation instructions / 生成指示

required
model Optional[str]

LLM model name / LLMモデル名

None
next_step Optional[str]

Next step after execution / 実行後の次ステップ

None
threshold int

Evaluation threshold / 評価閾値

85
retries int

Number of retries / リトライ回数

3

Returns:

Name Type Description
GenAgent GenAgent

Configured GenAgent instance / 設定済みGenAgentインスタンス

Source code in src\agents_sdk_models\gen_agent.py
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def create_simple_gen_agent(
    name: str,
    instructions: str,
    model: Optional[str] = None,
    next_step: Optional[str] = None,
    threshold: int = 85,
    retries: int = 3
) -> GenAgent:
    """
    Create a simple GenAgent with basic configuration
    基本設定でシンプルなGenAgentを作成

    Args:
        name: Agent name / エージェント名
        instructions: Generation instructions / 生成指示
        model: LLM model name / LLMモデル名
        next_step: Next step after execution / 実行後の次ステップ
        threshold: Evaluation threshold / 評価閾値
        retries: Number of retries / リトライ回数

    Returns:
        GenAgent: Configured GenAgent instance / 設定済みGenAgentインスタンス
    """
    return GenAgent(
        name=name,
        generation_instructions=instructions,
        evaluation_instructions=None,  # No evaluation for simple agent
        model=model,
        next_step=next_step,
        threshold=threshold,
        retries=retries
    )

disable_tracing()

English: Disable all tracing. 日本語: トレーシング機能をすべて無効化します。

Source code in src\agents_sdk_models\tracing.py
128
129
130
131
132
133
def disable_tracing():
    """
    English: Disable all tracing.
    日本語: トレーシング機能をすべて無効化します。
    """
    set_tracing_disabled(True)

enable_console_tracing()

English: Enable console tracing by registering ConsoleTracingProcessor and enabling tracing. 日本語: ConsoleTracingProcessorを登録してトレーシングを有効化します。

Source code in src\agents_sdk_models\tracing.py
117
118
119
120
121
122
123
124
125
def enable_console_tracing():
    """
    English: Enable console tracing by registering ConsoleTracingProcessor and enabling tracing.
    日本語: ConsoleTracingProcessorを登録してトレーシングを有効化します。
    """
    # Enable tracing in Agents SDK
    set_tracing_disabled(False)
    # Register console tracing processor
    set_trace_processors([ConsoleTracingProcessor()])

get_available_models(providers, ollama_base_url=None)

Get available model names for specified providers (synchronous version).

English: Get available model names for specified providers (synchronous version).

日本語: 指定されたプロバイダーの利用可能なモデル名を取得します(同期版)。

Parameters:

Name Type Description Default
providers List[ProviderType]

List of providers to get models for. モデルを取得するプロバイダーのリスト。

required
ollama_base_url Optional[str]

Base URL for Ollama API. If None, uses environment variable or default. Ollama API のベース URL。None の場合、環境変数またはデフォルトを使用。

None

Returns:

Type Description
dict[str, List[str]]

dict[str, List[str]]: Dictionary mapping provider names to lists of available models. プロバイダー名と利用可能なモデルのリストのマッピング辞書。

Source code in src\agents_sdk_models\llm.py
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
def get_available_models(
    providers: List[ProviderType],
    ollama_base_url: Optional[str] = None
) -> dict[str, List[str]]:
    """
    Get available model names for specified providers (synchronous version).

    English:
    Get available model names for specified providers (synchronous version).

    日本語:
    指定されたプロバイダーの利用可能なモデル名を取得します(同期版)。

    Args:
        providers (List[ProviderType]): List of providers to get models for.
            モデルを取得するプロバイダーのリスト。
        ollama_base_url (Optional[str]): Base URL for Ollama API. If None, uses environment variable or default.
            Ollama API のベース URL。None の場合、環境変数またはデフォルトを使用。

    Returns:
        dict[str, List[str]]: Dictionary mapping provider names to lists of available models.
                             プロバイダー名と利用可能なモデルのリストのマッピング辞書。
    """
    try:
        # English: Try to get the current event loop
        # 日本語: 現在のイベントループを取得しようとする
        loop = asyncio.get_running_loop()
        # English: If we're in a running loop, we need to handle this differently
        # 日本語: 実行中のループ内にいる場合、異なる方法で処理する必要がある
        import concurrent.futures
        with concurrent.futures.ThreadPoolExecutor() as executor:
            future = executor.submit(asyncio.run, get_available_models_async(providers, ollama_base_url))
            return future.result()
    except RuntimeError:
        # English: No running event loop, safe to use asyncio.run()
        # 日本語: 実行中のイベントループがない場合、asyncio.run() を安全に使用
        return asyncio.run(get_available_models_async(providers, ollama_base_url)) 

get_available_models_async(providers, ollama_base_url=None) async

Get available model names for specified providers.

English: Get available model names for specified providers.

日本語: 指定されたプロバイダーの利用可能なモデル名を取得します。

Parameters:

Name Type Description Default
providers List[ProviderType]

List of providers to get models for. モデルを取得するプロバイダーのリスト。

required
ollama_base_url Optional[str]

Base URL for Ollama API. If None, uses environment variable or default. Ollama API のベース URL。None の場合、環境変数またはデフォルトを使用。

None

Returns:

Type Description
dict[str, List[str]]

dict[str, List[str]]: Dictionary mapping provider names to lists of available models. プロバイダー名と利用可能なモデルのリストのマッピング辞書。

Raises:

Type Description
ValueError

If an unsupported provider is specified. サポートされていないプロバイダーが指定された場合。

RequestError

If there's an error connecting to the Ollama API. Ollama API への接続エラーが発生した場合。

Source code in src\agents_sdk_models\llm.py
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
async def get_available_models_async(
    providers: List[ProviderType],
    ollama_base_url: Optional[str] = None
) -> dict[str, List[str]]:
    """
    Get available model names for specified providers.

    English:
    Get available model names for specified providers.

    日本語:
    指定されたプロバイダーの利用可能なモデル名を取得します。

    Args:
        providers (List[ProviderType]): List of providers to get models for.
            モデルを取得するプロバイダーのリスト。
        ollama_base_url (Optional[str]): Base URL for Ollama API. If None, uses environment variable or default.
            Ollama API のベース URL。None の場合、環境変数またはデフォルトを使用。

    Returns:
        dict[str, List[str]]: Dictionary mapping provider names to lists of available models.
                             プロバイダー名と利用可能なモデルのリストのマッピング辞書。

    Raises:
        ValueError: If an unsupported provider is specified.
                    サポートされていないプロバイダーが指定された場合。
        httpx.RequestError: If there's an error connecting to the Ollama API.
                           Ollama API への接続エラーが発生した場合。
    """
    result = {}

    for provider in providers:
        if provider == "openai":
            # English: OpenAI models - latest available models
            # 日本語: OpenAI モデル - 最新の利用可能なモデル
            result["openai"] = [
                "gpt-4o",
                "gpt-4o-mini",
                "gpt-4.1",
                "o3",
                "o4-mini"
            ]
        elif provider == "google":
            # English: Google Gemini models - latest 2.5 series models
            # 日本語: Google Gemini モデル - 最新の 2.5 シリーズモデル
            result["google"] = [
                "gemini-2.5-pro",
                "gemini-2.5-flash"
            ]
        elif provider == "anthropic":
            # English: Anthropic Claude models - latest Claude-4 series models
            # 日本語: Anthropic Claude モデル - 最新の Claude-4 シリーズモデル
            result["anthropic"] = [
                "claude-opus-4",
                "claude-sonnet-4"
            ]
        elif provider == "ollama":
            # English: Get Ollama base URL from parameter, environment variable, or default
            # 日本語: パラメータ、環境変数、またはデフォルトから Ollama ベース URL を取得
            if ollama_base_url is None:
                ollama_base_url = os.environ.get("OLLAMA_BASE_URL", "http://localhost:11434")

            try:
                # English: Fetch available models from Ollama API
                # 日本語: Ollama API から利用可能なモデルを取得
                async with httpx.AsyncClient() as client:
                    response = await client.get(f"{ollama_base_url}/api/tags")
                    response.raise_for_status()

                    # English: Parse the response to extract model names
                    # 日本語: レスポンスを解析してモデル名を抽出
                    data = response.json()
                    models = []
                    if "models" in data:
                        for model_info in data["models"]:
                            if "name" in model_info:
                                models.append(model_info["name"])

                    result["ollama"] = models

            except httpx.RequestError as e:
                # English: If connection fails, return empty list with error info
                # 日本語: 接続に失敗した場合、エラー情報と共に空のリストを返す
                result["ollama"] = []
                print(f"Warning: Could not connect to Ollama at {ollama_base_url}: {e}")
            except Exception as e:
                # English: Handle other errors
                # 日本語: その他のエラーを処理
                result["ollama"] = []
                print(f"Warning: Error fetching Ollama models: {e}")
        else:
            raise ValueError(f"Unsupported provider: {provider}. Must be one of {ProviderType.__args__}")

    return result

get_llm(model=None, provider=None, temperature=0.3, api_key=None, base_url=None, thinking=False, **kwargs)

Factory function to get an instance of a language model based on the provider.

English: Factory function to get an instance of a language model based on the provider.

日本語: プロバイダーに基づいて言語モデルのインスタンスを取得するファクトリ関数。

Parameters:

Name Type Description Default
provider ProviderType

The LLM provider ("openai", "google", "anthropic", "ollama"). Defaults to "openai". LLM プロバイダー ("openai", "google", "anthropic", "ollama")。デフォルトは "openai"。

None
model Optional[str]

The specific model name for the provider. If None, uses the default for the provider. プロバイダー固有のモデル名。None の場合、プロバイダーのデフォルトを使用します。

None
temperature float

Sampling temperature. Defaults to 0.3. サンプリング温度。デフォルトは 0.3。

0.3
api_key Optional[str]

API key for the provider, if required. プロバイダーの API キー (必要な場合)。

None
base_url Optional[str]

Base URL for the provider's API, if needed (e.g., for self-hosted Ollama or OpenAI-compatible APIs). プロバイダー API のベース URL (必要な場合、例: セルフホストの Ollama や OpenAI 互換 API)。

None
thinking bool

Enable thinking mode for Claude models. Defaults to False. Claude モデルの思考モードを有効にするか。デフォルトは False。

False
tracing bool

Whether to enable tracing for the Agents SDK. Defaults to False. Agents SDK のトレーシングを有効化するか。デフォルトは False。

required
**kwargs Any

Additional keyword arguments to pass to the model constructor. モデルのコンストラクタに渡す追加のキーワード引数。

{}

Returns:

Name Type Description
Model Model

An instance of the appropriate language model class. 適切な言語モデルクラスのインスタンス。

Raises:

Type Description
ValueError

If an unsupported provider is specified. サポートされていないプロバイダーが指定された場合。

Source code in src\agents_sdk_models\llm.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
def get_llm(
    model: Optional[str] = None,
    provider: Optional[ProviderType] = None,
    temperature: float = 0.3,
    api_key: Optional[str] = None,
    base_url: Optional[str] = None,
    thinking: bool = False,
    **kwargs: Any,
) -> Model:
    """
    Factory function to get an instance of a language model based on the provider.

    English:
    Factory function to get an instance of a language model based on the provider.

    日本語:
    プロバイダーに基づいて言語モデルのインスタンスを取得するファクトリ関数。

    Args:
        provider (ProviderType): The LLM provider ("openai", "google", "anthropic", "ollama"). Defaults to "openai".
            LLM プロバイダー ("openai", "google", "anthropic", "ollama")。デフォルトは "openai"。
        model (Optional[str]): The specific model name for the provider. If None, uses the default for the provider.
            プロバイダー固有のモデル名。None の場合、プロバイダーのデフォルトを使用します。
        temperature (float): Sampling temperature. Defaults to 0.3.
            サンプリング温度。デフォルトは 0.3。
        api_key (Optional[str]): API key for the provider, if required.
            プロバイダーの API キー (必要な場合)。
        base_url (Optional[str]): Base URL for the provider's API, if needed (e.g., for self-hosted Ollama or OpenAI-compatible APIs).
            プロバイダー API のベース URL (必要な場合、例: セルフホストの Ollama や OpenAI 互換 API)。
        thinking (bool): Enable thinking mode for Claude models. Defaults to False.
            Claude モデルの思考モードを有効にするか。デフォルトは False。
        tracing (bool): Whether to enable tracing for the Agents SDK. Defaults to False.
            Agents SDK のトレーシングを有効化するか。デフォルトは False。
        **kwargs (Any): Additional keyword arguments to pass to the model constructor.
            モデルのコンストラクタに渡す追加のキーワード引数。

    Returns:
        Model: An instance of the appropriate language model class.
               適切な言語モデルクラスのインスタンス。

    Raises:
        ValueError: If an unsupported provider is specified.
                    サポートされていないプロバイダーが指定された場合。
    """
    # English: Configure OpenAI Agents SDK tracing
    # 日本語: OpenAI Agents SDK のトレーシングを設定する
    # set_tracing_disabled(not tracing)


    if model is None:
        model = os.environ.get("LLM_MODEL", "gpt-4o-mini")

    def get_provider_canditate(model: str) -> ProviderType:
        if "gpt" in model:
            return "openai"
        if "o3" in model or "o4" in model:
            return "openai"
        elif "gemini" in model:
            return "google"
        elif "claude" in model:
            return "anthropic"
        else:
            return "ollama"

    if provider is None:
        provider = get_provider_canditate(model)

    if provider == "openai":
        # Use the standard OpenAI model from the agents library
        # agentsライブラリの標準 OpenAI モデルを使用
        openai_kwargs = kwargs.copy()

        # English: Prepare arguments for OpenAI client and model
        # 日本語: OpenAI クライアントとモデルの引数を準備
        client_args = {}
        model_args = {}

        # English: Set API key for client
        # 日本語: クライアントに API キーを設定
        if api_key:
            client_args['api_key'] = api_key
        # English: Set base URL for client
        # 日本語: クライアントにベース URL を設定
        if base_url:
            client_args['base_url'] = base_url

        # English: Set model name for model constructor
        # 日本語: モデルコンストラクタにモデル名を設定
        model_args['model'] = model if model else "gpt-4o-mini" # Default to gpt-4o-mini

        # English: Temperature is likely handled by the runner or set post-init,
        # English: so remove it from constructor args.
        # 日本語: temperature はランナーによって処理されるか、初期化後に設定される可能性が高いため、
        # 日本語: コンストラクタ引数から削除します。
        # model_args['temperature'] = temperature # Removed based on TypeError

        # English: Add any other relevant kwargs passed in, EXCLUDING temperature
        # 日本語: 渡された他の関連する kwargs を追加 (temperature を除く)
        # Example: max_tokens, etc. Filter out args meant for the client.
        # 例: max_tokens など。クライアント向けの引数を除外します。
        for key, value in kwargs.items():
            # English: Exclude client args, thinking, temperature, and tracing
            # 日本語: クライアント引数、thinking、temperature、tracing を除外
            if key not in ['api_key', 'base_url', 'thinking', 'temperature', 'tracing']:
                model_args[key] = value

        # English: Remove 'thinking' as it's not used by OpenAI model
        # 日本語: OpenAI モデルでは使用されないため 'thinking' を削除
        model_args.pop('thinking', None)

        # English: Instantiate the OpenAI client
        # 日本語: OpenAI クライアントをインスタンス化
        openai_client = AsyncOpenAI(**client_args)

        # English: Instantiate and return the model, passing the client and model args
        # 日本語: クライアントとモデル引数を渡してモデルをインスタンス化して返す
        return OpenAIResponsesModel(
            openai_client=openai_client,
            **model_args
        )
    elif provider == "google":
        gemini_kwargs = kwargs.copy()
        if model:
            gemini_kwargs['model'] = model
        # thinking is not used by GeminiModel
        gemini_kwargs.pop('thinking', None)
        return GeminiModel(
            temperature=temperature,
            api_key=api_key,
            base_url=base_url, # Although Gemini doesn't typically use base_url, pass it if provided
            **gemini_kwargs
        )
    elif provider == "anthropic":
        claude_kwargs = kwargs.copy()
        if model:
            claude_kwargs['model'] = model
        return ClaudeModel(
            temperature=temperature,
            api_key=api_key,
            base_url=base_url, # Although Claude doesn't typically use base_url, pass it if provided
            thinking=thinking,
            **claude_kwargs
        )
    elif provider == "ollama":
        ollama_kwargs = kwargs.copy()
        if model:
            ollama_kwargs['model'] = model
        # thinking is not used by OllamaModel
        ollama_kwargs.pop('thinking', None)
        return OllamaModel(
            temperature=temperature,
            base_url=base_url,
            api_key=api_key, # Although Ollama doesn't typically use api_key, pass it if provided
            **ollama_kwargs
        )
    else:
        raise ValueError(f"Unsupported provider: {provider}. Must be one of {ProviderType.__args__}") 

クラス・関数一覧

名前 種別 概要
get_llm 関数 モデル名・プロバイダー名からLLMインスタンスを取得
AgentPipeline クラス 生成・評価・ツール・ガードレールを統合したパイプライン
ConsoleTracingProcessor クラス コンソール色分けトレース出力用プロセッサ
enable_console_tracing 関数 コンソールトレーシングを有効化
disable_tracing 関数 トレーシング機能をすべて無効化
OpenAIResponsesModel クラス OpenAI用モデルラッパー
GeminiModel クラス Google Gemini用モデルラッパー
ClaudeModel クラス Anthropic Claude用モデルラッパー
OllamaModel クラス Ollama用モデルラッパー

get_llm

  • モデル名・プロバイダー名からLLMインスタンスを返すファクトリ関数

  • 引数:

    • model (str): モデル名
    • provider (str, optional): プロバイダー名(省略時は自動推論)
    • temperature (float, optional): サンプリング温度
    • api_key (str, optional): プロバイダーAPIキー
    • base_url (str, optional): プロバイダーAPIベースURL
    • thinking (bool, optional): Claudeモデル思考モード
    • tracing (bool, optional): Agents SDK トレーシング有効化
  • 戻り値: LLMインスタンス

引数

名前 必須/オプション デフォルト 説明
model str 必須 - 使用するLLMモデル名
provider str (optional) オプション None モデルのプロバイダー名(自動推論可)
temperature float (optional) オプション 0.3 サンプリング温度
api_key str (optional) オプション None プロバイダーAPIキー
base_url str (optional) オプション None プロバイダーAPIベースURL
thinking bool (optional) オプション False Claudeモデルの思考モード
tracing bool (optional) オプション False Agents SDKのトレーシングを有効化するか

戻り値

LLMインスタンス

enable_console_tracing

  • コンソールトレーシング(ConsoleTracingProcessor)を有効化します。
  • 引数: なし
  • 戻り値: なし

disable_tracing

  • 全てのトレーシング機能(SDKおよびコンソール)を無効化します。
  • 引数: なし
  • 戻り値: なし

AgentPipeline

  • 生成・評価・ツール・ガードレールを統合したパイプライン管理クラス
  • 主な引数:
    • name (str): パイプライン名
    • generation_instructions (str): 生成用プロンプト
    • evaluation_instructions (str, optional): 評価用プロンプト
    • model (str or LLM): 使用するモデル
    • evaluation_model (str or LLM, optional): 評価に使用するモデル名またはLLMインスタンス(省略時はmodelを使用)
    • generation_tools (list, optional): 生成時ツール
    • input_guardrails/output_guardrails (list, optional): 入出力ガードレール
    • threshold (int): 評価閾値
    • retries (int): リトライ回数
    • retry_comment_importance (list[str], optional): 重要度指定
  • 主なメソッド:
    • run(input): 入力に対して生成・評価・自己改善を実行
  • 戻り値: 生成・評価結果

引数

名前 必須/オプション デフォルト 説明
name str 必須 - パイプライン名
generation_instructions str 必須 - 生成用システムプロンプト
evaluation_instructions str (optional) オプション None 評価用システムプロンプト
model str or LLM オプション None 使用するLLMモデル名またはLLMインスタンス
evaluation_model str or LLM オプション None 評価に使用するモデル名またはLLMインスタンス(省略時はmodelを使用)
generation_tools list (optional) オプション [] 生成時に使用するツールのリスト
evaluation_tools list (optional) オプション [] 評価時に使用するツールのリスト
input_guardrails list (optional) オプション [] 生成時の入力ガードレールリスト
output_guardrails list (optional) オプション [] 評価時の出力ガードレールリスト
routing_func Callable (optional) オプション None 出力ルーティング用関数
session_history list (optional) オプション [] セッション履歴
history_size int オプション 10 履歴保持数
threshold int オプション 85 評価スコアの閾値
retries int オプション 3 リトライ試行回数
improvement_callback Callable[[Any, EvaluationResult], None] (optional) オプション None 改善提案用コールバック
dynamic_prompt Callable[[str], str] (optional) オプション None 動的プロンプト生成関数
retry_comment_importance list[str] (optional) オプション [] リトライ時にプロンプトに含めるコメント重大度

戻り値

生成・評価結果(EvaluationResultを含むオブジェクト)

モデルラッパークラス

クラス名 概要
OpenAIResponsesModel OpenAI API用
GeminiModel Google Gemini API用
ClaudeModel Anthropic Claude API用
OllamaModel Ollama API用

クラス図(mermaid)

classDiagram
    class AgentPipeline {
        +run(input)
        -_build_generation_prompt()
        -_build_evaluation_prompt()
    }
    class OpenAIResponsesModel
    class GeminiModel
    class ClaudeModel
    class OllamaModel

    AgentPipeline --> OpenAIResponsesModel
    AgentPipeline --> GeminiModel
    AgentPipeline --> ClaudeModel
    AgentPipeline --> OllamaModel