Skip to content

Commit 2746eac

Browse files
authored
Merge pull request microsoft#202 from softchris/ch9-issue
adding dotnet lessons, also adding simpler notebooks for ch07 and ch0…
2 parents ec8af00 + 1e9c385 commit 2746eac

File tree

8 files changed

+327
-16
lines changed

8 files changed

+327
-16
lines changed

06-text-generation-apps/app-recipe.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@
2424

2525

2626
# engine
27-
engine = os.getenv("ENGINE")
2827

2928
# deployment_id
3029
deployment_name = os.getenv("DEPLOYMENT_NAME")
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!meta
2+
3+
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
4+
5+
#!csharp
6+
7+
#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.8"
8+
9+
#!csharp
10+
11+
using Azure;
12+
using Azure.AI.OpenAI;
13+
using static System.Environment;
14+
15+
#!csharp
16+
17+
string endpoint = "<replace with endpoint>";
18+
string key = "<replace with API key>";
19+
20+
OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));
21+
22+
var chatCompletionsOptions = new ChatCompletionsOptions()
23+
{
24+
Messages =
25+
{
26+
new ChatMessage(ChatRole.System, "You are the president of France"),
27+
new ChatMessage(ChatRole.System, "You have just resigned"),
28+
new ChatMessage(ChatRole.User, "What tasks needs doing?")
29+
},
30+
MaxTokens = 100
31+
};
32+
33+
Response<ChatCompletions> response = client.GetChatCompletions("gpt-35-turbo", chatCompletionsOptions);
34+
35+
Console.WriteLine(response.Value.Choices[0].Message.Content);
36+
37+
Console.WriteLine();
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": [
9+
"import os\n",
10+
"import openai\n",
11+
"\n",
12+
"openai.api_type = \"azure\"\n",
13+
"openai.api_version = os.getenv(\"AZURE_OPENAI_API_VERSION\",\"\").strip()\n",
14+
"\n",
15+
"API_KEY = os.getenv(\"AZURE_OPENAI_API_KEY\",\"\").strip()\n",
16+
"assert API_KEY, \"ERROR: Azure OpenAI Key is missing\"\n",
17+
"openai.api_key = API_KEY\n",
18+
"\n",
19+
"RESOURCE_ENDPOINT = os.getenv(\"OPENAI_API_BASE\",\"\").strip()\n",
20+
"assert RESOURCE_ENDPOINT, \"ERROR: Azure OpenAI Endpoint is missing\"\n",
21+
"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",
22+
"openai.api_base = RESOURCE_ENDPOINT\n",
23+
"deployment = \"gpt-35-turbo\" # replace with your deployment name"
24+
]
25+
},
26+
{
27+
"cell_type": "code",
28+
"execution_count": null,
29+
"metadata": {},
30+
"outputs": [],
31+
"source": [
32+
"# Create your first prompt\n",
33+
"text_prompt = \" My foot hurts, what can be wrong?\"\n",
34+
"\n",
35+
"response = openai.ChatCompletion.create(\n",
36+
" engine=deployment,\n",
37+
" messages = [\n",
38+
" {\"role\":\"system\", \"content\":\"I'm a doctor, specialist on surgery\"},\n",
39+
" {\"role\":\"user\",\"content\":text_prompt},])\n",
40+
"\n",
41+
"\n",
42+
"response['choices'][0]['message']['content']"
43+
]
44+
}
45+
],
46+
"metadata": {
47+
"kernelspec": {
48+
"display_name": "Python 3",
49+
"language": "python",
50+
"name": "python3"
51+
},
52+
"language_info": {
53+
"codemirror_mode": {
54+
"name": "ipython",
55+
"version": 3
56+
},
57+
"file_extension": ".py",
58+
"mimetype": "text/x-python",
59+
"name": "python",
60+
"nbconvert_exporter": "python",
61+
"pygments_lexer": "ipython3",
62+
"version": "3.10.11"
63+
},
64+
"orig_nbformat": 4
65+
},
66+
"nbformat": 4,
67+
"nbformat_minor": 2
68+
}
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#!meta
2+
3+
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
4+
5+
#!csharp
6+
7+
#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.9"
8+
9+
#!csharp
10+
11+
using Azure;
12+
using Azure.AI.OpenAI;
13+
14+
#!csharp
15+
16+
#r "nuget:Microsoft.DotNet.Interactive.AIUtilities, 1.0.0-beta.23557.4"
17+
18+
using Microsoft.DotNet.Interactive;
19+
using Microsoft.DotNet.Interactive.AIUtilities;
20+
21+
#!csharp
22+
23+
var azureOpenAIKey = "<replace with API key>";
24+
var azureOpenAIEndpoint = "<replace with endpoint>";
25+
var deployment = "<replace with deployment name, should be of type ADA embedding for Azure Open AI>";
26+
27+
#!csharp
28+
29+
OpenAIClient client = new (new Uri(azureOpenAIEndpoint), new AzureKeyCredential(azureOpenAIKey));
30+
31+
#!csharp
32+
33+
var source = "Car";
34+
var compareTo = "Vehicle";
35+
var parrot = "A bird";
36+
37+
var parrotEmbeddings = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ parrot }));
38+
39+
// vector version
40+
var embeddings = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ source }));
41+
42+
// vector version
43+
var embeddingsCompareTo = await client.GetEmbeddingsAsync(new EmbeddingsOptions(deployment, new []{ compareTo }));
44+
45+
var sourceValue = embeddings.Value.Data[0].Display();
46+
Console.WriteLine(sourceValue);
47+
var compareToValue = embeddingsCompareTo.Value.Data[0].Display();
48+
Console.WriteLine(compareToValue);
49+
50+
#!csharp
51+
52+
var comparer = new CosineSimilarityComparer<float[]>(f => f);
53+
var carArray = embeddings.Value.Data[0].Embedding.ToArray(); // float []
54+
var vehicleArray = embeddingsCompareTo.Value.Data[0].Embedding.ToArray(); // float []
55+
var parrotArray = parrotEmbeddings.Value.Data[0].Embedding.ToArray(); // float []
56+
57+
var score = comparer.Score(carArray, vehicleArray);
58+
Console.WriteLine(score);
59+
60+
score = comparer.Score(carArray, parrotArray);
61+
Console.WriteLine(score);
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
{
2+
"cells": [
3+
{
4+
"cell_type": "code",
5+
"execution_count": null,
6+
"metadata": {},
7+
"outputs": [],
8+
"source": [
9+
"!pip install openai dotenv"
10+
]
11+
},
12+
{
13+
"cell_type": "code",
14+
"execution_count": null,
15+
"metadata": {},
16+
"outputs": [],
17+
"source": [
18+
"import os\n",
19+
"import openai\n",
20+
"from dotenv import load_dotenv\n",
21+
"load_dotenv()\n",
22+
"\n",
23+
"openai.api_type = \"azure\"\n",
24+
"openai.api_version = os.getenv(\"AZURE_OPENAI_API_VERSION\",\"\").strip()\n",
25+
"\n",
26+
"API_KEY = os.getenv(\"AZURE_OPENAI_API_KEY\",\"\").strip()\n",
27+
"assert API_KEY, \"ERROR: Azure OpenAI Key is missing\"\n",
28+
"openai.api_key = API_KEY\n",
29+
"\n",
30+
"RESOURCE_ENDPOINT = os.getenv(\"OPENAI_API_BASE\",\"\").strip()\n",
31+
"assert RESOURCE_ENDPOINT, \"ERROR: Azure OpenAI Endpoint is missing\"\n",
32+
"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",
33+
"openai.api_base = RESOURCE_ENDPOINT"
34+
]
35+
},
36+
{
37+
"cell_type": "code",
38+
"execution_count": null,
39+
"metadata": {},
40+
"outputs": [],
41+
"source": [
42+
"# Dependencies for embeddings_utils\n",
43+
"!pip install matplotlib plotly scikit-learn pandas"
44+
]
45+
},
46+
{
47+
"cell_type": "code",
48+
"execution_count": null,
49+
"metadata": {},
50+
"outputs": [],
51+
"source": [
52+
"from openai.embeddings_utils import cosine_similarity"
53+
]
54+
},
55+
{
56+
"cell_type": "code",
57+
"execution_count": null,
58+
"metadata": {},
59+
"outputs": [],
60+
"source": [
61+
"text = 'the quick brown fox jumped over the lazy dog'\n",
62+
"model = 'text-embedding-ada-002'\n",
63+
"openai.Embedding()\\\n",
64+
" .create(input=[text], engine='text-embedding-ada-002')[\"data\"][0][\"embedding\"]"
65+
]
66+
},
67+
{
68+
"cell_type": "code",
69+
"execution_count": null,
70+
"metadata": {},
71+
"outputs": [],
72+
"source": [
73+
"# compare several words\n",
74+
"automobile_embedding = openai.Embedding.create(input='automobile', engine=model)[\"data\"][0][\"embedding\"]\n",
75+
"vehicle_embedding = openai.Embedding.create(input='vehicle', engine=model)[\"data\"][0][\"embedding\"]\n",
76+
"dinosaur_embedding = openai.Embedding.create(input='dinosaur', engine=model)[\"data\"][0][\"embedding\"]\n",
77+
"stick_embedding = openai.Embedding.create(input='stick', engine=model)[\"data\"][0][\"embedding\"]\n",
78+
"\n",
79+
"# 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",
80+
"print(cosine_similarity(automobile_embedding, automobile_embedding))\n",
81+
"print(cosine_similarity(automobile_embedding, vehicle_embedding))\n",
82+
"print(cosine_similarity(automobile_embedding, dinosaur_embedding))\n",
83+
"print(cosine_similarity(automobile_embedding, stick_embedding))"
84+
]
85+
}
86+
],
87+
"metadata": {
88+
"kernelspec": {
89+
"display_name": "Python 3",
90+
"language": "python",
91+
"name": "python3"
92+
},
93+
"language_info": {
94+
"codemirror_mode": {
95+
"name": "ipython",
96+
"version": 3
97+
},
98+
"file_extension": ".py",
99+
"mimetype": "text/x-python",
100+
"name": "python",
101+
"nbconvert_exporter": "python",
102+
"pygments_lexer": "ipython3",
103+
"version": "3.10.11"
104+
},
105+
"orig_nbformat": 4
106+
},
107+
"nbformat": 4,
108+
"nbformat_minor": 2
109+
}

