Skip to content

Commit

Permalink
Merge pull request #202 from softchris/ch9-issue
Browse files Browse the repository at this point in the history
adding dotnet lessons, also adding simpler notebooks for ch07 and ch0…
  • Loading branch information
leestott authored Nov 24, 2023
2 parents ec8af00 + 1e9c385 commit 2746eac
Show file tree
Hide file tree
Showing 8 changed files with 327 additions and 16 deletions.
1 change: 0 additions & 1 deletion 06-text-generation-apps/app-recipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@


# engine
engine = os.getenv("ENGINE")

# deployment_id
deployment_name = os.getenv("DEPLOYMENT_NAME")
Expand Down
37 changes: 37 additions & 0 deletions 07-building-chat-applications/dotnet/notebook-azure-openai.dib
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!meta

{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}

#!csharp

#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.8"

#!csharp

using Azure;
using Azure.AI.OpenAI;
using static System.Environment;

#!csharp

string endpoint = "<replace with endpoint>";
string key = "<replace with API key>";

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var chatCompletionsOptions = new ChatCompletionsOptions()
{
Messages =
{
new ChatMessage(ChatRole.System, "You are the president of France"),
new ChatMessage(ChatRole.System, "You have just resigned"),
new ChatMessage(ChatRole.User, "What tasks needs doing?")
},
MaxTokens = 100
};

Response<ChatCompletions> response = client.GetChatCompletions("gpt-35-turbo", chatCompletionsOptions);

Console.WriteLine(response.Value.Choices[0].Message.Content);

Console.WriteLine();
68 changes: 68 additions & 0 deletions 07-building-chat-applications/notebook-simple-azure-openai.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import openai\n",
"\n",
"openai.api_type = \"azure\"\n",
"openai.api_version = os.getenv(\"AZURE_OPENAI_API_VERSION\",\"\").strip()\n",
"\n",
"API_KEY = os.getenv(\"AZURE_OPENAI_API_KEY\",\"\").strip()\n",
"assert API_KEY, \"ERROR: Azure OpenAI Key is missing\"\n",
"openai.api_key = API_KEY\n",
"\n",
"RESOURCE_ENDPOINT = os.getenv(\"OPENAI_API_BASE\",\"\").strip()\n",
"assert RESOURCE_ENDPOINT, \"ERROR: Azure OpenAI Endpoint is missing\"\n",
"assert \"openai.azure.com\" in RESOURCE_ENDPOINT.lower(), \"ERROR: Azure OpenAI Endpoint should be in the form: \\n\\n\\t<your unique endpoint identifier>.openai.azure.com\"\n",
"openai.api_base = RESOURCE_ENDPOINT\n",
"deployment = \"gpt-35-turbo\" # replace with your deployment name"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Create your first prompt\n",
"text_prompt = \" My foot hurts, what can be wrong?\"\n",
"\n",
"response = openai.ChatCompletion.create(\n",
" engine=deployment,\n",
" messages = [\n",
" {\"role\":\"system\", \"content\":\"I'm a doctor, specialist on surgery\"},\n",
" {\"role\":\"user\",\"content\":text_prompt},])\n",
"\n",
"\n",
"response['choices'][0]['message']['content']"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.11"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
61 changes: 61 additions & 0 deletions 08-building-search-applications/dotnet/notebook-azure-openai.dib
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#!meta

{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}

#!csharp

#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.9"

#!csharp

using Azure;
using Azure.AI.OpenAI;

#!csharp

#r "nuget:Microsoft.DotNet.Interactive.AIUtilities, 1.0.0-beta.23557.4"

using Microsoft.DotNet.Interactive;
using Microsoft.DotNet.Interactive.AIUtilities;

#!csharp

var azureOpenAIKey = "<replace with API key>";
var azureOpenAIEndpoint = "<replace with endpoint>";
var deployment = "<replace with deployment name, should be of type ADA embedding for Azure Open AI>";

#!csharp

OpenAIClient client = new (new Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey));

#!csharp

var source = "Car";
var compareTo = "Vehicle";
var parrot = "A bird";

var parrotEmbeddings = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ parrot }));

// vector version
var embeddings = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ source }));

// vector version
var embeddingsCompareTo = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ compareTo }));

var sourceValue = embeddings.Value.Data[0].Display();
Console.WriteLine(sourceValue);
var compareToValue = embeddingsCompareTo.Value.Data[0].Display();
Console.WriteLine(compareToValue);

#!csharp

var comparer = new CosineSimilarityComparer<float[]>(f => f);
var carArray = embeddings.Value.Data[0].Embedding.ToArray(); // float []
var vehicleArray = embeddingsCompareTo.Value.Data[0].Embedding.ToArray(); // float []
var parrotArray = parrotEmbeddings.Value.Data[0].Embedding.ToArray(); // float []

var score = comparer.Score(carArray, vehicleArray);
Console.WriteLine(score);

