mirror of
https://github.com/microsoft/semantic-kernel.git
synced 2026-10-12 02:19:06 +00:00
### Motivation and Context text-davinci-003 is being retired by Azure OpenAI and is no longer supported for new deployments Resolves - https://github.com/microsoft/semantic-kernel/issues/2309 <!-- Thank you for your contribution to the semantic-kernel repo! Please help reviewers and future users, providing the following information: 1. Why is this change required? 2. What problem does it solve? 3. What scenario does it contribute to? 4. If it fixes an open issue, please link to the issue here. --> ### Description Update examples and notebooks to use gpt-35-turbo / gpt-3.5-turbo instead <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [ ] The code builds clean without any errors or warnings - [ ] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone 😄 Signed-off-by: karthikmurali60 <[email protected]> Co-authored-by: Lee Miller <[email protected]> Co-authored-by: Gil LaHaye <[email protected]>
19 KiB
19 KiB
In [ ]:
!python -m pip install semantic-kernel==0.3.1.dev0In [ ]:
import os
import sys
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
kernel = sk.Kernel()
useAzureOpenAI = False
# Configure AI service used by the kernel
if useAzureOpenAI:
deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
kernel.add_chat_service("chat_completion", AzureChatCompletion("gpt-35-turbo", endpoint, api_key))
else:
api_key, org_id = sk.openai_settings_from_dot_env()
kernel.add_chat_service("chat-gpt", OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id))In [ ]:
import random
from semantic_kernel.skill_definition import sk_function
class GenerateNumberSkill:
"""
Description: Generate a number between 3-x.
"""
@sk_function(
description="Generate a random number between 3-x",
name="GenerateNumberThreeOrHigher"
)
def generate_number_three_or_higher(self, input: str) -> str:
"""
Generate a number between 3-<input>
Example:
"8" => rand(3,8)
Args:
input -- The upper limit for the random number generation
Returns:
int value
"""
try:
return str(random.randint(3, int(input)))
except ValueError as e:
print(f"Invalid input {input}")
raise eIn [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$input}} paragraphs long
"""
corgi_story = kernel.create_semantic_function(prompt_template=sk_prompt,
function_name="CorgiStory",
skill_name="CorgiSkill",
description="Write a short story about two Corgis on an adventure",
max_tokens=500,
temperature=0.5,
top_p=0.5)
generate_number_skill = kernel.import_skill(GenerateNumberSkill())In [ ]:
# Run the number generator
generate_number_three_or_higher = generate_number_skill["GenerateNumberThreeOrHigher"]
number_result = generate_number_three_or_higher(6)
print(number_result)In [ ]:
story = await corgi_story.invoke_async(input=number_result.result)In [ ]:
print("Generating a corgi story exactly {} paragraphs long: ".format(number_result.result))
print("=====================================================")
print(story)In [ ]:
import os
import sys
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion, OpenAIChatCompletion
kernel = sk.Kernel()
useAzureOpenAI = False
# Configure AI service used by the kernel
if useAzureOpenAI:
deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
kernel.add_chat_service("chat_completion", AzureChatCompletion("gpt-35-turbo", endpoint, api_key))
else:
api_key, org_id = sk.openai_settings_from_dot_env()
kernel.add_chat_service("chat-gpt", OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id))
In [ ]:
import random
from semantic_kernel.skill_definition import sk_function, sk_function_context_parameter
from semantic_kernel import SKContext
class GenerateNumberSkill:
"""
Description: Generate a number between a min and a max.
"""
@sk_function(
description="Generate a random number between min and max",
name="GenerateNumber"
)
@sk_function_context_parameter(name="min", description="Minimum number of paragraphs.")
@sk_function_context_parameter(name="max", description="Maximum number of paragraphs.", default_value=10)
def generate_number(self, context: SKContext) -> str:
"""
Generate a number between min-max
Example:
min="4" max="10" => rand(4,8)
Args:
min -- The lower limit for the random number generation
max -- The upper limit for the random number generation
Returns:
int value
"""
try:
return str(random.randint(int(context["min"]), int(context["max"])))
except ValueError as e:
print(f"Invalid input {context['min']} {context['max']}")
raise eIn [ ]:
generate_number_skill = kernel.import_skill(GenerateNumberSkill())
generate_number = generate_number_skill["GenerateNumber"]In [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$paragraph_count}} paragraphs long
- Be written in this language: {{$language}}
"""
corgi_story = kernel.create_semantic_function(prompt_template=sk_prompt,
function_name="CorgiStory",
skill_name="CorgiSkill",
description="Write a short story about two Corgis on an adventure",
max_tokens=500,
temperature=0.5,
top_p=0.5)In [ ]:
context_variables = sk.ContextVariables(variables={
"min": 1,
"max": 5,
"language": "Spanish"
})In [ ]:
context_variables['paragraph_count'] = generate_number.invoke(variables=context_variables).resultIn [ ]:
# Pass the output to the semantic story function
story = await corgi_story.invoke_async(variables=context_variables)In [ ]:
print("Generating a corgi story exactly {} paragraphs long in {} language: ".format(context_variables["paragraph_count"],
context_variables["language"]))
print("=====================================================")
print(story)In [ ]:
import random
from semantic_kernel.skill_definition import sk_function
class GenerateNamesSkill:
"""
Description: Generate character names.
"""
# The default function name will be the name of the function itself, however you can override this
# by setting the name=<name override> in the @sk_function decorator. In this case, we're using
# the same name as the function name for simplicity.
@sk_function(
description="Generate character names",
name="generate_names"
)
def generate_names(self) -> str:
"""
Generate two names.
Returns:
str
"""
names = {
"Hoagie",
"Hamilton",
"Bacon",
"Pizza",
"Boots",
"Shorts",
"Tuna"
}
first_name = random.choice(list(names))
names.remove(first_name)
second_name = random.choice(list(names))
return f"{first_name}, {second_name}"In [ ]:
generate_names_skill = kernel.import_skill(GenerateNamesSkill(), skill_name="GenerateNames")
generate_names = generate_names_skill["generate_names"]In [ ]:
sk_prompt = """
Write a short story about two Corgis on an adventure.
The story must be:
- G rated
- Have a positive message
- No sexism, racism or other bias/bigotry
- Be exactly {{$paragraph_count}} paragraphs long
- Be written in this language: {{$language}}
- The two names of the corgis are {{GenerateNames.generate_names}}
"""In [ ]:
corgi_story = kernel.create_semantic_function(prompt_template=sk_prompt,
function_name="CorgiStory",
skill_name="CorgiSkill",
description="Write a short story about two Corgis on an adventure",
max_tokens=500,
temperature=0.5,
top_p=0.5)In [ ]:
context_variables = sk.ContextVariables(variables={
"min": 1,
"max": 5,
"language": "Spanish"
})
context_variables['paragraph_count'] = generate_number.invoke(variables=context_variables).resultIn [ ]:
# Pass the output to the semantic story function
story = await corgi_story.invoke_async(variables=context_variables)In [ ]:
print("Generating a corgi story exactly {} paragraphs long in {} language: ".format(context_variables["paragraph_count"],
context_variables["language"]))
print("=====================================================")
print(story)