09-building-image-applications/app.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@
1919
try:
2020
# Create an image by using the image generation API
2121
generation_response = openai.Image.create(
22-
prompt='Bunny on horse, holding a lollipop, on a foggy meadow where it grows daffodils', # Enter your prompt text here
22+
prompt='Red and white Rocket with fussy paws', # Enter your prompt text here
2323
size='1024x1024',
2424
n=2,
25-
temperature=0,
25+
temperature=1,
2626
)
2727
# Set the directory for the stored image
2828
image_dir = os.path.join(os.curdir, 'images')
@@ -50,20 +50,20 @@
5050

5151
# ---creating variation below---
5252

53-
response = openai.Image.create_variation(
54-
image=open(image_path, "rb"),
55-
n=1,
56-
size="1024x1024"
57-
)
53+
# response = openai.Image.create_variation(
54+
# image=open(image_path, "rb"),
55+
# n=1,
56+
# size="1024x1024"
57+
# )
5858

59-
image_path = os.path.join(image_dir, 'generated_variation.png')
59+
# image_path = os.path.join(image_dir, 'generated_variation.png')
6060

61-
image_url = response['data'][0]['url']
61+
# image_url = response['data'][0]['url']
6262

63-
generated_image = requests.get(image_url).content # download the image
64-
with open(image_path, "wb") as image_file:
65-
image_file.write(generated_image)
63+
# generated_image = requests.get(image_url).content # download the image
64+
# with open(image_path, "wb") as image_file:
65+
# image_file.write(generated_image)
6666

