Files
semantic-kernel/samples/notebooks/python/03-semantic-function-inline.ipynb
T
7ed26eacaa Python: Update notebooks by pinning pip package and removing requirements.txt (#868)
### Motivation and Context

* Removing the requirements.txt and just pinning each notebook to a pip
package that should work.
Doing this allows users to run notebooks without error even if the code
in the core repo updates.
When a new pip package is released, we will bump the version number in
each notebook.
* Fix usage of context variables. Apps should avoid using anonymous
context variables and prefer using the context, to retain access to the
kernel internals during the orchestration.

---------

Co-authored-by: Alex Chao <[email protected]>
Co-authored-by: Devis Lucato <[email protected]>
2023-05-08 18:13:17 -07:00

217 lines
7.5 KiB
Plaintext
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{
"cells": [
{
"cell_type": "markdown",
"id": "3c93ac5b",
"metadata": {},
"source": [
"# Running Semantic Functions Inline"
]
},
{
"cell_type": "markdown",
"id": "ebcabb91",
"metadata": {},
"source": []
},
{
"cell_type": "markdown",
"id": "40201641",
"metadata": {},
"source": [
"The [previous notebook](./02-running-prompts-from-file.ipynb)\n",
"showed how to define a semantic function using a prompt template stored on a file.\n",
"\n",
"In this notebook, we'll show how to use the Semantic Kernel to define functions inline with your python code. This can be useful in a few scenarios:\n",
"\n",
"* Dynamically generating the prompt using complex rules at runtime\n",
"* Writing prompts by editing Python code instead of TXT files.\n",
"* Easily creating demos, like this document\n",
"\n",
"Prompt templates are defined using the SK template language, which allows to reference variables and functions. Read [this doc](https://aka.ms/sk/howto/configurefunction) to learn more about the design decisions for prompt templating. \n",
"\n",
"For now we'll use only the `{{$input}}` variable, and see more complex templates later.\n",
"\n",
"Almost all semantic function prompts have a reference to `{{$input}}`, which is the default way\n",
"a user can import content from the context variables."
]
},
{
"cell_type": "markdown",
"id": "d90b0c13",
"metadata": {},
"source": [
"Prepare a semantic kernel instance first, loading also the AI service settings defined in the [Setup notebook](00-getting-started.ipynb):"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "1da651d4",
"metadata": {},
"outputs": [],
"source": [
"!python -m pip install semantic-kernel==0.2.7.dev0"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3712b7c3",
"metadata": {},
"outputs": [],
"source": [
"import semantic_kernel as sk\n",
"from semantic_kernel.connectors.ai.open_ai import AzureTextCompletion, OpenAITextCompletion\n",
"\n",
"kernel = sk.Kernel()\n",
"\n",
"useAzureOpenAI = False\n",
"\n",
"# Configure AI service used by the kernel\n",
"if useAzureOpenAI:\n",
" deployment, api_key, endpoint = sk.azure_openai_settings_from_dot_env()\n",
" kernel.add_text_completion_service(\"dv\", AzureTextCompletion(deployment, endpoint, api_key))\n",
"else:\n",
" api_key, org_id = sk.openai_settings_from_dot_env()\n",
" kernel.add_text_completion_service(\"dv\", OpenAITextCompletion(\"text-davinci-003\", api_key, org_id))"
]
},
{
"cell_type": "markdown",
"id": "589733c5",
"metadata": {},
"source": [
"Let's use a prompt to create a semantic function used to summarize content, allowing for some creativity and a sufficient number of tokens.\n",
"\n",
"The function will take in input the text to summarize."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ae29c207",
"metadata": {},
"outputs": [],
"source": [
"prompt = \"\"\"{{$input}}\n",
"Summarize the content above.\n",
"\"\"\"\n",
"\n",
"summarize = kernel.create_semantic_function(prompt, max_tokens=2000, temperature=0.2, top_p=0.5)"
]
},
{
"cell_type": "markdown",
"id": "f26b90c4",
"metadata": {},
"source": [
"Set up some content to summarize, here's an extract about Demo, an ancient Greek poet, taken from Wikipedia (https://en.wikipedia.org/wiki/Demo_(ancient_Greek_poet)."
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "314557fb",
"metadata": {},
"outputs": [],
"source": [
"input_text = \"\"\"\n",
"Demo (ancient Greek poet)\n",
"From Wikipedia, the free encyclopedia\n",
"Demo or Damo (Greek: Δεμώ, Δαμώ; fl. c. AD 200) was a Greek woman of the Roman period, known for a single epigram, engraved upon the Colossus of Memnon, which bears her name. She speaks of herself therein as a lyric poetess dedicated to the Muses, but nothing is known of her life.[1]\n",
"Identity\n",
"Demo was evidently Greek, as her name, a traditional epithet of Demeter, signifies. The name was relatively common in the Hellenistic world, in Egypt and elsewhere, and she cannot be further identified. The date of her visit to the Colossus of Memnon cannot be established with certainty, but internal evidence on the left leg suggests her poem was inscribed there at some point in or after AD 196.[2]\n",
"Epigram\n",
"There are a number of graffiti inscriptions on the Colossus of Memnon. Following three epigrams by Julia Balbilla, a fourth epigram, in elegiac couplets, entitled and presumably authored by \"Demo\" or \"Damo\" (the Greek inscription is difficult to read), is a dedication to the Muses.[2] The poem is traditionally published with the works of Balbilla, though the internal evidence suggests a different author.[1]\n",
"In the poem, Demo explains that Memnon has shown her special respect. In return, Demo offers the gift for poetry, as a gift to the hero. At the end of this epigram, she addresses Memnon, highlighting his divine status by recalling his strength and holiness.[2]\n",
"Demo, like Julia Balbilla, writes in the artificial and poetic Aeolic dialect. The language indicates she was knowledgeable in Homeric poetry—'bearing a pleasant gift', for example, alludes to the use of that phrase throughout the Iliad and Odyssey.[a][2] \n",
"\"\"\""
]
},
{
"cell_type": "markdown",
"id": "bf0f2330",
"metadata": {},
"source": [
"...and run the summary function:"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7b0e3b0c",
"metadata": {},
"outputs": [],
"source": [
"# If needed, async is available too: summary = await summarize.invoke_async(input_text)\n",
"summary = summarize(input_text)\n",
"\n",
"print(summary)"
]
},
{
"cell_type": "markdown",
"id": "4777f447",
"metadata": {},
"source": [
"Here's one more example of how to write an inline Semantic Function that gives a TLDR for a piece of text.\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ea8128c8",
"metadata": {},
"outputs": [],
"source": [
"sk_prompt = \"\"\"\n",
"{{$input}}\n",
"\n",
"Give me the TLDR in 5 words.\n",
"\"\"\"\n",
"\n",
"text = \"\"\"\n",
" 1) A robot may not injure a human being or, through inaction,\n",
" allow a human being to come to harm.\n",
"\n",
" 2) A robot must obey orders given it by human beings except where\n",
" such orders would conflict with the First Law.\n",
"\n",
" 3) A robot must protect its own existence as long as such protection\n",
" does not conflict with the First or Second Law.\n",
"\"\"\"\n",
"\n",
"tldr_function = kernel.create_semantic_function(sk_prompt, max_tokens=200, temperature=0, top_p=0.5)\n",
"\n",
"summary = tldr_function(text)\n",
"\n",
"print(f\"Output: {summary}\") # Output: Robots must not harm humans."
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"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.9"
}
},
"nbformat": 4,
"nbformat_minor": 5
}