mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: Standardize docstrings: Use Keyword Args for Settings classes and add environment variable examples (#1202)
* Initial plan * Update Settings classes to use Keyword Args and add examples Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Add examples and env var documentation to chat clients Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Add env var docs and examples to Responses and AzureAI clients Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Remove Args from class docstrings where they belong in __init__ Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Add env var docs and examples to Assistants clients Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * updated to keyword args * Fix incorrect code block formatting in _workflows/_executor.py Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Fix markdown code blocks in _workflows/_edge.py - use Sphinx format Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> * Update _assistants_client.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: eavanvalkenburg <13749212+eavanvalkenburg@users.noreply.github.com> Co-authored-by: eavanvalkenburg <github@vanvalkenburg.eu> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
0cd794abe7
commit
8bd3e11d3e
@@ -104,13 +104,31 @@ class AzureAISettings(AFBaseSettings):
|
||||
with the encoding 'utf-8'. If the settings are not found in the .env file, the settings
|
||||
are ignored; however, validation will fail alerting that the settings are missing.
|
||||
|
||||
Args:
|
||||
Keyword Args:
|
||||
project_endpoint: The Azure AI Project endpoint URL.
|
||||
(Env var AZURE_AI_PROJECT_ENDPOINT)
|
||||
Can be set via environment variable AZURE_AI_PROJECT_ENDPOINT.
|
||||
model_deployment_name: The name of the model deployment to use.
|
||||
(Env var AZURE_AI_MODEL_DEPLOYMENT_NAME)
|
||||
Can be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
|
||||
env_file_path: If provided, the .env settings are read from this file path location.
|
||||
env_file_encoding: The encoding of the .env file, defaults to 'utf-8'.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework_azure_ai import AzureAISettings
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_AI_PROJECT_ENDPOINT=https://your-project.cognitiveservices.azure.com
|
||||
# Set AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4
|
||||
settings = AzureAISettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = AzureAISettings(
|
||||
project_endpoint="https://your-project.cognitiveservices.azure.com", model_deployment_name="gpt-4"
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
settings = AzureAISettings(env_file_path="path/to/.env")
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = "AZURE_AI_"
|
||||
@@ -144,24 +162,47 @@ class AzureAIAgentClient(BaseChatClient):
|
||||
env_file_encoding: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Initialize a AzureAIAgentClient.
|
||||
"""Initialize an Azure AI Agent client.
|
||||
|
||||
Args:
|
||||
Keyword Args:
|
||||
project_client: An existing AIProjectClient to use. If not provided, one will be created.
|
||||
agent_id: The ID of an existing agent to use. If not provided and project_client is provided,
|
||||
a new agent will be created (and deleted after the request). If neither project_client
|
||||
nor agent_id is provided, both will be created and managed automatically.
|
||||
agent_name: The name to use when creating new agents.
|
||||
thread_id: Default thread ID to use for conversations. Can be overridden by
|
||||
conversation_id property, when making a request.
|
||||
project_endpoint: The Azure AI Project endpoint URL, can also be set via
|
||||
'AZURE_AI_PROJECT_ENDPOINT' environment variable. Is ignored when a project_client is passed.
|
||||
conversation_id property when making a request.
|
||||
project_endpoint: The Azure AI Project endpoint URL.
|
||||
Can also be set via environment variable AZURE_AI_PROJECT_ENDPOINT.
|
||||
Ignored when a project_client is passed.
|
||||
model_deployment_name: The model deployment name to use for agent creation.
|
||||
Can also be set via 'AZURE_AI_MODEL_DEPLOYMENT_NAME' environment variable.
|
||||
Can also be set via environment variable AZURE_AI_MODEL_DEPLOYMENT_NAME.
|
||||
async_credential: Azure async credential to use for authentication.
|
||||
env_file_path: Path to environment file for loading settings.
|
||||
env_file_encoding: Encoding of the environment file.
|
||||
**kwargs: Additional keyword arguments passed to the parent class.
|
||||
kwargs: Additional keyword arguments passed to the parent class.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework_azure_ai import AzureAIAgentClient
|
||||
from azure.identity.aio import DefaultAzureCredential
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_AI_PROJECT_ENDPOINT=https://your-project.cognitiveservices.azure.com
|
||||
# Set AZURE_AI_MODEL_DEPLOYMENT_NAME=gpt-4
|
||||
credential = DefaultAzureCredential()
|
||||
client = AzureAIAgentClient(async_credential=credential)
|
||||
|
||||
# Or passing parameters directly
|
||||
client = AzureAIAgentClient(
|
||||
project_endpoint="https://your-project.cognitiveservices.azure.com",
|
||||
model_deployment_name="gpt-4",
|
||||
async_credential=credential,
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureAIAgentClient(async_credential=credential, env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
azure_ai_settings = AzureAISettings(
|
||||
|
||||
@@ -31,18 +31,33 @@ class CopilotStudioSettings(AFBaseSettings):
|
||||
with the encoding 'utf-8'. If the settings are not found in the .env file, the settings
|
||||
are ignored; however, validation will fail alerting that the settings are missing.
|
||||
|
||||
Attributes:
|
||||
environmentid: Environment ID of environment with the Copilot Studio App..
|
||||
(Env var COPILOTSTUDIOAGENT__ENVIRONMENTID)
|
||||
Keyword Args:
|
||||
environmentid: Environment ID of environment with the Copilot Studio App.
|
||||
Can be set via environment variable COPILOTSTUDIOAGENT__ENVIRONMENTID.
|
||||
schemaname: The agent identifier or schema name of the Copilot to use.
|
||||
(Env var COPILOTSTUDIOAGENT__SCHEMANAME)
|
||||
Can be set via environment variable COPILOTSTUDIOAGENT__SCHEMANAME.
|
||||
agentappid: The app ID of the App Registration used to login.
|
||||
(Env var COPILOTSTUDIOAGENT__AGENTAPPID)
|
||||
Can be set via environment variable COPILOTSTUDIOAGENT__AGENTAPPID.
|
||||
tenantid: The tenant ID of the App Registration used to login.
|
||||
(Env var COPILOTSTUDIOAGENT__TENANTID)
|
||||
Parameters:
|
||||
Can be set via environment variable COPILOTSTUDIOAGENT__TENANTID.
|
||||
env_file_path: If provided, the .env settings are read from this file path location.
|
||||
env_file_encoding: The encoding of the .env file, defaults to 'utf-8'.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework_copilotstudio import CopilotStudioSettings
|
||||
|
||||
# Using environment variables
|
||||
# Set COPILOTSTUDIOAGENT__ENVIRONMENTID=env-123
|
||||
# Set COPILOTSTUDIOAGENT__SCHEMANAME=my-agent
|
||||
settings = CopilotStudioSettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = CopilotStudioSettings(environmentid="env-123", schemaname="my-agent")
|
||||
|
||||
# Or loading from a .env file
|
||||
settings = CopilotStudioSettings(env_file_path="path/to/.env")
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = "COPILOTSTUDIOAGENT__"
|
||||
|
||||
@@ -161,9 +161,6 @@ class ChatMessageStore:
|
||||
The store maintains messages in memory and provides methods to serialize
|
||||
and deserialize the state for persistence purposes.
|
||||
|
||||
Args:
|
||||
messages: The optional initial list of ChatMessage objects to populate the store.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
|
||||
@@ -195,11 +195,6 @@ class BaseTool(SerializationMixin):
|
||||
|
||||
This class provides the foundation for creating custom tools with serialization support.
|
||||
|
||||
Args:
|
||||
name: The name of the tool.
|
||||
description: A description of the tool.
|
||||
additional_properties: Additional properties associated with the tool.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
@@ -545,25 +540,16 @@ def _default_histogram() -> Histogram:
|
||||
|
||||
|
||||
class AIFunction(BaseTool, Generic[ArgsT, ReturnT]):
|
||||
"""A AITool that is callable as code.
|
||||
"""A tool that wraps a Python function to make it callable by AI models.
|
||||
|
||||
This class wraps a Python function to make it callable by AI models with automatic
|
||||
parameter validation and JSON schema generation.
|
||||
|
||||
Args:
|
||||
name: The name of the function.
|
||||
description: A description of the function.
|
||||
approval_mode: Whether or not approval is required to run this tool.
|
||||
Default is that approval is not needed.
|
||||
additional_properties: Additional properties to set on the function.
|
||||
func: The function to wrap.
|
||||
input_model: The Pydantic model that defines the input parameters for the function.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from typing import Annotated
|
||||
from pydantic import BaseModel
|
||||
from pydantic import BaseModel, Field
|
||||
from agent_framework import AIFunction, ai_function
|
||||
|
||||
|
||||
|
||||
@@ -401,13 +401,7 @@ AnnotatedRegions = TextSpanRegion
|
||||
|
||||
|
||||
class BaseAnnotation(SerializationMixin):
|
||||
"""Base class for all AI Annotation types.
|
||||
|
||||
Args:
|
||||
additional_properties: Optional additional properties associated with the content.
|
||||
raw_representation: Optional raw representation of the content from an underlying implementation.
|
||||
|
||||
"""
|
||||
"""Base class for all AI Annotation types."""
|
||||
|
||||
DEFAULT_EXCLUDE: ClassVar[set[str]] = {"raw_representation", "additional_properties"}
|
||||
|
||||
|
||||
@@ -20,14 +20,14 @@ def _extract_function_name(func: Callable[..., Any]) -> str:
|
||||
stable value so that serialized representations remain intelligible when
|
||||
they are later rendered in logs or reconstructed during deserialization.
|
||||
|
||||
Example:
|
||||
```python
|
||||
def threshold(value: float) -> bool:
|
||||
return value > 0.5
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
def threshold(value: float) -> bool:
|
||||
return value > 0.5
|
||||
|
||||
|
||||
assert _extract_function_name(threshold) == "threshold"
|
||||
```
|
||||
assert _extract_function_name(threshold) == "threshold"
|
||||
"""
|
||||
if hasattr(func, "__name__"):
|
||||
name = func.__name__
|
||||
@@ -44,14 +44,14 @@ def _missing_callable(name: str) -> Callable[..., Any]:
|
||||
runtime execution, while making it obvious which callable needs to be
|
||||
re-registered.
|
||||
|
||||
Example:
|
||||
```python
|
||||
guard = _missing_callable("transform_price")
|
||||
try:
|
||||
guard()
|
||||
except RuntimeError as exc:
|
||||
assert "transform_price" in str(exc)
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
guard = _missing_callable("transform_price")
|
||||
try:
|
||||
guard()
|
||||
except RuntimeError as exc:
|
||||
assert "transform_price" in str(exc)
|
||||
"""
|
||||
|
||||
def _raise(*_: Any, **__: Any) -> Any:
|
||||
@@ -70,12 +70,12 @@ class Edge(DictConvertible):
|
||||
serialising the edge down to primitives we can reconstruct the topology of
|
||||
a workflow irrespective of the original Python process.
|
||||
|
||||
Example:
|
||||
```python
|
||||
edge = Edge(source_id="ingest", target_id="score", condition=lambda payload: payload["ready"])
|
||||
assert edge.should_route({"ready": True}) is True
|
||||
assert edge.should_route({"ready": False}) is False
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edge = Edge(source_id="ingest", target_id="score", condition=lambda payload: payload["ready"])
|
||||
assert edge.should_route({"ready": True}) is True
|
||||
assert edge.should_route({"ready": False}) is False
|
||||
"""
|
||||
|
||||
ID_SEPARATOR: ClassVar[str] = "->"
|
||||
@@ -110,12 +110,12 @@ class Edge(DictConvertible):
|
||||
when the callable cannot be introspected (for example after
|
||||
deserialization).
|
||||
|
||||
Example:
|
||||
```python
|
||||
edge = Edge("fetch", "parse", condition=lambda data: data.is_valid)
|
||||
assert edge.source_id == "fetch"
|
||||
assert edge.target_id == "parse"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edge = Edge("fetch", "parse", condition=lambda data: data.is_valid)
|
||||
assert edge.source_id == "fetch"
|
||||
assert edge.target_id == "parse"
|
||||
"""
|
||||
if not source_id:
|
||||
raise ValueError("Edge source_id must be a non-empty string")
|
||||
@@ -135,11 +135,11 @@ class Edge(DictConvertible):
|
||||
adjacency lists or visualisations to refer to an edge without carrying
|
||||
the full object.
|
||||
|
||||
Example:
|
||||
```python
|
||||
edge = Edge("reader", "writer")
|
||||
assert edge.id == "reader->writer"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edge = Edge("reader", "writer")
|
||||
assert edge.id == "reader->writer"
|
||||
"""
|
||||
return f"{self.source_id}{self.ID_SEPARATOR}{self.target_id}"
|
||||
|
||||
@@ -152,12 +152,12 @@ class Edge(DictConvertible):
|
||||
this edge. Any exception raised by the callable is deliberately allowed
|
||||
to surface to the caller to avoid masking logic bugs.
|
||||
|
||||
Example:
|
||||
```python
|
||||
edge = Edge("stage1", "stage2", condition=lambda payload: payload["score"] > 0.8)
|
||||
assert edge.should_route({"score": 0.9}) is True
|
||||
assert edge.should_route({"score": 0.4}) is False
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edge = Edge("stage1", "stage2", condition=lambda payload: payload["score"] > 0.8)
|
||||
assert edge.should_route({"score": 0.9}) is True
|
||||
assert edge.should_route({"score": 0.4}) is False
|
||||
"""
|
||||
if self._condition is None:
|
||||
return True
|
||||
@@ -170,12 +170,12 @@ class Edge(DictConvertible):
|
||||
plus the condition name when it is known. Serialisation intentionally
|
||||
omits the live callable to keep payloads transport-friendly.
|
||||
|
||||
Example:
|
||||
```python
|
||||
edge = Edge("reader", "writer", condition=lambda payload: payload["ok"])
|
||||
snapshot = edge.to_dict()
|
||||
assert snapshot == {"source_id": "reader", "target_id": "writer", "condition_name": "<lambda>"}
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edge = Edge("reader", "writer", condition=lambda payload: payload["ok"])
|
||||
snapshot = edge.to_dict()
|
||||
assert snapshot == {"source_id": "reader", "target_id": "writer", "condition_name": "<lambda>"}
|
||||
"""
|
||||
payload = {"source_id": self.source_id, "target_id": self.target_id}
|
||||
if self.condition_name is not None:
|
||||
@@ -191,13 +191,13 @@ class Edge(DictConvertible):
|
||||
stored `condition_name` is preserved so that downstream consumers can
|
||||
detect missing callables and re-register them where appropriate.
|
||||
|
||||
Example:
|
||||
```python
|
||||
payload = {"source_id": "reader", "target_id": "writer", "condition_name": "is_ready"}
|
||||
edge = Edge.from_dict(payload)
|
||||
assert edge.source_id == "reader"
|
||||
assert edge.condition_name == "is_ready"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
payload = {"source_id": "reader", "target_id": "writer", "condition_name": "is_ready"}
|
||||
edge = Edge.from_dict(payload)
|
||||
assert edge.source_id == "reader"
|
||||
assert edge.condition_name == "is_ready"
|
||||
"""
|
||||
return cls(
|
||||
source_id=data["source_id"],
|
||||
@@ -217,17 +217,17 @@ class Case:
|
||||
`SwitchCaseEdgeGroupCase` so that execution can operate with live callables
|
||||
without polluting persisted state.
|
||||
|
||||
Example:
|
||||
```python
|
||||
class JsonExecutor(Executor):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(id="json", defer_discovery=True)
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
class JsonExecutor(Executor):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(id="json", defer_discovery=True)
|
||||
|
||||
|
||||
processor = JsonExecutor()
|
||||
case = Case(condition=lambda payload: payload["kind"] == "json", target=processor)
|
||||
assert case.target.id == "json"
|
||||
```
|
||||
processor = JsonExecutor()
|
||||
case = Case(condition=lambda payload: payload["kind"] == "json", target=processor)
|
||||
assert case.target.id == "json"
|
||||
"""
|
||||
|
||||
condition: Callable[[Any], bool]
|
||||
@@ -242,16 +242,16 @@ class Default:
|
||||
practice it is guaranteed to exist so that routing never produces an empty
|
||||
target.
|
||||
|
||||
Example:
|
||||
```python
|
||||
class DeadLetterExecutor(Executor):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(id="dead_letter", defer_discovery=True)
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
class DeadLetterExecutor(Executor):
|
||||
def __init__(self) -> None:
|
||||
super().__init__(id="dead_letter", defer_discovery=True)
|
||||
|
||||
|
||||
fallback = Default(target=DeadLetterExecutor())
|
||||
assert fallback.target.id == "dead_letter"
|
||||
```
|
||||
fallback = Default(target=DeadLetterExecutor())
|
||||
assert fallback.target.id == "dead_letter"
|
||||
"""
|
||||
|
||||
target: Executor
|
||||
@@ -267,11 +267,11 @@ class EdgeGroup(DictConvertible):
|
||||
identifying information and handles serialisation duties so specialised
|
||||
groups need only maintain their additional state.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = EdgeGroup([Edge("source", "sink")])
|
||||
assert group.source_executor_ids == ["source"]
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = EdgeGroup([Edge("source", "sink")])
|
||||
assert group.source_executor_ids == ["source"]
|
||||
"""
|
||||
|
||||
id: str
|
||||
@@ -303,12 +303,12 @@ class EdgeGroup(DictConvertible):
|
||||
Logical discriminator used to recover the appropriate subclass when
|
||||
de-serialising.
|
||||
|
||||
Example:
|
||||
```python
|
||||
edges = [Edge("validate", "persist")]
|
||||
group = EdgeGroup(edges, id="stage", type="Custom")
|
||||
assert group.to_dict()["type"] == "Custom"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
edges = [Edge("validate", "persist")]
|
||||
group = EdgeGroup(edges, id="stage", type="Custom")
|
||||
assert group.to_dict()["type"] == "Custom"
|
||||
"""
|
||||
self.id = id or f"{self.__class__.__name__}/{uuid.uuid4()}"
|
||||
self.type = type or self.__class__.__name__
|
||||
@@ -321,11 +321,11 @@ class EdgeGroup(DictConvertible):
|
||||
The property preserves order-of-first-appearance so the caller can rely
|
||||
on deterministic iteration when reconstructing graph topology.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = EdgeGroup([Edge("read", "write"), Edge("read", "archive")])
|
||||
assert group.source_executor_ids == ["read"]
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = EdgeGroup([Edge("read", "write"), Edge("read", "archive")])
|
||||
assert group.source_executor_ids == ["read"]
|
||||
"""
|
||||
return list(dict.fromkeys(edge.source_id for edge in self.edges))
|
||||
|
||||
@@ -333,11 +333,11 @@ class EdgeGroup(DictConvertible):
|
||||
def target_executor_ids(self) -> list[str]:
|
||||
"""Return the ordered, deduplicated list of downstream executor ids.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = EdgeGroup([Edge("read", "write"), Edge("read", "archive")])
|
||||
assert group.target_executor_ids == ["write", "archive"]
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = EdgeGroup([Edge("read", "write"), Edge("read", "archive")])
|
||||
assert group.target_executor_ids == ["write", "archive"]
|
||||
"""
|
||||
return list(dict.fromkeys(edge.target_id for edge in self.edges))
|
||||
|
||||
@@ -348,12 +348,12 @@ class EdgeGroup(DictConvertible):
|
||||
round-tripping through formats such as JSON without leaking Python
|
||||
objects.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = EdgeGroup([Edge("read", "write")])
|
||||
snapshot = group.to_dict()
|
||||
assert snapshot["edges"][0]["source_id"] == "read"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = EdgeGroup([Edge("read", "write")])
|
||||
snapshot = group.to_dict()
|
||||
assert snapshot["edges"][0]["source_id"] == "read"
|
||||
"""
|
||||
return {
|
||||
"id": self.id,
|
||||
@@ -370,15 +370,15 @@ class EdgeGroup(DictConvertible):
|
||||
`__name__`, which must therefore remain stable across versions when
|
||||
persisted workflows are in circulation.
|
||||
|
||||
Example:
|
||||
```python
|
||||
@EdgeGroup.register
|
||||
class CustomGroup(EdgeGroup):
|
||||
pass
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
@EdgeGroup.register
|
||||
class CustomGroup(EdgeGroup):
|
||||
pass
|
||||
|
||||
|
||||
assert EdgeGroup._TYPE_REGISTRY["CustomGroup"] is CustomGroup
|
||||
```
|
||||
assert EdgeGroup._TYPE_REGISTRY["CustomGroup"] is CustomGroup
|
||||
"""
|
||||
cls._TYPE_REGISTRY[subclass.__name__] = subclass
|
||||
return subclass
|
||||
@@ -393,12 +393,12 @@ class EdgeGroup(DictConvertible):
|
||||
even for complex group types that configure additional runtime
|
||||
callables.
|
||||
|
||||
Example:
|
||||
```python
|
||||
payload = {"type": "EdgeGroup", "edges": [{"source_id": "a", "target_id": "b"}]}
|
||||
group = EdgeGroup.from_dict(payload)
|
||||
assert isinstance(group, EdgeGroup)
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
payload = {"type": "EdgeGroup", "edges": [{"source_id": "a", "target_id": "b"}]}
|
||||
group = EdgeGroup.from_dict(payload)
|
||||
assert isinstance(group, EdgeGroup)
|
||||
"""
|
||||
group_type = data.get("type", "EdgeGroup")
|
||||
target_cls = cls._TYPE_REGISTRY.get(group_type, EdgeGroup)
|
||||
@@ -448,11 +448,11 @@ class SingleEdgeGroup(EdgeGroup):
|
||||
) -> None:
|
||||
"""Create a one-to-one edge group between two executors.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = SingleEdgeGroup("ingest", "validate")
|
||||
assert group.edges[0].source_id == "ingest"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = SingleEdgeGroup("ingest", "validate")
|
||||
assert group.edges[0].source_id == "ingest"
|
||||
"""
|
||||
edge = Edge(source_id=source_id, target_id=target_id, condition=condition)
|
||||
super().__init__([edge], id=id, type=self.__class__.__name__)
|
||||
@@ -503,15 +503,15 @@ class FanOutEdgeGroup(EdgeGroup):
|
||||
id:
|
||||
Stable identifier for the group; defaults to an autogenerated UUID.
|
||||
|
||||
Example:
|
||||
```python
|
||||
def choose_targets(message: dict[str, Any], available: list[str]) -> list[str]:
|
||||
return [target for target in available if message.get(target)]
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
def choose_targets(message: dict[str, Any], available: list[str]) -> list[str]:
|
||||
return [target for target in available if message.get(target)]
|
||||
|
||||
|
||||
group = FanOutEdgeGroup("sensor", ["db", "cache"], selection_func=choose_targets)
|
||||
assert group.selection_func is choose_targets
|
||||
```
|
||||
group = FanOutEdgeGroup("sensor", ["db", "cache"], selection_func=choose_targets)
|
||||
assert group.selection_func is choose_targets
|
||||
"""
|
||||
if len(target_ids) <= 1:
|
||||
raise ValueError("FanOutEdgeGroup must contain at least two targets.")
|
||||
@@ -532,11 +532,11 @@ class FanOutEdgeGroup(EdgeGroup):
|
||||
The list is defensively copied to prevent callers from mutating the
|
||||
internal state while still providing deterministic ordering.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = FanOutEdgeGroup("node", ["alpha", "beta"])
|
||||
assert group.target_ids == ["alpha", "beta"]
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = FanOutEdgeGroup("node", ["alpha", "beta"])
|
||||
assert group.target_ids == ["alpha", "beta"]
|
||||
"""
|
||||
return list(self._target_ids)
|
||||
|
||||
@@ -547,11 +547,11 @@ class FanOutEdgeGroup(EdgeGroup):
|
||||
When no selection function was supplied the property returns `None`,
|
||||
signalling that all targets must receive the payload.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = FanOutEdgeGroup("source", ["x", "y"], selection_func=None)
|
||||
assert group.selection_func is None
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = FanOutEdgeGroup("source", ["x", "y"], selection_func=None)
|
||||
assert group.selection_func is None
|
||||
"""
|
||||
return self._selection_func
|
||||
|
||||
@@ -561,12 +561,12 @@ class FanOutEdgeGroup(EdgeGroup):
|
||||
In addition to the base `EdgeGroup` payload we embed the human-friendly
|
||||
name of the selection function. The callable itself is not persisted.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = FanOutEdgeGroup("source", ["a", "b"], selection_func=lambda *_: ["a"])
|
||||
snapshot = group.to_dict()
|
||||
assert snapshot["selection_func_name"] == "<lambda>"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = FanOutEdgeGroup("source", ["a", "b"], selection_func=lambda *_: ["a"])
|
||||
snapshot = group.to_dict()
|
||||
assert snapshot["selection_func_name"] == "<lambda>"
|
||||
"""
|
||||
payload = super().to_dict()
|
||||
payload["selection_func_name"] = self.selection_func_name
|
||||
@@ -595,11 +595,11 @@ class FanInEdgeGroup(EdgeGroup):
|
||||
id:
|
||||
Optional explicit identifier for the edge group.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = FanInEdgeGroup(["parser", "enricher"], target_id="writer")
|
||||
assert group.to_dict()["edges"][0]["target_id"] == "writer"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = FanInEdgeGroup(["parser", "enricher"], target_id="writer")
|
||||
assert group.to_dict()["edges"][0]["target_id"] == "writer"
|
||||
"""
|
||||
if len(source_ids) <= 1:
|
||||
raise ValueError("FanInEdgeGroup must contain at least two sources.")
|
||||
@@ -645,11 +645,11 @@ class SwitchCaseEdgeGroupCase(DictConvertible):
|
||||
Human-friendly label for the predicate used for diagnostics and
|
||||
on-disk persistence.
|
||||
|
||||
Example:
|
||||
```python
|
||||
case = SwitchCaseEdgeGroupCase(lambda payload: payload["type"] == "csv", target_id="csv_handler")
|
||||
assert case.condition_name == "<lambda>"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
case = SwitchCaseEdgeGroupCase(lambda payload: payload["type"] == "csv", target_id="csv_handler")
|
||||
assert case.condition_name == "<lambda>"
|
||||
"""
|
||||
if not target_id:
|
||||
raise ValueError("SwitchCaseEdgeGroupCase requires a target_id")
|
||||
@@ -671,26 +671,26 @@ class SwitchCaseEdgeGroupCase(DictConvertible):
|
||||
`RuntimeError` when invoked so that workflow authors are forced to
|
||||
provide the missing callable explicitly.
|
||||
|
||||
Example:
|
||||
```python
|
||||
case = SwitchCaseEdgeGroupCase(None, target_id="missing", condition_name="needs_registration")
|
||||
guard = case.condition
|
||||
try:
|
||||
guard({})
|
||||
except RuntimeError:
|
||||
pass
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
case = SwitchCaseEdgeGroupCase(None, target_id="missing", condition_name="needs_registration")
|
||||
guard = case.condition
|
||||
try:
|
||||
guard({})
|
||||
except RuntimeError:
|
||||
pass
|
||||
"""
|
||||
return self._condition
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialise the case metadata without the executable predicate.
|
||||
|
||||
Example:
|
||||
```python
|
||||
case = SwitchCaseEdgeGroupCase(lambda _: True, target_id="handler")
|
||||
assert case.to_dict()["target_id"] == "handler"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
case = SwitchCaseEdgeGroupCase(lambda _: True, target_id="handler")
|
||||
assert case.to_dict()["target_id"] == "handler"
|
||||
"""
|
||||
payload = {"target_id": self.target_id, "type": self.type}
|
||||
if self.condition_name is not None:
|
||||
@@ -701,12 +701,12 @@ class SwitchCaseEdgeGroupCase(DictConvertible):
|
||||
def from_dict(cls, data: dict[str, Any]) -> "SwitchCaseEdgeGroupCase":
|
||||
"""Instantiate a case from its serialised dictionary payload.
|
||||
|
||||
Example:
|
||||
```python
|
||||
payload = {"target_id": "handler", "condition_name": "is_ready"}
|
||||
case = SwitchCaseEdgeGroupCase.from_dict(payload)
|
||||
assert case.target_id == "handler"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
payload = {"target_id": "handler", "condition_name": "is_ready"}
|
||||
case = SwitchCaseEdgeGroupCase.from_dict(payload)
|
||||
assert case.target_id == "handler"
|
||||
"""
|
||||
return cls(
|
||||
condition=None,
|
||||
@@ -729,11 +729,11 @@ class SwitchCaseEdgeGroupDefault(DictConvertible):
|
||||
def __init__(self, target_id: str) -> None:
|
||||
"""Point the default branch toward the given executor identifier.
|
||||
|
||||
Example:
|
||||
```python
|
||||
fallback = SwitchCaseEdgeGroupDefault(target_id="dead_letter")
|
||||
assert fallback.target_id == "dead_letter"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
fallback = SwitchCaseEdgeGroupDefault(target_id="dead_letter")
|
||||
assert fallback.target_id == "dead_letter"
|
||||
"""
|
||||
if not target_id:
|
||||
raise ValueError("SwitchCaseEdgeGroupDefault requires a target_id")
|
||||
@@ -743,11 +743,11 @@ class SwitchCaseEdgeGroupDefault(DictConvertible):
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""Serialise the default branch metadata for persistence or logging.
|
||||
|
||||
Example:
|
||||
```python
|
||||
fallback = SwitchCaseEdgeGroupDefault("dead_letter")
|
||||
assert fallback.to_dict()["type"] == "Default"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
fallback = SwitchCaseEdgeGroupDefault("dead_letter")
|
||||
assert fallback.to_dict()["type"] == "Default"
|
||||
"""
|
||||
return {"target_id": self.target_id, "type": self.type}
|
||||
|
||||
@@ -755,12 +755,12 @@ class SwitchCaseEdgeGroupDefault(DictConvertible):
|
||||
def from_dict(cls, data: dict[str, Any]) -> "SwitchCaseEdgeGroupDefault":
|
||||
"""Recreate the default branch from its persisted form.
|
||||
|
||||
Example:
|
||||
```python
|
||||
payload = {"target_id": "dead_letter", "type": "Default"}
|
||||
fallback = SwitchCaseEdgeGroupDefault.from_dict(payload)
|
||||
assert fallback.target_id == "dead_letter"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
payload = {"target_id": "dead_letter", "type": "Default"}
|
||||
fallback = SwitchCaseEdgeGroupDefault.from_dict(payload)
|
||||
assert fallback.target_id == "dead_letter"
|
||||
"""
|
||||
return cls(target_id=data["target_id"])
|
||||
|
||||
@@ -797,16 +797,16 @@ class SwitchCaseEdgeGroup(FanOutEdgeGroup):
|
||||
id:
|
||||
Optional explicit identifier for the edge group.
|
||||
|
||||
Example:
|
||||
```python
|
||||
cases = [
|
||||
SwitchCaseEdgeGroupCase(lambda payload: payload["kind"] == "csv", target_id="process_csv"),
|
||||
SwitchCaseEdgeGroupDefault(target_id="process_default"),
|
||||
]
|
||||
group = SwitchCaseEdgeGroup("router", cases)
|
||||
encoded = group.to_dict()
|
||||
assert encoded["cases"][0]["type"] == "Case"
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
cases = [
|
||||
SwitchCaseEdgeGroupCase(lambda payload: payload["kind"] == "csv", target_id="process_csv"),
|
||||
SwitchCaseEdgeGroupDefault(target_id="process_default"),
|
||||
]
|
||||
group = SwitchCaseEdgeGroup("router", cases)
|
||||
encoded = group.to_dict()
|
||||
assert encoded["cases"][0]["type"] == "Case"
|
||||
"""
|
||||
if len(cases) < 2:
|
||||
raise ValueError("SwitchCaseEdgeGroup must contain at least two cases (including the default case).")
|
||||
@@ -849,18 +849,18 @@ class SwitchCaseEdgeGroup(FanOutEdgeGroup):
|
||||
Each case is converted using `encode_value` to respect dataclass
|
||||
semantics as well as any nested serialisable structures.
|
||||
|
||||
Example:
|
||||
```python
|
||||
group = SwitchCaseEdgeGroup(
|
||||
"router",
|
||||
[
|
||||
SwitchCaseEdgeGroupCase(lambda _: True, target_id="handler"),
|
||||
SwitchCaseEdgeGroupDefault(target_id="fallback"),
|
||||
],
|
||||
)
|
||||
snapshot = group.to_dict()
|
||||
assert len(snapshot["cases"]) == 2
|
||||
```
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
group = SwitchCaseEdgeGroup(
|
||||
"router",
|
||||
[
|
||||
SwitchCaseEdgeGroupCase(lambda _: True, target_id="handler"),
|
||||
SwitchCaseEdgeGroupDefault(target_id="fallback"),
|
||||
],
|
||||
)
|
||||
snapshot = group.to_dict()
|
||||
assert len(snapshot["cases"]) == 2
|
||||
"""
|
||||
payload = super().to_dict()
|
||||
payload["cases"] = [encode_value(case) for case in self.cases]
|
||||
|
||||
@@ -178,14 +178,13 @@ class Executor(DictConvertible):
|
||||
|
||||
@executor
|
||||
async def process_text(text: str, ctx: WorkflowContext[str]) -> None:
|
||||
await ctx.send_message(text.upper())
|
||||
await ctx.send_message(text.upper())
|
||||
|
||||
|
||||
# Or with custom ID:
|
||||
@executor(id="text_processor")
|
||||
def sync_process(text: str, ctx: WorkflowContext[str]) -> None:
|
||||
ctx.send_message(text.lower()) # Sync functions run in thread pool
|
||||
```
|
||||
# Or with custom ID:
|
||||
@executor(id="text_processor")
|
||||
def sync_process(text: str, ctx: WorkflowContext[str]) -> None:
|
||||
ctx.send_message(text.lower()) # Sync functions run in thread pool
|
||||
|
||||
## Sub-workflow Composition
|
||||
Executors can contain sub-workflows using WorkflowExecutor. Sub-workflows can make requests
|
||||
|
||||
@@ -23,6 +23,7 @@ class AzureOpenAIAssistantsClient(OpenAIAssistantsClient):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
deployment_name: str | None = None,
|
||||
assistant_id: str | None = None,
|
||||
assistant_name: str | None = None,
|
||||
@@ -42,32 +43,56 @@ class AzureOpenAIAssistantsClient(OpenAIAssistantsClient):
|
||||
) -> None:
|
||||
"""Initialize an Azure OpenAI Assistants client.
|
||||
|
||||
Args:
|
||||
Keyword Args:
|
||||
deployment_name: The Azure OpenAI deployment name for the model to use.
|
||||
Can also be set via environment variable AZURE_OPENAI_CHAT_DEPLOYMENT_NAME.
|
||||
assistant_id: The ID of an Azure OpenAI assistant to use.
|
||||
If not provided, a new assistant will be created (and deleted after the request).
|
||||
assistant_name: The name to use when creating new assistants.
|
||||
thread_id: Default thread ID to use for conversations. Can be overridden by
|
||||
conversation_id property, when making a request.
|
||||
conversation_id property when making a request.
|
||||
If not provided, a new thread will be created (and deleted after the request).
|
||||
api_key: The optional API key to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
endpoint: The optional deployment endpoint. If provided will override the value
|
||||
api_key: The API key to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable AZURE_OPENAI_API_KEY.
|
||||
endpoint: The deployment endpoint. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
base_url: The optional deployment base_url. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_ENDPOINT.
|
||||
base_url: The deployment base URL. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
api_version: The optional deployment api version. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_BASE_URL.
|
||||
api_version: The deployment API version. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
ad_token: The Azure Active Directory token. (Optional)
|
||||
ad_token_provider: The Azure Active Directory token provider. (Optional)
|
||||
token_endpoint: The token endpoint to request an Azure token. (Optional)
|
||||
credential: The Azure credential to use for authentication. (Optional)
|
||||
Can also be set via environment variable AZURE_OPENAI_API_VERSION.
|
||||
ad_token: The Azure Active Directory token.
|
||||
ad_token_provider: The Azure Active Directory token provider.
|
||||
token_endpoint: The token endpoint to request an Azure token.
|
||||
Can also be set via environment variable AZURE_OPENAI_TOKEN_ENDPOINT.
|
||||
credential: The Azure credential to use for authentication.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
env_file_path: Use the environment settings file as a fallback
|
||||
to environment variables. (Optional)
|
||||
env_file_encoding: The encoding of the environment settings file. (Optional)
|
||||
to environment variables.
|
||||
env_file_encoding: The encoding of the environment settings file.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureOpenAIAssistantsClient
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com
|
||||
# Set AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-4
|
||||
# Set AZURE_OPENAI_API_KEY=your-key
|
||||
client = AzureOpenAIAssistantsClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = AzureOpenAIAssistantsClient(
|
||||
endpoint="https://your-endpoint.openai.azure.com", deployment_name="gpt-4", api_key="your-key"
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureOpenAIAssistantsClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
azure_openai_settings = AzureOpenAISettings(
|
||||
|
||||
@@ -65,31 +65,55 @@ class AzureOpenAIChatClient(AzureOpenAIConfigMixin, OpenAIBaseChatClient):
|
||||
instruction_role: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Initialize an AzureChatCompletion service.
|
||||
"""Initialize an Azure OpenAI Chat completion client.
|
||||
|
||||
Args:
|
||||
api_key: The optional api key. If provided, will override the value in the
|
||||
env vars or .env file.
|
||||
deployment_name: The optional deployment. If provided, will override the value
|
||||
api_key: The API key. If provided, will override the value in the env vars or .env file.
|
||||
Can also be set via environment variable AZURE_OPENAI_API_KEY.
|
||||
deployment_name: The deployment name. If provided, will override the value
|
||||
(chat_deployment_name) in the env vars or .env file.
|
||||
endpoint: The optional deployment endpoint. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_CHAT_DEPLOYMENT_NAME.
|
||||
endpoint: The deployment endpoint. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
base_url: The optional deployment base_url. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_ENDPOINT.
|
||||
base_url: The deployment base URL. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
api_version: The optional deployment api version. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_BASE_URL.
|
||||
api_version: The deployment API version. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
ad_token: The Azure Active Directory token. (Optional)
|
||||
ad_token_provider: The Azure Active Directory token provider. (Optional)
|
||||
token_endpoint: The token endpoint to request an Azure token. (Optional)
|
||||
credential: The Azure credential for authentication. (Optional)
|
||||
Can also be set via environment variable AZURE_OPENAI_API_VERSION.
|
||||
ad_token: The Azure Active Directory token.
|
||||
ad_token_provider: The Azure Active Directory token provider.
|
||||
token_endpoint: The token endpoint to request an Azure token.
|
||||
Can also be set via environment variable AZURE_OPENAI_TOKEN_ENDPOINT.
|
||||
credential: The Azure credential for authentication.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
env_file_path: Use the environment settings file as a fallback to using env vars.
|
||||
env_file_encoding: The encoding of the environment settings file, defaults to 'utf-8'.
|
||||
instruction_role: The role to use for 'instruction' messages, for example, summarization
|
||||
prompts could use `developer` or `system`. (Optional)
|
||||
prompts could use `developer` or `system`.
|
||||
kwargs: Other keyword parameters.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureOpenAIChatClient
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com
|
||||
# Set AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-4
|
||||
# Set AZURE_OPENAI_API_KEY=your-key
|
||||
client = AzureOpenAIChatClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = AzureOpenAIChatClient(
|
||||
endpoint="https://your-endpoint.openai.azure.com", deployment_name="gpt-4", api_key="your-key"
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureOpenAIChatClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
# Filter out any None values from the arguments
|
||||
|
||||
@@ -29,6 +29,7 @@ class AzureOpenAIResponsesClient(AzureOpenAIConfigMixin, OpenAIBaseResponsesClie
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
api_key: str | None = None,
|
||||
deployment_name: str | None = None,
|
||||
endpoint: str | None = None,
|
||||
@@ -45,31 +46,55 @@ class AzureOpenAIResponsesClient(AzureOpenAIConfigMixin, OpenAIBaseResponsesClie
|
||||
instruction_role: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Initialize an AzureResponses service.
|
||||
"""Initialize an Azure OpenAI Responses client.
|
||||
|
||||
Args:
|
||||
api_key: The optional api key. If provided, will override the value in the
|
||||
env vars or .env file.
|
||||
deployment_name: The optional deployment. If provided, will override the value
|
||||
Keyword Args:
|
||||
api_key: The API key. If provided, will override the value in the env vars or .env file.
|
||||
Can also be set via environment variable AZURE_OPENAI_API_KEY.
|
||||
deployment_name: The deployment name. If provided, will override the value
|
||||
(responses_deployment_name) in the env vars or .env file.
|
||||
endpoint: The optional deployment endpoint. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME.
|
||||
endpoint: The deployment endpoint. If provided will override the value
|
||||
in the env vars or .env file.
|
||||
base_url: The optional deployment base_url. If provided will override the value
|
||||
in the env vars or .env file. Currently, the base_url must end with "/openai/v1/"
|
||||
api_version: The optional deployment api version. If provided will override the value
|
||||
Can also be set via environment variable AZURE_OPENAI_ENDPOINT.
|
||||
base_url: The deployment base URL. If provided will override the value
|
||||
in the env vars or .env file. Currently, the base_url must end with "/openai/v1/".
|
||||
Can also be set via environment variable AZURE_OPENAI_BASE_URL.
|
||||
api_version: The deployment API version. If provided will override the value
|
||||
in the env vars or .env file. Currently, the api_version must be "preview".
|
||||
ad_token: The Azure Active Directory token. (Optional)
|
||||
ad_token_provider: The Azure Active Directory token provider. (Optional)
|
||||
token_endpoint: The token endpoint to request an Azure token. (Optional)
|
||||
credential: The Azure credential for authentication. (Optional)
|
||||
Can also be set via environment variable AZURE_OPENAI_API_VERSION.
|
||||
ad_token: The Azure Active Directory token.
|
||||
ad_token_provider: The Azure Active Directory token provider.
|
||||
token_endpoint: The token endpoint to request an Azure token.
|
||||
Can also be set via environment variable AZURE_OPENAI_TOKEN_ENDPOINT.
|
||||
credential: The Azure credential for authentication.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
env_file_path: Use the environment settings file as a fallback to using env vars.
|
||||
env_file_encoding: The encoding of the environment settings file, defaults to 'utf-8'.
|
||||
instruction_role: The role to use for 'instruction' messages, for example, summarization
|
||||
prompts could use `developer` or `system`. (Optional)
|
||||
prompts could use `developer` or `system`.
|
||||
kwargs: Additional keyword arguments.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureOpenAIResponsesClient
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com
|
||||
# Set AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME=gpt-4o
|
||||
# Set AZURE_OPENAI_API_KEY=your-key
|
||||
client = AzureOpenAIResponsesClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = AzureOpenAIResponsesClient(
|
||||
endpoint="https://your-endpoint.openai.azure.com", deployment_name="gpt-4o", api_key="your-key"
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
client = AzureOpenAIResponsesClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
if model_id := kwargs.pop("model_id", None) and not deployment_name:
|
||||
deployment_name = str(model_id)
|
||||
|
||||
@@ -37,45 +37,64 @@ class AzureOpenAISettings(AFBaseSettings):
|
||||
with the encoding 'utf-8'. If the settings are not found in the .env file, the settings
|
||||
are ignored; however, validation will fail alerting that the settings are missing.
|
||||
|
||||
Args:
|
||||
Keyword Args:
|
||||
endpoint: The endpoint of the Azure deployment. This value
|
||||
can be found in the Keys & Endpoint section when examining
|
||||
your resource from the Azure portal, the endpoint should end in openai.azure.com.
|
||||
If both base_url and endpoint are supplied, base_url will be used.
|
||||
(Env var AZURE_OPENAI_ENDPOINT)
|
||||
Can be set via environment variable AZURE_OPENAI_ENDPOINT.
|
||||
chat_deployment_name: The name of the Azure Chat deployment. This value
|
||||
will correspond to the custom name you chose for your deployment
|
||||
when you deployed a model. This value can be found under
|
||||
Resource Management > Deployments in the Azure portal or, alternatively,
|
||||
under Management > Deployments in Azure AI Foundry.
|
||||
(Env var AZURE_OPENAI_CHAT_DEPLOYMENT_NAME)
|
||||
Can be set via environment variable AZURE_OPENAI_CHAT_DEPLOYMENT_NAME.
|
||||
responses_deployment_name: The name of the Azure Responses deployment. This value
|
||||
will correspond to the custom name you chose for your deployment
|
||||
when you deployed a model. This value can be found under
|
||||
Resource Management > Deployments in the Azure portal or, alternatively,
|
||||
under Management > Deployments in Azure AI Foundry.
|
||||
(Env var AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME)
|
||||
Can be set via environment variable AZURE_OPENAI_RESPONSES_DEPLOYMENT_NAME.
|
||||
api_key: The API key for the Azure deployment. This value can be
|
||||
found in the Keys & Endpoint section when examining your resource in
|
||||
the Azure portal. You can use either KEY1 or KEY2.
|
||||
(Env var AZURE_OPENAI_API_KEY)
|
||||
Can be set via environment variable AZURE_OPENAI_API_KEY.
|
||||
api_version: The API version to use. The default value is `default_api_version`.
|
||||
(Env var AZURE_OPENAI_API_VERSION)
|
||||
Can be set via environment variable AZURE_OPENAI_API_VERSION.
|
||||
base_url: The url of the Azure deployment. This value
|
||||
can be found in the Keys & Endpoint section when examining
|
||||
your resource from the Azure portal, the base_url consists of the endpoint,
|
||||
followed by /openai/deployments/{deployment_name}/,
|
||||
use endpoint if you only want to supply the endpoint.
|
||||
(Env var AZURE_OPENAI_BASE_URL)
|
||||
Can be set via environment variable AZURE_OPENAI_BASE_URL.
|
||||
token_endpoint: The token endpoint to use to retrieve the authentication token.
|
||||
The default value is `default_token_endpoint`.
|
||||
(Env var AZURE_OPENAI_TOKEN_ENDPOINT)
|
||||
Can be set via environment variable AZURE_OPENAI_TOKEN_ENDPOINT.
|
||||
default_api_version: The default API version to use if not specified.
|
||||
The default value is "2024-10-21".
|
||||
default_token_endpoint: The default token endpoint to use if not specified.
|
||||
The default value is "https://cognitiveservices.azure.com/.default".
|
||||
env_file_path: The path to the .env file to load settings from.
|
||||
env_file_encoding: The encoding of the .env file, defaults to 'utf-8'.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.azure import AzureOpenAISettings
|
||||
|
||||
# Using environment variables
|
||||
# Set AZURE_OPENAI_ENDPOINT=https://your-endpoint.openai.azure.com
|
||||
# Set AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=gpt-4
|
||||
# Set AZURE_OPENAI_API_KEY=your-key
|
||||
settings = AzureOpenAISettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = AzureOpenAISettings(
|
||||
endpoint="https://your-endpoint.openai.azure.com", chat_deployment_name="gpt-4", api_key="your-key"
|
||||
)
|
||||
|
||||
# Or loading from a .env file
|
||||
settings = AzureOpenAISettings(env_file_path="path/to/.env")
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = "AZURE_OPENAI_"
|
||||
|
||||
@@ -349,18 +349,33 @@ class ObservabilitySettings(AFBaseSettings):
|
||||
Warning:
|
||||
Sensitive events should only be enabled on test and development environments.
|
||||
|
||||
Args:
|
||||
Keyword Args:
|
||||
enable_otel: Enable OpenTelemetry diagnostics. Default is False.
|
||||
(Env var ENABLE_OTEL)
|
||||
Can be set via environment variable ENABLE_OTEL.
|
||||
enable_sensitive_data: Enable OpenTelemetry sensitive events. Default is False.
|
||||
(Env var ENABLE_SENSITIVE_DATA)
|
||||
Can be set via environment variable ENABLE_SENSITIVE_DATA.
|
||||
applicationinsights_connection_string: The Azure Monitor connection string. Default is None.
|
||||
(Env var APPLICATIONINSIGHTS_CONNECTION_STRING)
|
||||
otlp_endpoint: The OpenTelemetry Protocol (OTLP) endpoint. Default is None.
|
||||
(Env var OTLP_ENDPOINT)
|
||||
vs_code_extension_port: The port the AI Toolkit or AzureAI Foundry VS Code extensions are listening on.
|
||||
Default is None.
|
||||
(Env var VS_CODE_EXTENSION_PORT)
|
||||
Can be set via environment variable APPLICATIONINSIGHTS_CONNECTION_STRING.
|
||||
otlp_endpoint: The OpenTelemetry Protocol (OTLP) endpoint. Default is None.
|
||||
Can be set via environment variable OTLP_ENDPOINT.
|
||||
vs_code_extension_port: The port the AI Toolkit or Azure AI Foundry VS Code extensions are listening on.
|
||||
Default is None.
|
||||
Can be set via environment variable VS_CODE_EXTENSION_PORT.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework import ObservabilitySettings
|
||||
|
||||
# Using environment variables
|
||||
# Set ENABLE_OTEL=true
|
||||
# Set APPLICATIONINSIGHTS_CONNECTION_STRING=InstrumentationKey=...
|
||||
settings = ObservabilitySettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = ObservabilitySettings(
|
||||
enable_otel=True, applicationinsights_connection_string="InstrumentationKey=..."
|
||||
)
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = ""
|
||||
|
||||
@@ -60,6 +60,7 @@ class OpenAIAssistantsClient(OpenAIConfigMixin, BaseChatClient):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
model_id: str | None = None,
|
||||
assistant_id: str | None = None,
|
||||
assistant_name: str | None = None,
|
||||
@@ -75,27 +76,44 @@ class OpenAIAssistantsClient(OpenAIConfigMixin, BaseChatClient):
|
||||
) -> None:
|
||||
"""Initialize an OpenAI Assistants client.
|
||||
|
||||
Args:
|
||||
model_id: OpenAI model name, see
|
||||
https://platform.openai.com/docs/models
|
||||
Keyword Args:
|
||||
model_id: OpenAI model name, see https://platform.openai.com/docs/models.
|
||||
Can also be set via environment variable OPENAI_CHAT_MODEL_ID.
|
||||
assistant_id: The ID of an OpenAI assistant to use.
|
||||
If not provided, a new assistant will be created (and deleted after the request).
|
||||
assistant_name: The name to use when creating new assistants.
|
||||
thread_id: Default thread ID to use for conversations. Can be overridden by
|
||||
conversation_id property, when making a request.
|
||||
conversation_id property when making a request.
|
||||
If not provided, a new thread will be created (and deleted after the request).
|
||||
api_key: The optional API key to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
org_id: The optional org ID to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
base_url: The optional base URL to use. If provided will override,
|
||||
api_key: The API key to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_API_KEY.
|
||||
org_id: The org ID to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_ORG_ID.
|
||||
base_url: The base URL to use. If provided will override the standard value.
|
||||
Can also be set via environment variable OPENAI_BASE_URL.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
env_file_path: Use the environment settings file as a fallback
|
||||
to environment variables. (Optional)
|
||||
env_file_encoding: The encoding of the environment settings file. (Optional)
|
||||
to environment variables.
|
||||
env_file_encoding: The encoding of the environment settings file.
|
||||
kwargs: Other keyword parameters.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.openai import OpenAIAssistantsClient
|
||||
|
||||
# Using environment variables
|
||||
# Set OPENAI_API_KEY=sk-...
|
||||
# Set OPENAI_CHAT_MODEL_ID=gpt-4
|
||||
client = OpenAIAssistantsClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = OpenAIAssistantsClient(model_id="gpt-4", api_key="sk-...")
|
||||
|
||||
# Or loading from a .env file
|
||||
client = OpenAIAssistantsClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
openai_settings = OpenAISettings(
|
||||
|
||||
@@ -465,6 +465,7 @@ class OpenAIChatClient(OpenAIConfigMixin, OpenAIBaseChatClient):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
model_id: str | None = None,
|
||||
api_key: str | None = None,
|
||||
org_id: str | None = None,
|
||||
@@ -475,26 +476,42 @@ class OpenAIChatClient(OpenAIConfigMixin, OpenAIBaseChatClient):
|
||||
env_file_path: str | None = None,
|
||||
env_file_encoding: str | None = None,
|
||||
) -> None:
|
||||
"""Initialize an OpenAIChatCompletion service.
|
||||
"""Initialize an OpenAI Chat completion client.
|
||||
|
||||
Args:
|
||||
model_id: OpenAI model name, see
|
||||
https://platform.openai.com/docs/models
|
||||
api_key: The optional API key to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
org_id: The optional org ID to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
Keyword Args:
|
||||
model_id: OpenAI model name, see https://platform.openai.com/docs/models.
|
||||
Can also be set via environment variable OPENAI_CHAT_MODEL_ID.
|
||||
api_key: The API key to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_API_KEY.
|
||||
org_id: The org ID to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_ORG_ID.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
instruction_role: The role to use for 'instruction' messages, for example,
|
||||
"system" or "developer". If not provided, the default is "system".
|
||||
base_url: The optional base URL to use. If provided will override
|
||||
the standard value for a OpenAI connector,
|
||||
the env vars or .env file value.
|
||||
base_url: The base URL to use. If provided will override
|
||||
the standard value for an OpenAI connector, the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_BASE_URL.
|
||||
env_file_path: Use the environment settings file as a fallback
|
||||
to environment variables. (Optional)
|
||||
env_file_encoding: The encoding of the environment settings file. (Optional)
|
||||
to environment variables.
|
||||
env_file_encoding: The encoding of the environment settings file.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.openai import OpenAIChatClient
|
||||
|
||||
# Using environment variables
|
||||
# Set OPENAI_API_KEY=sk-...
|
||||
# Set OPENAI_CHAT_MODEL_ID=gpt-4
|
||||
client = OpenAIChatClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = OpenAIChatClient(model_id="gpt-4", api_key="sk-...")
|
||||
|
||||
# Or loading from a .env file
|
||||
client = OpenAIChatClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
openai_settings = OpenAISettings(
|
||||
|
||||
@@ -945,6 +945,7 @@ class OpenAIResponsesClient(OpenAIConfigMixin, OpenAIBaseResponsesClient):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
model_id: str | None = None,
|
||||
api_key: str | None = None,
|
||||
org_id: str | None = None,
|
||||
@@ -956,25 +957,42 @@ class OpenAIResponsesClient(OpenAIConfigMixin, OpenAIBaseResponsesClient):
|
||||
env_file_encoding: str | None = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
"""Initialize an OpenAIChatCompletion service.
|
||||
"""Initialize an OpenAI Responses client.
|
||||
|
||||
Args:
|
||||
model_id: OpenAI model name, see
|
||||
https://platform.openai.com/docs/models
|
||||
api_key: The optional API key to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
org_id: The optional org ID to use. If provided will override,
|
||||
the env vars or .env file value.
|
||||
base_url: The optional base URL to use. If provided will override,
|
||||
Keyword Args:
|
||||
model_id: OpenAI model name, see https://platform.openai.com/docs/models.
|
||||
Can also be set via environment variable OPENAI_RESPONSES_MODEL_ID.
|
||||
api_key: The API key to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_API_KEY.
|
||||
org_id: The org ID to use. If provided will override the env vars or .env file value.
|
||||
Can also be set via environment variable OPENAI_ORG_ID.
|
||||
base_url: The base URL to use. If provided will override the standard value.
|
||||
Can also be set via environment variable OPENAI_BASE_URL.
|
||||
default_headers: The default headers mapping of string keys to
|
||||
string values for HTTP requests. (Optional)
|
||||
async_client: An existing client to use. (Optional)
|
||||
string values for HTTP requests.
|
||||
async_client: An existing client to use.
|
||||
instruction_role: The role to use for 'instruction' messages, for example,
|
||||
"system" or "developer". If not provided, the default is "system".
|
||||
env_file_path: Use the environment settings file as a fallback
|
||||
to environment variables. (Optional)
|
||||
env_file_encoding: The encoding of the environment settings file. (Optional)
|
||||
to environment variables.
|
||||
env_file_encoding: The encoding of the environment settings file.
|
||||
kwargs: Other keyword parameters.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.openai import OpenAIResponsesClient
|
||||
|
||||
# Using environment variables
|
||||
# Set OPENAI_API_KEY=sk-...
|
||||
# Set OPENAI_RESPONSES_MODEL_ID=gpt-4o
|
||||
client = OpenAIResponsesClient()
|
||||
|
||||
# Or passing parameters directly
|
||||
client = OpenAIResponsesClient(model_id="gpt-4o", api_key="sk-...")
|
||||
|
||||
# Or loading from a .env file
|
||||
client = OpenAIResponsesClient(env_file_path="path/to/.env")
|
||||
"""
|
||||
try:
|
||||
openai_settings = OpenAISettings(
|
||||
|
||||
@@ -57,19 +57,35 @@ class OpenAISettings(AFBaseSettings):
|
||||
encoding 'utf-8'. If the settings are not found in the .env file, the settings are ignored;
|
||||
however, validation will fail alerting that the settings are missing.
|
||||
|
||||
Args:
|
||||
api_key: OpenAI API key, see https://platform.openai.com/account/api-keys
|
||||
(Env var OPENAI_API_KEY)
|
||||
Keyword Args:
|
||||
api_key: OpenAI API key, see https://platform.openai.com/account/api-keys.
|
||||
Can be set via environment variable OPENAI_API_KEY.
|
||||
base_url: The base URL for the OpenAI API.
|
||||
(Env var OPENAI_BASE_URL)
|
||||
Can be set via environment variable OPENAI_BASE_URL.
|
||||
org_id: This is usually optional unless your account belongs to multiple organizations.
|
||||
(Env var OPENAI_ORG_ID)
|
||||
Can be set via environment variable OPENAI_ORG_ID.
|
||||
chat_model_id: The OpenAI chat model ID to use, for example, gpt-3.5-turbo or gpt-4.
|
||||
(Env var OPENAI_CHAT_MODEL_ID)
|
||||
Can be set via environment variable OPENAI_CHAT_MODEL_ID.
|
||||
responses_model_id: The OpenAI responses model ID to use, for example, gpt-4o or o1.
|
||||
(Env var OPENAI_RESPONSES_MODEL_ID)
|
||||
Can be set via environment variable OPENAI_RESPONSES_MODEL_ID.
|
||||
env_file_path: The path to the .env file to load settings from.
|
||||
env_file_encoding: The encoding of the .env file, defaults to 'utf-8'.
|
||||
|
||||
Examples:
|
||||
.. code-block:: python
|
||||
|
||||
from agent_framework.openai import OpenAISettings
|
||||
|
||||
# Using environment variables
|
||||
# Set OPENAI_API_KEY=sk-...
|
||||
# Set OPENAI_CHAT_MODEL_ID=gpt-4
|
||||
settings = OpenAISettings()
|
||||
|
||||
# Or passing parameters directly
|
||||
settings = OpenAISettings(api_key="sk-...", chat_model_id="gpt-4")
|
||||
|
||||
# Or loading from a .env file
|
||||
settings = OpenAISettings(env_file_path="path/to/.env")
|
||||
"""
|
||||
|
||||
env_prefix: ClassVar[str] = "OPENAI_"
|
||||
|
||||
Reference in New Issue
Block a user