semantic-kernel
Integrate cutting-edge LLM technology quickly and easily into your apps
Top Related Projects
Examples and guides for using the OpenAI API
🦜🔗 Build context-aware reasoning applications
Build high-quality LLM apps - from prototyping, testing to production deployment and monitoring.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
AI orchestration framework to build customizable, production-ready LLM applications. Connect components (models, vector DBs, file converters) to pipelines or agents that can interact with your data. With advanced retrieval methods, it's best suited for building RAG, question answering, semantic search or conversational agent chatbots.
Quick Overview
Semantic Kernel is an open-source SDK developed by Microsoft that integrates Large Language Models (LLMs) into applications. It provides a lightweight framework for orchestrating AI plugins, combining semantic and native functions, and enabling developers to create AI-powered experiences.
Pros
- Seamless integration of LLMs into applications
- Supports multiple AI services and models (e.g., OpenAI, Azure OpenAI)
- Extensible plugin architecture for custom AI capabilities
- Cross-platform compatibility (C#, Python, Java)
Cons
- Relatively new project, still in active development
- Limited documentation and examples compared to more established frameworks
- Potential learning curve for developers new to AI integration
- Dependency on external AI services may introduce latency or cost concerns
Code Examples
- Creating a kernel and running a semantic function:
using Microsoft.SemanticKernel;
var kernel = Kernel.Builder.Build();
kernel.Config.AddOpenAITextCompletionService("text-davinci-003", "YOUR_API_KEY");
var result = await kernel.RunAsync("What's the capital of France?");
Console.WriteLine(result);
- Using a pre-defined skill:
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Skills.Core;
var kernel = Kernel.Builder.Build();
kernel.Config.AddOpenAITextCompletionService("text-davinci-003", "YOUR_API_KEY");
var timeSkill = kernel.ImportSkill(new TimeSkill());
var result = await kernel.RunAsync("What time is it?", timeSkill["Now"]);
Console.WriteLine(result);
- Creating a custom semantic function:
using Microsoft.SemanticKernel;
var kernel = Kernel.Builder.Build();
kernel.Config.AddOpenAITextCompletionService("text-davinci-003", "YOUR_API_KEY");
string skPrompt = @"
Generate a short poem about {{$input}}.
Be creative and use metaphors.
";
var poetryFunction = kernel.CreateSemanticFunction(skPrompt);
var result = await kernel.RunAsync("artificial intelligence", poetryFunction);
Console.WriteLine(result);
Getting Started
-
Install the NuGet package:
dotnet add package Microsoft.SemanticKernel
-
Create a new kernel and configure an AI service:
using Microsoft.SemanticKernel; var kernel = Kernel.Builder.Build(); kernel.Config.AddOpenAITextCompletionService("text-davinci-003", "YOUR_API_KEY");
-
Run a semantic function:
var result = await kernel.RunAsync("Tell me a joke about programming."); Console.WriteLine(result);
Competitor Comparisons
Examples and guides for using the OpenAI API
Pros of openai-cookbook
- Extensive collection of practical examples and tutorials for using OpenAI's APIs
- Covers a wide range of use cases and applications, from basic to advanced
- Regularly updated with new examples and best practices
Cons of openai-cookbook
- Focused solely on OpenAI's offerings, limiting its scope compared to Semantic Kernel
- Less emphasis on integrating AI capabilities into larger applications or frameworks
- Lacks the structured approach to building AI-powered applications that Semantic Kernel provides
Code Comparison
openai-cookbook:
import openai
response = openai.Completion.create(
engine="text-davinci-002",
prompt="Translate the following English text to French: '{}'",
max_tokens=60
)
Semantic Kernel:
var kernel = Kernel.Builder.Build();
kernel.Config.AddOpenAITextCompletionService("davinci", "your-api-key");
var translator = kernel.CreateSemanticFunction("Translate the following English text to French: {{$input}}");
var result = await translator.InvokeAsync("Hello, world!");
🦜🔗 Build context-aware reasoning applications
Pros of LangChain
- More extensive documentation and examples
- Larger community and ecosystem of integrations
- Supports multiple programming languages (Python, JavaScript)
Cons of LangChain
- Steeper learning curve due to more complex architecture
- Less focus on enterprise-grade features and security
Code Comparison
LangChain:
from langchain import OpenAI, LLMChain, PromptTemplate
llm = OpenAI(temperature=0.9)
prompt = PromptTemplate(input_variables=["product"], template="What is a good name for a company that makes {product}?")
chain = LLMChain(llm=llm, prompt=prompt)
print(chain.run("colorful socks"))
Semantic Kernel:
using Microsoft.SemanticKernel;
var kernel = Kernel.Builder.Build();
kernel.Config.AddOpenAITextCompletionService("davinci", "YOUR_API_KEY");
var prompt = "What is a good name for a company that makes {{$input}}?";
var result = await kernel.RunAsync(prompt, new KernelArguments { ["input"] = "colorful socks" });
Console.WriteLine(result);
Both repositories aim to simplify working with large language models, but they have different approaches. LangChain offers more flexibility and a wider range of integrations, while Semantic Kernel focuses on providing a more structured, enterprise-ready framework. The choice between them depends on specific project requirements and developer preferences.
Build high-quality LLM apps - from prototyping, testing to production deployment and monitoring.
Pros of Promptflow
- More focused on workflow management and orchestration for AI tasks
- Provides a visual interface for designing and managing prompt flows
- Better suited for non-technical users and rapid prototyping
Cons of Promptflow
- Less flexible for complex programming tasks
- More limited in terms of language support and integration options
- Newer project with a smaller community and fewer resources
Code Comparison
Semantic Kernel:
var kernel = Kernel.Builder.Build();
var result = await kernel.RunAsync("What is the capital of France?");
Console.WriteLine(result);
Promptflow:
from promptflow import PFClient
client = PFClient()
flow = client.flows.load("my_flow")
result = client.test(flow=flow, inputs={"question": "What is the capital of France?"})
print(result)
Summary
Semantic Kernel is a more comprehensive SDK for AI integration, offering greater flexibility and programming capabilities. Promptflow, on the other hand, excels in visual workflow design and is more accessible to non-developers. The choice between the two depends on the specific needs of the project and the technical expertise of the team.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
Pros of Transformers
- Extensive model support: Offers a wide range of pre-trained models and architectures
- Active community: Large user base and frequent updates
- Comprehensive documentation: Detailed guides and examples for various use cases
Cons of Transformers
- Steeper learning curve: Requires more in-depth knowledge of NLP concepts
- Higher resource requirements: Models can be computationally intensive
- Less focus on integration: Primarily designed for research and model development
Code Comparison
Transformers:
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
result = classifier("I love this product!")[0]
print(f"Label: {result['label']}, Score: {result['score']:.4f}")
Semantic Kernel:
using Microsoft.SemanticKernel;
var kernel = Kernel.Builder.Build();
var sentiment = kernel.ImportSkill("SentimentAnalysisSkill");
var result = await kernel.RunAsync("I love this product!", sentiment["Analyze"]);
Console.WriteLine($"Sentiment: {result}");
Summary
Transformers is a powerful library for NLP tasks with a vast array of models, while Semantic Kernel focuses on integrating AI capabilities into applications. Transformers offers more flexibility for research and custom model development, whereas Semantic Kernel provides a more streamlined approach for incorporating AI into existing software systems.
AI orchestration framework to build customizable, production-ready LLM applications. Connect components (models, vector DBs, file converters) to pipelines or agents that can interact with your data. With advanced retrieval methods, it's best suited for building RAG, question answering, semantic search or conversational agent chatbots.
Pros of Haystack
- More focused on question answering and information retrieval tasks
- Offers a wider range of pre-built components for NLP pipelines
- Provides better support for document-level processing and indexing
Cons of Haystack
- Less integrated with other AI services and platforms
- May have a steeper learning curve for beginners
- Limited support for general-purpose AI development compared to Semantic Kernel
Code Comparison
Haystack example:
from haystack import Pipeline
from haystack.nodes import TfidfRetriever, FARMReader
pipeline = Pipeline()
pipeline.add_node(component=TfidfRetriever(document_store=document_store), name="Retriever", inputs=["Query"])
pipeline.add_node(component=FARMReader(model_name_or_path="deepset/roberta-base-squad2"), name="Reader", inputs=["Retriever"])
Semantic Kernel example:
var kernel = Kernel.Builder.Build();
kernel.ImportSkill(new TextSkill());
kernel.ImportSemanticSkillFromDirectory("skills", "RecommendationSkill");
var result = await kernel.RunAsync("What's a good movie to watch?", recommendationSkill["GetRecommendation"]);
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
Semantic Kernel
Build intelligent AI agents and multi-agent systems with this enterprise-ready orchestration framework
What is Semantic Kernel?
Semantic Kernel is a model-agnostic SDK that empowers developers to build, orchestrate, and deploy AI agents and multi-agent systems. Whether you're building a simple chatbot or a complex multi-agent workflow, Semantic Kernel provides the tools you need with enterprise-grade reliability and flexibility.
System Requirements
- Python: 3.10+
- .NET: .NET 8.0+
- Java: JDK 17+
- OS Support: Windows, macOS, Linux
Key Features
- Model Flexibility: Connect to any LLM with built-in support for OpenAI, Azure OpenAI, Hugging Face, NVidia and more
- Agent Framework: Build modular AI agents with access to tools/plugins, memory, and planning capabilities
- Multi-Agent Systems: Orchestrate complex workflows with collaborating specialist agents
- Plugin Ecosystem: Extend with native code functions, prompt templates, OpenAPI specs, or Model Context Protocol (MCP)
- Vector DB Support: Seamless integration with Azure AI Search, Elasticsearch, Chroma, and more
- Multimodal Support: Process text, vision, and audio inputs
- Local Deployment: Run with Ollama, LMStudio, or ONNX
- Process Framework: Model complex business processes with a structured workflow approach
- Enterprise Ready: Built for observability, security, and stable APIs
Installation
First, set the environment variable for your AI Services:
Azure OpenAI:
export AZURE_OPENAI_API_KEY=AAA....
or OpenAI directly:
export OPENAI_API_KEY=sk-...
Python
pip install semantic-kernel
.NET
dotnet add package Microsoft.SemanticKernel
dotnet add package Microsoft.SemanticKernel.Agents.core
Java
See semantic-kernel-java build for instructions.
Quickstart
Basic Agent - Python
Create a simple assistant that responds to user prompts:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
async def main():
# Initialize a chat agent with basic instructions
agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="SK-Assistant",
instructions="You are a helpful assistant.",
)
# Get a response to a user message
response = await agent.get_response(messages="Write a haiku about Semantic Kernel.")
print(response.content)
asyncio.run(main())
# Output:
# Language's essence,
# Semantic threads intertwine,
# Meaning's core revealed.
Basic Agent - .NET
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
);
var kernel = builder.Build();
ChatCompletionAgent agent =
new()
{
Name = "SK-Agent",
Instructions = "You are a helpful assistant.",
Kernel = kernel,
};
await foreach (AgentResponseItem<ChatMessageContent> response
in agent.InvokeAsync("Write a haiku about Semantic Kernel."))
{
Console.WriteLine(response.Message);
}
// Output:
// Language's essence,
// Semantic threads intertwine,
// Meaning's core revealed.
Agent with Plugins - Python
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):
price: float
name: str
async def main():
# Configure structured output 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(messages="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())
Agent with Plugin - .NET
using System.ComponentModel;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Agents;
using Microsoft.SemanticKernel.ChatCompletion;
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(
Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"),
Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
);
var kernel = builder.Build();
kernel.Plugins.Add(KernelPluginFactory.CreateFromType<MenuPlugin>());
ChatCompletionAgent agent =
new()
{
Name = "SK-Assistant",
Instructions = "You are a helpful assistant.",
Kernel = kernel,
Arguments = new KernelArguments(new PromptExecutionSettings() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() })
};
await foreach (AgentResponseItem<ChatMessageContent> response
in agent.InvokeAsync("What is the price of the soup special?"))
{
Console.WriteLine(response.Message);
}
sealed class MenuPlugin
{
[KernelFunction, Description("Provides a list of specials from the menu.")]
public string GetSpecials() =>
"""
Special Soup: Clam Chowder
Special Salad: Cobb Salad
Special Drink: Chai Tea
""";
[KernelFunction, Description("Provides the price of the requested menu item.")]
public string GetItemPrice(
[Description("The name of the menu item.")]
string menuItem) =>
"$9.99";
}
Multi-Agent System - Python
Build a system of specialized agents that can collaborate:
import asyncio
from semantic_kernel.agents import ChatCompletionAgent, ChatHistoryAgentThread
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
billing_agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="BillingAgent",
instructions="You handle billing issues like charges, payment methods, cycles, fees, discrepancies, and payment failures."
)
refund_agent = ChatCompletionAgent(
service=AzureChatCompletion(),
name="RefundAgent",
instructions="Assist users with refund inquiries, including eligibility, policies, processing, and status updates.",
)
triage_agent = ChatCompletionAgent(
service=OpenAIChatCompletion(),
name="TriageAgent",
instructions="Evaluate user requests and forward them to BillingAgent or RefundAgent for targeted assistance."
" Provide the full answer to the user containing any information from the agents",
plugins=[billing_agent, refund_agent],
)
thread: ChatHistoryAgentThread = None
async def main() -> None:
print("Welcome to the chat bot!\n Type 'exit' to exit.\n Try to get some billing or refund help.")
while True:
user_input = input("User:> ")
if user_input.lower().strip() == "exit":
print("\n\nExiting chat...")
return False
response = await triage_agent.get_response(
messages=user_input,
thread=thread,
)
if response:
print(f"Agent :> {response}")
# Agent :> I understand that you were charged twice for your subscription last month, and I'm here to assist you with resolving this issue. Hereâs what we need to do next:
# 1. **Billing Inquiry**:
# - Please provide the email address or account number associated with your subscription, the date(s) of the charges, and the amount charged. This will allow the billing team to investigate the discrepancy in the charges.
# 2. **Refund Process**:
# - For the refund, please confirm your subscription type and the email address associated with your account.
# - Provide the dates and transaction IDs for the charges you believe were duplicated.
# Once we have these details, we will be able to:
# - Check your billing history for any discrepancies.
# - Confirm any duplicate charges.
# - Initiate a refund for the duplicate payment if it qualifies. The refund process usually takes 5-10 business days after approval.
# Please provide the necessary details so we can proceed with resolving this issue for you.
if __name__ == "__main__":
asyncio.run(main())
Where to Go Next
- ð Try our Getting Started Guide or learn about Building Agents
- ð Explore over 100 Detailed Samples
- ð¡ Learn about core Semantic Kernel Concepts
API References
Troubleshooting
Common Issues
- Authentication Errors: Check that your API key environment variables are correctly set
- Model Availability: Verify your Azure OpenAI deployment or OpenAI model access
Getting Help
- Check our GitHub issues for known problems
- Search the Discord community for solutions
- Include your SDK version and full error messages when asking for help
Join the community
We welcome your contributions and suggestions to the SK community! One of the easiest ways to participate is to engage in discussions in the GitHub repository. Bug reports and fixes are welcome!
For new features, components, or extensions, please open an issue and discuss with us before sending a PR. This is to avoid rejection as we might be taking the core in a different direction, but also to consider the impact on the larger ecosystem.
To learn more and get started:
-
Read the documentation
-
Learn how to contribute to the project
-
Ask questions in the GitHub discussions
-
Ask questions in the Discord community
-
Follow the team on our blog
Contributor Wall of Fame
Code of Conduct
This project has adopted the Microsoft Open Source Code of Conduct. For more information, see the Code of Conduct FAQ or contact opencode@microsoft.com with any additional questions or comments.
License
Copyright (c) Microsoft Corporation. All rights reserved.
Licensed under the MIT license.
Top Related Projects
Examples and guides for using the OpenAI API
🦜🔗 Build context-aware reasoning applications
Build high-quality LLM apps - from prototyping, testing to production deployment and monitoring.
🤗 Transformers: the model-definition framework for state-of-the-art machine learning models in text, vision, audio, and multimodal models, for both inference and training.
AI orchestration framework to build customizable, production-ready LLM applications. Connect components (models, vector DBs, file converters) to pipelines or agents that can interact with your data. With advanced retrieval methods, it's best suited for building RAG, question answering, semantic search or conversational agent chatbots.
Convert
designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot