Skip to content

Commit

Permalink
Convert example code from Python to C# and Semantic Kernel
Browse files Browse the repository at this point in the history
  • Loading branch information
softchris authored Feb 17, 2025
1 parent ca99c76 commit 609536e
Showing 1 changed file with 57 additions and 40 deletions.
97 changes: 57 additions & 40 deletions 02-explore-agentic-frameworks/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,50 +62,67 @@ Frameworks like LangChain and Microsoft Semantic Kernel offer pre-built componen

**Example code**. Let's look at an example of how you can use a pre-built parser to extract information from user input:

```python
import os
from langchain.output_parsers import PydanticOutputParser
from langchain.prompts import PromptTemplate
from langchain_openai import AzureChatOpenAI
from pydantic import BaseModel, Field
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Define a Pydantic model for structured data
class FlightBooking(BaseModel):
origin: str = Field(description="Departure city")
destination: str = Field(description="Arrival city")
date: str = Field(description="Flight date")

# Initialize parser
parser = PydanticOutputParser(pydantic_object=FlightBooking)

# Define the prompt template
prompt = PromptTemplate(
template="Extract structured flight details from the following text:\n{text}\n{format_instructions}",
input_variables=["text"],
partial_variables={"format_instructions": parser.get_format_instructions()},
)
```csharp

# Initialize Azure OpenAI LLM
llm = AzureChatOpenAI(
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
openai_api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
deployment_name=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
openai_api_key=os.getenv("AZURE_OPENAI_API_KEY"),
temperature=0
)
// Semantic Kernel example
ChatHistory chatHistory = [];
chatHistory.AddUserMessage("I'd like to go To New York");

// Define a plugin that contains the function to book travel
public class BookTravelPlugin(
IPizzaService pizzaService,
IUserContext userContext,
IPaymentService paymentService)
{

[KernelFunction("book_flight")]
[Description("Book travel given location and date")]
public async Task<Booking> BookFlight(
DateTime date,
string location,
)
{
// book travel given date,location
}
}

IKernelBuilder kernelBuilder = new KernelBuilder();
kernelBuilder..AddAzureOpenAIChatCompletion(
deploymentName: "NAME_OF_YOUR_DEPLOYMENT",
apiKey: "YOUR_API_KEY",
endpoint: "YOUR_AZURE_ENDPOINT"
);
kernelBuilder.Plugins.AddFromType<BookTravelPlugin>("BookTravel");
Kernel kernel = kernelBuilder.Build();

/*
Behind the scenes, i.e recognizes the tool to call, what arguments it already has (location) and what it needs (date)
{
"tool_calls": [
{
"id": "call_abc123",
"type": "function",
"function": {
"name": "BookTravelPlugin-book_flight",
"arguments": "{\n\"location\": \"New York\",\n\"date\": \"15th July\"\n}"
}
}
]
*/

ChatResponse response = await chatCompletion.GetChatMessageContentAsync(
chatHistory,
executionSettings: openAIPromptExecutionSettings,
kernel: kernel)

# Chain together the prompt, model, and parser
chain = prompt | llm | parser

# Invoke the chain
parsed_data = chain.invoke({"text": user_input})
Console.WriteLine(response);
chatHistory.AddAssistantMessage(response);

print(parsed_data)
# Output: origin='New York' destination='London' date='July 15th'
// AI Response: "Before I can book your flight, I need to know your departure date. When are you planning to travel?"
// I.e above it figures out the tool to call, what arguments it already has (location) and what it needs (date) from the user input, at this point it ends up asking the user for the missing information
```

What you can see from this example is how you can leverage a pre-built parser to extract key information from user input, such as the origin, destination, and date of a flight booking request. This modular approach allows you to focus on the high-level logic.
Expand Down

0 comments on commit 609536e

Please sign in to comment.