67-
# Display the image in the default image viewer
68-
image = Image.open(image_path)
69-
image.show()
67+
# # Display the image in the default image viewer
68+
# image = Image.open(image_path)
69+
# image.show()
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#!meta
2+
3+
{"kernelInfo":{"defaultKernelName":"csharp","items":[{"aliases":[],"name":"csharp"}]}}
4+
5+
#!csharp
6+
7+
#r "nuget: Azure.AI.OpenAI, 1.0.0-beta.9"
8+
9+
#!csharp
10+
11+
using System;
12+
using System.IO;
13+
using System.Threading.Tasks;
14+
using Azure.AI.OpenAI;
15+
using Azure;
16+
17+
#!csharp
18+
19+
string endpoint = "<replace with endpoint>";
20+
string key = "<replace with API key>";
21+
22+
#!csharp
23+
24+
OpenAIClient client = new(new Uri(endpoint), new AzureKeyCredential(key));
25+
26+
var imageGenerations = await client.GetImageGenerationsAsync(
27+
new ImageGenerationOptions()
28+
{
29+
Prompt = "captain with a parrot on his shoulder",
30+
Size = ImageSize.Size256x256,
31+
});
32+
33+
// Image Generations responses provide URLs you can use to retrieve requested images
34+
Uri imageUri = imageGenerations.Value.Data[0].Url;
35+
36+
// Print the image URI to console:
37+
Console.WriteLine(imageUri);
Loading

0 commit comments

Comments
 (0)