Skip to content

Commit

Permalink
Update READMEs, reduce code complexity, misc improvements (microsoft#374
Browse files Browse the repository at this point in the history
)

READMEs and examples are out of date and showing incorrect code. There
are also a few bugs in the SKFunction blocking simpler syntax.

Extend SKFunction to allow synchronous calls and have simpler syntax
when async is not required.

* Update homepage README, moving all Python examples under python/README
* Make SKFunction callable as per v0
* Fix bugs in SKFunction
* Fix examples using realistic code
* Allow to use functions synchronously
  • Loading branch information
dluc committed Apr 13, 2023
1 parent 7d9c40f commit 3b04cfa
Show file tree
Hide file tree
Showing 15 changed files with 464 additions and 432 deletions.
116 changes: 64 additions & 52 deletions python/README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,22 @@
# Quickstart with Poetry
# Setup

## Installation
## OpenAI / Azure OpenAI API keys

Make sure you have an
[Open AI API Key](https://openai.com/api/) or
[Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api)

Copy those keys into a `.env` file (see the `.env.example` file):

```
OPENAI_API_KEY=""
OPENAI_ORG_ID=""
AZURE_OPENAI_API_KEY=""
AZURE_OPENAI_ENDPOINT=""
AZURE_OPENAI_DEPLOYMENT_NAME=""
```

## Using Poetry

First, navigate to the directory containing this README using your chosen shell.
You will need to have Python 3.10 installed.
Expand All @@ -16,72 +32,68 @@ poetry install
poetry shell
```

Make sure you have an
[Open AI API Key](https://openai.com/api/) or
[Azure Open AI service key](https://learn.microsoft.com/azure/cognitive-services/openai/quickstart?pivots=rest-api)

Copy those keys into a `.env` file in this repo (see the `.env.example` file):
# Get Started with Semantic Kernel ⚡

```
OPENAI_API_KEY=""
OPENAI_ORG_ID=""
AZURE_OPENAI_API_KEY=""
AZURE_OPENAI_ENDPOINT=""
```

### Quickstart ⚡
## Example: Running a simple prompt.

```python
import semantic_kernel as sk
import semantic_kernel.ai.open_ai as sk_oai
from semantic_kernel.ai.open_ai import OpenAITextCompletion

kernel = sk.create_kernel()

# This requires a `.env` file in your current
# directory (see above)
# Prepare OpenAI backend using credentials stored in the `.env` file
api_key, org_id = sk.openai_settings_from_dot_env()
kernel.config.add_text_backend("dv", OpenAITextCompletion("text-davinci-003", api_key, org_id))

kernel.config.add_text_backend(
"davinci-002", sk_oai.OpenAITextCompletion(
"text-davinci-002", api_key, org_id
)
)

sk_prompt = """
{{$input}}
# Wrap your prompt in a function
prompt = kernel.create_semantic_function("""
1) A robot may not injure a human being or, through inaction,
allow a human being to come to harm.
Give me the TLDR in exactly 5 words.
"""
2) A robot must obey orders given it by human beings except where
such orders would conflict with the First Law.
text_to_summarize = """
1) A robot may not injure a human being or, through inaction,
allow a human being to come to harm.
3) A robot must protect its own existence as long as such protection
does not conflict with the First or Second Law.
2) A robot must obey orders given it by human beings except where
such orders would conflict with the First Law.
Give me the TLDR in exactly 5 words.""")

3) A robot must protect its own existence as long as such protection
does not conflict with the First or Second Law.
"""

tldr_function = kernel.create_semantic_function(
sk_prompt,
max_tokens=200,
temperature=0,
top_p=0.5,
)
# Run your prompt
print(prompt()) # => Robots must not harm humans.
```

summary = await kernel.run_on_str_async(text_to_summarize, tldr_function)
output = str(summary.variables).strip()
print("Output: " + output)
## Example: Turn prompts into **reusable functions** with input parameters.

# Output: Robots must not harm humans.
```python
# Create a reusable function with one input parameter
summarize = kernel.create_semantic_function("{{$input}}\n\nOne line TLDR with the fewest words.")

# Summarize the laws of thermodynamics
print(summarize("""
1st Law of Thermodynamics - Energy cannot be created or destroyed.
2nd Law of Thermodynamics - For a spontaneous process, the entropy of the universe increases.
3rd Law of Thermodynamics - A perfect crystal at zero Kelvin has zero entropy."""))

# Summarize the laws of motion
print(summarize("""
1. An object at rest remains at rest, and an object in motion remains in motion at constant speed and in a straight line unless acted on by an unbalanced force.
2. The acceleration of an object depends on the mass of the object and the amount of force applied.
3. Whenever one object exerts a force on another object, the second object exerts an equal and opposite on the first."""))

# Summarize the law of universal gravitation
print(summarize("""
Every point mass attracts every single other point mass by a force acting along the line intersecting both points.
The force is proportional to the product of the two masses and inversely proportional to the square of the distance between them."""))

# Output:
# Energy conserved, entropy increases, zero entropy at 0K.
# Objects move in response to forces.
# Gravitational force between two point masses is inversely proportional to the square of the distance between them.
```

Hint: if you want to run this via a file, say `my_sk_example.py`, you will
need to import `asyncio` and replace the `await kernel.run_on_str_async(...)`
call with `asyncio.run(kernel.run_on_str_async(...))`.
## How does this compare to the C# version of Semantic Kernel?

Hint: if you want to try this directly in your terminal, run `python3 -m asyncio`
and then paste the code above into the Python REPL. (This is to enable the
top-level `await` syntax.)
Refer to the [FEATURE_PARITY.md](FEATURE_PARITY.md) doc to see where
things stand in matching the features and functionality of the main SK branch.
Loading

0 comments on commit 3b04cfa

Please sign in to comment.