score = comparer.Score(carArray, parrotArray);
Console.WriteLine(score);
109 changes: 109 additions & 0 deletions 08-building-search-applications/notebook-azure-openai-simple.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"!pip install openai dotenv"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import openai\n",
"from dotenv import load_dotenv\n",
"load_dotenv()\n",
"\n",
"openai.api_type = \"azure\"\n",
"openai.api_version = os.getenv(\"AZURE_OPENAI_API_VERSION\",\"\").strip()\n",
"\n",
"API_KEY = os.getenv(\"AZURE_OPENAI_API_KEY\",\"\").strip()\n",
"assert API_KEY, \"ERROR: Azure OpenAI Key is missing\"\n",
"openai.api_key = API_KEY\n",
"\n",
"RESOURCE_ENDPOINT = os.getenv(\"OPENAI_API_BASE\",\"\").strip()\n",
"assert RESOURCE_ENDPOINT, \"ERROR: Azure OpenAI Endpoint is missing\"\n",
"assert \"openai.azure.com\" in RESOURCE_ENDPOINT.lower(), \"ERROR: Azure OpenAI Endpoint should be in the form: \\n\\n\\t<your unique endpoint identifier>.openai.azure.com\"\n",
"openai.api_base = RESOURCE_ENDPOINT"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Dependencies for embeddings_utils\n",
"!pip install matplotlib plotly scikit-learn pandas"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from openai.embeddings_utils import cosine_similarity"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"text = 'the quick brown fox jumped over the lazy dog'\n",
"model = 'text-embedding-ada-002'\n",
"openai.Embedding()\\\n",
" .create(input=[text], engine='text-embedding-ada-002')[\"data\"][0][\"embedding\"]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# compare several words\n",
"automobile_embedding = openai.Embedding.create(input='automobile', engine=model)[\"data\"][0][\"embedding\"]\n",
"vehicle_embedding = openai.Embedding.create(input='vehicle', engine=model)[\"data\"][0][\"embedding\"]\n",
"dinosaur_embedding = openai.Embedding.create(input='dinosaur', engine=model)[\"data\"][0][\"embedding\"]\n",
"stick_embedding = openai.Embedding.create(input='stick', engine=model)[\"data\"][0][\"embedding\"]\n",
"\n",
"# comparing cosine similarity, automobiles vs automobiles should be 1.0, i.e exactly the same, while automobiles vs dinosaurs should be between 0 and 1, i.e. not the same\n",
"print(cosine_similarity(automobile_embedding, automobile_embedding))\n",
"print(cosine_similarity(automobile_embedding, vehicle_embedding))\n",
"print(cosine_similarity(automobile_embedding, dinosaur_embedding))\n",
"print(cosine_similarity(automobile_embedding, stick_embedding))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.10.11"
},
"orig_nbformat": 4
},
"nbformat": 4,
"nbformat_minor": 2
}
30 changes: 15 additions & 15 deletions 09-building-image-applications/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@
try:
# Create an image by using the image generation API
generation_response = openai.Image.create(
prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here
prompt='Red and white Rocket with fussy paws', # Enter your prompt text here
size='1024x1024',
n=2,
temperature=0,
temperature=1,
)
# Set the directory for the stored image
image_dir = os.path.join(os.curdir, 'images')
Expand Down Expand Up @@ -50,20 +50,20 @@

# ---creating variation below---

response = openai.Image.create_variation(
image=open(image_path, "rb"),
n=1,
size="1024x1024"
)
# response = openai.Image.create_variation(
# image=open(image_path, "rb"),
# n=1,
# size="1024x1024"
# )

image_path = os.path.join(image_dir, 'generated_variation.png')
# image_path = os.path.join(image_dir, 'generated_variation.png')

image_url = response['data'][0]['url']
# image_url = response['data'][0]['url']

generated_image = requests.get(image_url).content # download the image
with open(image_path, "wb") as image_file:
image_file.write(generated_image)
# generated_image = requests.get(image_url).content # download the image
# with open(image_path, "wb") as image_file:
# image_file.write(generated_image)

# Display the image in the default image viewer
image = Image.open(image_path)
image.show()
# # Display the image in the default image viewer
# image = Image.open(image_path)
# image.show()
37 changes: 37 additions & 0 deletions 09-building-image-applications/dotnet/notebook-azure-openai.dib
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!meta

{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}

#!csharp

#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.9"

#!csharp

using System;
using System.IO;
using System.Threading.Tasks;
using Azure.AI.OpenAI;
using Azure;

#!csharp

string endpoint = "<replace with endpoint>";
string key = "<replace with API key>";

#!csharp

OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));

var imageGenerations = await client.GetImageGenerationsAsync(
new ImageGenerationOptions()
{
Prompt = "captain with a parrot on his shoulder",
Size = ImageSize.Size256x256,
});

// Image Generations responses provide URLs you can use to retrieve requested images
Uri imageUri = imageGenerations.Value.Data[0].Url;

// Print the image URI to console:
Console.WriteLine(imageUri);
Binary file modified 09-building-image-applications/images/generated-image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 2746eac

Please sign in to comment.