Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
rstropek committed Apr 4, 2024
2 parents ded199a + f3e4e69 commit 1405918
Show file tree
Hide file tree
Showing 31 changed files with 107 additions and 5 deletions.
File renamed without changes.
File renamed without changes.
76 changes: 76 additions & 0 deletions labs/015-basics-python/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import time
import os
from dotenv import load_dotenv
from openai import AzureOpenAI


# Load environment variables from .env file
load_dotenv()

client = AzureOpenAI(
api_key=os.getenv("OPENAI_AZURE_KEY"),
api_version="2024-02-01",
azure_endpoint=os.getenv("OPENAI_AZURE_ENDPOINT")
)

# In this sample, we use key-based authentication. This is only done because this sample
# will be done by a larger group in a hackathon event. In real world, AVOID key-based
# authentication. ALWAYS prefer Microsoft Entra-based authentication (Managed Identity)!

# System prompt
system_prompt = """
You are an assistant that helps customer to find the right bike. Options are:
* Light, single-speed bike for urban commuting.
* Gravel bike designed to ride on many different surfaces.
* Cargo bike for transporting kids or goods.
* Racing bike for sports.
* Moutainbike designed for off-road cycling.
* All bike types above a also available with electric motors.
Ask the user about how she or he is going to use the bike. Make a suggestion
based on the intended use.
If transporting goods or kids seems to be important for the customer,
mention the option of using a bike trailer as an alternative for cargo bikes.
Point out that bike trailers should not be used with carbon bike frames.
Only answer questions related to bike type selection. If the user asks
questions not related to this topic, tell her or him that you cannot
answer such questions.
"""

# Initial assistant message to get the conversation started
assistant_message = "Hi! Can I help you find the right bike?"

print(f"🤖: {assistant_message}")

deploymentModel = os.getenv("OPENAI_AZURE_DEPLOYMENT")
while True:
# Ask the user for a message. Exit program in case of empty message.
user_message = input("\nYou (just press enter to exit the conversation): ")
if not user_message:
break

# Send the messages to the API and wait for the response. Display a
# waiting indicator while waiting for the response.
print("\nThinking...", end="")

response = client.chat.completions.create(model=deploymentModel,
messages=[
{"role": "system",
"content": system_prompt},
{"role": "assistant",
"content": assistant_message},
{"role": "user",
"content": user_message}
])

print("\n")
if len(response.choices) == 0:
print(f"Error: no response from the API. Exiting...")
break

# Add the response from the API to the list of messages to send to the API
assistant_message = response.choices[0].message.content
print(f"🤖: {assistant_message}")
22 changes: 22 additions & 0 deletions labs/015-basics-python/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# OpenAI API Basics

## Introduction

This example introduces you to the fundamentals of using the Azure OpenAI API. We will cover the following topics:

* How to setup your connection to Azure OpenAI
* Configuring the system prompt
* Build a conversation loop
* Send messages to OpenAI and receive the agent's response

## Exercises

* Make yourself familiar with the code in [main.py](./main.py).
* Think about an assistant that would be relevant to your business or personal life. Adjust the system prompt to match your assistant's purpose. Test the program and see how well it performs.
* Try to break out of the limits of the system prompt. What happens if you ask the assistant to do something that is not related to the system prompt?

## Advanced Exercises

* Setup an ChatGPT 3.5 model and compare the results with the GPT-4 model.
* Convert the console application to an ASP.NET Core web application.
* Use streaming to receive messages from the OpenAI API step by step.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ logger.info('Connection pool connected');
const openai = new OpenAI({
// Note that this base URL is different from the one that you would need for
// chat completions API. The base URL here is for the new Assistants API.
baseURL: `${process.env.OPENAI_AZURE_ENDPOINT}openai`,
baseURL: `${process.env.OPENAI_AZURE_ENDPOINT}/openai`,
apiKey: process.env.OPENAI_AZURE_KEY,
defaultQuery: { 'api-version': '2024-03-01-preview' },
defaultHeaders: { 'api-key': process.env.OPENAI_AZURE_KEY }
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function createConnectionPool(connectionString: string): Promise<sq
}

const config: sql.config = {
user: connectionStringParts.get('User') ?? '',
user: connectionStringParts.get('User ID') ?? '',
password: connectionStringParts.get('Password') ?? '',
server: server,
database: connectionStringParts.get('Initial Catalog') ?? '',
Expand Down
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const products = await getProductModels(pool);
logger.info('Product models complete', { count: products.length });

const openai = new OpenAI({
baseURL: `${process.env.OPENAI_AZURE_ENDPOINT}openai/deployments/${process.env.OPENAI_AZURE_EMBEDDINGS}/`,
baseURL: `${process.env.OPENAI_AZURE_ENDPOINT}/openai/deployments/${process.env.OPENAI_AZURE_EMBEDDINGS}/`,
apiKey: process.env.OPENAI_AZURE_KEY,
defaultQuery: { 'api-version': '2024-03-01-preview' },
defaultHeaders: { 'api-key': process.env.OPENAI_AZURE_KEY }
Expand Down
File renamed without changes.
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ export async function createConnectionPool(connectionString: string): Promise<sq
}

const config: sql.config = {
user: connectionStringParts.get('User') ?? '',
user: connectionStringParts.get('User ID') ?? '',
password: connectionStringParts.get('Password') ?? '',
server: server,
database: connectionStringParts.get('Initial Catalog') ?? '',
Expand Down
File renamed without changes.
6 changes: 5 additions & 1 deletion readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

This repository contains demos and samples for the [_Microsoft Build: AI Day (Austria)_](https://msevents.microsoft.com/event?id=3431470856). It contains the following labs:

* [OpenAI Chat Completions Basics](./labs/010-basics/) (C# and .NET)
* [OpenAI Chat Completions Basics](./labs/010-basics/) (C# and .NET or Python)
* [Function Calling with Chat Completions](./labs/020-functions/) (C# and .NET)
* [Using Tools with the new _Assistant_ API](./labs/030-assistants/) (TypeScript and Node.js)
* [Embeddings and the RAG model](./labs/040-embeddings-rag/) (TypeScript and Node.js)
Expand Down Expand Up @@ -37,6 +37,10 @@ If you do not want to use _Dev Containers_, install the following software on yo
* Latest LTS version of [Node.js](https://nodejs.org)
* Latest version of Visual Studio Code

## Environment variables

Within this workshop we are working with a shared Azure OpenAI tenant and specific deployments. As part of the workshop you will receive an `.env` file from your instructors, so you can access the shared Azure OpenAI tenant from your project folder. After adding the `.env` file to the root of this repository, or copying the `.env.template` file and rename it, you will be able to execute the various `labs` in this repostiory.

## Sample Data

The hands-on-labs in this repo use the [_Adventure Works LT_ sample database](https://learn.microsoft.com/en-us/sql/samples/adventureworks-install-configure). If you participate in the official hackathon, your trainers will provide a connection string to an instance of _Adventure Works LT_ in Azure. If you work on the samples at home, [install _Adventure Works LT_ in Azure](https://learn.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-server-ver16&tabs=ssms#deploy-to-azure-sql-database) or on a [local SQL Server](https://learn.microsoft.com/en-us/sql/samples/adventureworks-install-configure?view=sql-server-ver16&tabs=ssms#restore-to-sql-server).
Expand Down

0 comments on commit 1405918

Please sign in to comment.