Files
semantic-kernel/python
13f812b825 Python: Update pymongo requirement from <4.16,>=4.8.0 to >=4.8.0,<4.17 in /python (#13866)
Updates the requirements on
[pymongo](https://github.com/mongodb/mongo-python-driver) to permit the
latest version.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a
href="https://github.com/mongodb/mongo-python-driver/releases">pymongo's
releases</a>.</em></p>
<blockquote>
<h2>PyMongo 4.16.0</h2>
<p>Community notes: <!-- raw HTML omitted --></p>
</blockquote>
</details>
<details>
<summary>Changelog</summary>
<p><em>Sourced from <a
href="https://github.com/mongodb/mongo-python-driver/blob/master/doc/changelog.rst">pymongo's
changelog</a>.</em></p>
<blockquote>
<h2>Changes in Version 4.16.0 (2026/01/07)</h2>
<p>PyMongo 4.16 brings a number of changes including:</p>
<ul>
<li>Removed invalid documents from
:class:<code>bson.errors.InvalidDocument</code> error messages as
doing so may leak sensitive user data.
Instead, invalid documents are stored in
:attr:<code>bson.errors.InvalidDocument.document</code>.</li>
<li>PyMongo now requires <code>dnspython&gt;=2.6.1</code>, since
<code>dnspython</code> 1.0 is no longer maintained.
The minimum version is <code>2.6.1</code> to account for
<code>CVE-2023-29483
&lt;https://www.cve.org/CVERecord?id=CVE-2023-29483&gt;</code>_.</li>
<li>Removed support for Eventlet.
Eventlet is actively being sunset by its maintainers and has
compatibility issues with PyMongo's dnspython dependency.</li>
<li>Use Zstandard support from the standard library for Python 3.14+,
and use <code>backports.zstd</code> for older versions.</li>
<li>Fixed return type annotation for <code>find_one_and_*</code> methods
on :class:<code>~pymongo.asynchronous.collection.AsyncCollection</code>
and :class:<code>~pymongo.synchronous.collection.Collection</code> to
include <code>None</code>.</li>
<li>Added support for NumPy 1D-arrays in
:class:<code>bson.binary.BinaryVector</code>.</li>
<li>Prevented :class:<code>~pymongo.encryption.ClientEncryption</code>
from loading the crypt
shared library to fix &quot;MongoCryptError: An existing crypt_shared
library is
loaded by the application&quot; unless the linked library search path is
set.</li>
</ul>
<h2>Changes in Version 4.15.5 (2025/12/02)</h2>
<p>Version 4.15.5 is a bug fix release.</p>
<ul>
<li>Fixed a bug that could cause <code>AutoReconnect(&quot;connection
pool paused&quot;)</code> errors when cursors fetched more documents
from the database after SDAM heartbeat failures.</li>
</ul>
<h2>Changes in Version 4.15.4 (2025/10/21)</h2>
<p>Version 4.15.4 is a bug fix release.</p>
<ul>
<li>Relaxed the callback type of
:meth:<code>~pymongo.asynchronous.client_session.AsyncClientSession.with_transaction</code>
to allow the broader Awaitable type rather than only Coroutine
objects.</li>
<li>Added the missing Python 3.14 trove classifier to the package
metadata.</li>
</ul>
<p>Issues Resolved
...............</p>
<p>See the <code>PyMongo 4.15.4 release notes in JIRA</code>_ for the
list of resolved issues
in this release.</p>
<p>.. _PyMongo 4.15.4 release notes in JIRA: <a
href="https://jira.mongodb.org/secure/ReleaseNote.jspa?projectId=10004&amp;version=47237">https://jira.mongodb.org/secure/ReleaseNote.jspa?projectId=10004&amp;version=47237</a></p>
<h2>Changes in Version 4.15.3 (2025/10/07)</h2>
<p>Version 4.15.3 is a bug fix release.</p>
<ul>
<li>Fixed a memory leak when raising
:class:<code>bson.errors.InvalidDocument</code> with C extensions.</li>
<li>Fixed the return type of the
:meth:<code>~pymongo.asynchronous.collection.AsyncCollection.distinct</code>,</li>
</ul>
<!-- raw HTML omitted -->
</blockquote>
<p>... (truncated)</p>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/32901018ca14d9acb05004a88d65b6ab0b29c877"><code>3290101</code></a>
Prepare 4.16.0 release (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2672">#2672</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/1be94d262dd0281b032b6f9e56d381cac3a7a6d9"><code>1be94d2</code></a>
PYTHON-5685 Fix unified spec sync metadata for csot and sessions tests
(<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2669">#2669</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/6585d9cb51d5c9b2d85eec4f49b8196612d9e8ee"><code>6585d9c</code></a>
PYTHON-2442: Refactor: use _asdict() in _options_dict() (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2670">#2670</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/fdb1f7ea4abe128ae4e59e3d063fd95d7daaa964"><code>fdb1f7e</code></a>
PYTHON-5677 Prevent ClientEncryption from loading crypt shared library
(<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2659">#2659</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/0cd9763423b85cd37779ea934bf7b1f8be8bbf8e"><code>0cd9763</code></a>
Bump zizmorcore/zizmor-action from
cb3d8e846e148d1111d90b03375b9c03deceda37 t...</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/2f263d4d3f11eb4a2b32ace467fd2767c371f4d7"><code>2f263d4</code></a>
PYTHON-5680 Fix handling of expectedDocuments in Unified Test Runner (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2665">#2665</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/e9658b2406232b6bd6ac1d961b368142f8819479"><code>e9658b2</code></a>
Add 4.15.5 release date to changelog (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2666">#2666</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/10dd20405ba19c643a1b305ff84f742b19c40daf"><code>10dd204</code></a>
Update coverage[toml] requirement from &lt;=7.10.6,&gt;=5 to
&gt;=5,&lt;=7.10.7 (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2662">#2662</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/130067799cc671d4dcc2f34dafff73c4ef5ddeaf"><code>1300677</code></a>
[Spec Resync] 12-22-2025 (<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2663">#2663</a>)</li>
<li><a
href="https://github.com/mongodb/mongo-python-driver/commit/18c1f142b5b3fd179a677b2736332dc17770b7c2"><code>18c1f14</code></a>
PYTHON-5529 Introduce optin setting to await for MinPoolSize population
(<a
href="https://redirect.github.com/mongodb/mongo-python-driver/issues/2664">#2664</a>)</li>
<li>Additional commits viewable in <a
href="https://github.com/mongodb/mongo-python-driver/compare/4.8.0...4.16.0">compare
view</a></li>
</ul>
</details>
<br />


You can trigger a rebase of this PR by commenting `@dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `@dependabot rebase` will rebase this PR
- `@dependabot recreate` will recreate this PR, overwriting any edits
that have been made to it
- `@dependabot show <dependency name> ignore conditions` will show all
of the ignore conditions of the specified dependency
- `@dependabot ignore this major version` will close this PR and stop
Dependabot creating any more for this major version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this minor version` will close this PR and stop
Dependabot creating any more for this minor version (unless you reopen
the PR or upgrade to it yourself)
- `@dependabot ignore this dependency` will close this PR and stop
Dependabot creating any more for this dependency (unless you reopen the
PR or upgrade to it yourself)


</details>

> **Note**
> Automatic rebases have been disabled on this pull request as it has
been open for over 30 days.

---------

Signed-off-by: dependabot[bot] <[email protected]>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: moonbox3 <[email protected]>
2026-06-17 11:20:12 +00:00
..
2023-04-13 16:12:36 -07:00
2024-08-27 16:45:09 +00:00

Get Started with Semantic Kernel Python

Important

Semantic Kernel is now Microsoft Agent Framework! Microsoft Agent Framework (MAF) is the enterprise‑ready successor to Semantic Kernel. Microsoft Agent Framework is now available at version 1.0 as a production-ready release: stable APIs, and a commitment to long-term support. Whether you're building a single assistant or orchestrating a fleet of specialized agents, Microsoft Agent Framework 1.0 gives you enterprise-grade multi-agent orchestration, multi-provider model support, and cross-runtime interoperability via A2A and MCP.

Learn more about Semantic Kernel and Agent Framework here: Semantic Kernel and Microsoft Agent Framework on the Agent Framework blog, and try out the Semantic Kernel migration guide.

Highlights

  • Flexible Agent Framework: build, orchestrate, and deploy AI agents and multi-agent systems
  • Multi-Agent Systems: Model workflows and collaboration between AI specialists
  • Plugin Ecosystem: Extend with Python, OpenAPI, Model Context Protocol (MCP), and more
  • LLM Support: OpenAI, Azure OpenAI, Hugging Face, Mistral, Google AI, ONNX, Ollama, NVIDIA NIM, and others
  • Vector DB Support: Azure AI Search, Elasticsearch, Chroma, and more
  • Process Framework: Build structured business processes with workflow modeling
  • Multimodal: Text, vision, audio

Quick Install

pip install --upgrade semantic-kernel
# Optional: Add integrations
pip install --upgrade semantic-kernel[hugging_face]
pip install --upgrade semantic-kernel[all]

Supported Platforms:

  • Python: 3.10+
  • OS: Windows, macOS, Linux

1. Setup API Keys

Set as environment variables, or create a .env file at your project root:

OPENAI_API_KEY=sk-...
OPENAI_CHAT_MODEL_ID=...
...
AZURE_OPENAI_API_KEY=...
AZURE_OPENAI_ENDPOINT=...
AZURE_OPENAI_CHAT_DEPLOYMENT_NAME=...
...

You can also override environment variables by explicitly passing configuration parameters to the AI service constructor:

chat_service = AzureChatCompletion(
    api_key=...,
    endpoint=...,
    deployment_name=...,
    api_version=...,
)

See the following setup guide for more information.

2. Use the Kernel for Prompt Engineering

Create prompt functions and invoke them via the Kernel:

import asyncio
from semantic_kernel import Kernel
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
from semantic_kernel.functions import KernelArguments

kernel = Kernel()
kernel.add_service(OpenAIChatCompletion())

prompt = """
1) A robot may not injure a human being...
2) A robot must obey orders given it by human beings...
3) A robot must protect its own existence...

Give me the TLDR in exactly {{$num_words}} words."""


async def main():
    result = await kernel.invoke_prompt(prompt, arguments=KernelArguments(num_words=5))
    print(result)


asyncio.run(main())
# Output: Protect humans, obey, self-preserve, prioritized.

3. Directly Use AI Services (No Kernel Required)

You can use the AI service classes directly for advanced workflows:

import asyncio
import asyncio

from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.contents import ChatHistory


async def main():
    service = OpenAIChatCompletion()
    settings = OpenAIChatPromptExecutionSettings()

    chat_history = ChatHistory(system_message="You are a helpful assistant.")
    chat_history.add_user_message("Write a haiku about Semantic Kernel.")
    response = await service.get_chat_message_content(chat_history=chat_history, settings=settings)
    print(response.content)

    """
    Output:

    Thoughts weave through context,  
    Semantic threads interlace—  
    Kernel sparks meaning.
    """


asyncio.run(main())

4. Build an Agent with Plugins and Tools

Add Python functions as plugins or Pydantic models as structured outputs;

Enhance your agent with custom tools (plugins) and structured output:

import asyncio
from typing import Annotated
from pydantic import BaseModel
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatPromptExecutionSettings
from semantic_kernel.functions import kernel_function, KernelArguments


class MenuPlugin:
    @kernel_function(description="Provides a list of specials from the menu.")
    def get_specials(self) -> Annotated[str, "Returns the specials from the menu."]:
        return """
        Special Soup: Clam Chowder
        Special Salad: Cobb Salad
        Special Drink: Chai Tea
        """

    @kernel_function(description="Provides the price of the requested menu item.")
    def get_item_price(
        self, menu_item: Annotated[str, "The name of the menu item."]
    ) -> Annotated[str, "Returns the price of the menu item."]:
        return "$9.99"


class MenuItem(BaseModel):
    # Used for structured outputs
    price: float
    name: str


async def main():
    # Configure structured outputs format
    settings = OpenAIChatPromptExecutionSettings()
    settings.response_format = MenuItem

    # Create agent with plugin and settings
    agent = ChatCompletionAgent(
        service=AzureChatCompletion(),
        name="SK-Assistant",
        instructions="You are a helpful assistant.",
        plugins=[MenuPlugin()],
        arguments=KernelArguments(settings),
    )

    response = await agent.get_response("What is the price of the soup special?")
    print(response.content)

    # Output:
    # The price of the Clam Chowder, which is the soup special, is $9.99.


asyncio.run(main())

You can explore additional getting started agent samples here.

5. Multi-Agent Orchestration

Coordinate a group of agents to iteratively solve a problem or refine content together:

import asyncio
from semantic_kernel.agents import ChatCompletionAgent, GroupChatOrchestration, RoundRobinGroupChatManager
from semantic_kernel.agents.runtime import InProcessRuntime
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion


def get_agents():
    return [
        ChatCompletionAgent(
            name="Writer",
            instructions="You are a creative content writer. Generate and refine slogans based on feedback.",
            service=AzureChatCompletion(),
        ),
        ChatCompletionAgent(
            name="Reviewer",
            instructions="You are a critical reviewer. Provide detailed feedback on proposed slogans.",
            service=AzureChatCompletion(),
        ),
    ]


async def main():
    agents = get_agents()
    group_chat = GroupChatOrchestration(
        members=agents,
        manager=RoundRobinGroupChatManager(max_rounds=5),
    )
    runtime = InProcessRuntime()
    runtime.start()
    result = await group_chat.invoke(
        task="Create a slogan for a new electric SUV that is affordable and fun to drive.",
        runtime=runtime,
    )
    value = await result.get()
    print(f"Final Slogan: {value}")

    # Example Output:
    # Final Slogan: "Feel the Charge: Adventure Meets Affordability in Your New Electric SUV!"

    await runtime.stop_when_idle()


if __name__ == "__main__":
    asyncio.run(main())

For orchestration-focused examples, see these orchestration samples.

More Examples & Notebooks

Semantic Kernel Documentation