コンテンツにスキップ

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を使用してコンテンツの生成と評価を管理するパイプラインクラス

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

Source code in src\agents_sdk_models\pipeline.py
 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
class AgentPipeline:
    """
    AgentPipeline class for managing the generation and evaluation of content using OpenAI Agents SDK
    OpenAI Agents SDKを使用してコンテンツの生成と評価を管理するパイプラインクラス

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

    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,
    ) -> None:
        """
        Initialize the Pipeline with configuration parameters
        設定パラメータでパイプラインを初期化する

        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 / リトライ時にプロンプトに含めるコメントの重大度レベル(任意)
        """
        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 []

        # 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,
        )

        json_instr ="""
        ----
        出力フォーマット:
        JSON で必ず次の形式にしてください:
        {
            "score": int(0~100),
            "comment": [str]
        }"
        """
        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)
        return "\n".join(filter(None, [session, recent, f"UserInput: {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 = [
            "----",
            f"ユーザー入力:\n{user_input}",
            "----",
            f"生成結果:\n{generated_output}",
        ]
        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 comments
                comment_lines = "\n".join(f"- ({c.get('importance')}) {c.get('content')}" for c in comments)
            else:
                comment_lines = ""
            # Build base prompt
            if attempt > 0 and comment_lines:
                base = self.dynamic_prompt(user_input) if self.dynamic_prompt else self._build_generation_prompt(user_input)
                gen_prompt = "\n".join([comment_lines, base])
            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=["評価 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)

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

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
Source code in src\agents_sdk_models\pipeline.py
 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
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,
) -> None:
    """
    Initialize the Pipeline with configuration parameters
    設定パラメータでパイプラインを初期化する

    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 / リトライ時にプロンプトに含めるコメントの重大度レベル(任意)
    """
    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 []

    # 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,
    )

    json_instr ="""
    ----
    出力フォーマット:
    JSON で必ず次の形式にしてください:
    {
        "score": int(0~100),
        "comment": [str]
    }"
    """
    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
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
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 comments
            comment_lines = "\n".join(f"- ({c.get('importance')}) {c.get('content')}" for c in comments)
        else:
            comment_lines = ""
        # Build base prompt
        if attempt > 0 and comment_lines:
            base = self.dynamic_prompt(user_input) if self.dynamic_prompt else self._build_generation_prompt(user_input)
            gen_prompt = "\n".join([comment_lines, base])
        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=["評価 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

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
    )

EvaluationResult dataclass

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

Source code in src\agents_sdk_models\pipeline.py
24
25
26
27
28
29
30
31
@dataclass
class EvaluationResult:
    """
    Result of evaluation for generated content
    生成されたコンテンツの評価結果を保持するクラス
    """
    score: int  # Evaluation score (0-100) / 評価スコア(0-100)
    comment: List[str]  # List of evaluation comments / 評価コメントのリスト

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
    )

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
    )

disable_tracing()

English: Disable all tracing. 日本語: トレーシング機能をすべて無効化します。

Source code in src\agents_sdk_models\tracing.py
124
125
126
127
128
129
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
113
114
115
116
117
118
119
120
121
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
    add_trace_processor(ConsoleTracingProcessor())

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
 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
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
        if not base_url:
            base_url = "http://localhost:11434"
        # 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