Skip to content

Commit de3436d

Browse files
authored
Python: fixes and release (#855)
* Fix lint errors * Bump version number * Add retry loop to integration tests * Enable all integration tests: some tests will fail if OpenAI/Azure are throttling.
1 parent 3fae7c4 commit de3436d

File tree

10 files changed

+87
-46
lines changed

10 files changed

+87
-46
lines changed

Diff for: python/pyproject.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[tool.poetry]
22
name = "semantic-kernel"
3-
version = "0.2.6.dev"
3+
version = "0.2.7.dev"
44
description = ""
55
authors = ["Microsoft <[email protected]>"]
66
readme = "pip/README.md"

Diff for: python/semantic_kernel/connectors/ai/hugging_face/services/hf_text_completion.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33
from logging import Logger
44
from typing import Optional
55

6-
76
from semantic_kernel.connectors.ai.ai_exception import AIException
87
from semantic_kernel.connectors.ai.complete_request_settings import (
98
CompleteRequestSettings,
@@ -48,11 +47,13 @@ def __init__(
4847
self._log = log if log is not None else NullLogger()
4948

5049
try:
51-
import transformers
5250
import torch
51+
import transformers
5352
except (ImportError, ModuleNotFoundError):
54-
raise ImportError("Please ensure that torch and transformers are installed to use HuggingFaceTextCompletion")
55-
53+
raise ImportError(
54+
"Please ensure that torch and transformers are installed to use HuggingFaceTextCompletion"
55+
)
56+
5657
self.device = (
5758
"cuda:" + device if device >= 0 and torch.cuda.is_available() else "cpu"
5859
)
@@ -75,6 +76,7 @@ async def complete_async(
7576
"""
7677
try:
7778
import transformers
79+
7880
generation_config = transformers.GenerationConfig(
7981
temperature=request_settings.temperature,
8082
top_p=request_settings.top_p,

Diff for: python/semantic_kernel/connectors/ai/hugging_face/services/hf_text_embedding.py

+7-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
from logging import Logger
44
from typing import List, Optional
5+
56
from numpy import array, ndarray
67

78
from semantic_kernel.connectors.ai.ai_exception import AIException
@@ -37,11 +38,13 @@ def __init__(
3738
self._log = log if log is not None else NullLogger()
3839

3940
try:
40-
import torch
4141
import sentence_transformers
42-
except (ImportError):
43-
raise ImportError("Please ensure that torch and sentence-transformers are installed to use HuggingFaceTextEmbedding")
44-
42+
import torch
43+
except ImportError:
44+
raise ImportError(
45+
"Please ensure that torch and sentence-transformers are installed to use HuggingFaceTextEmbedding"
46+
)
47+
4548
self.device = (
4649
"cuda:" + device if device >= 0 and torch.cuda.is_available() else "cpu"
4750
)

Diff for: python/semantic_kernel/kernel.py

+1
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@
4949

5050
T = TypeVar("T")
5151

52+
5253
class Kernel(KernelBase, KernelExtensions):
5354
_log: Logger
5455
_skill_collection: SkillCollectionBase

Diff for: python/tests/integration/completions/e2e_text_completion.py

+56-24
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,25 @@
1+
import logging
2+
import time
3+
14
import semantic_kernel as sk
25

6+
logging.basicConfig(level=logging.DEBUG)
7+
logger = logging.getLogger()
8+
9+
10+
async def retry(func, retries=15, delay=1):
11+
for i in range(retries):
12+
try:
13+
result = str(await func())
14+
if "Error" in result:
15+
raise ValueError(result)
16+
return result
17+
except Exception as e:
18+
logger.error(f"Retry {i + 1}: {e}")
19+
if i == retries - 1: # Last retry
20+
raise
21+
time.sleep(delay)
22+
323

424
async def summarize_function_test(kernel: sk.Kernel):
525
# Define semantic function using SK prompt template language
@@ -33,68 +53,80 @@ async def summarize_function_test(kernel: sk.Kernel):
3353
print()
3454

3555
# Summarize input string and print
36-
summary = await kernel.run_async(tldr_function, input_str=text_to_summarize)
37-
56+
summary = await retry(
57+
lambda: kernel.run_async(tldr_function, input_str=text_to_summarize)
58+
)
3859
output = str(summary).strip()
3960
print(f"Summary using input string: '{output}'")
40-
assert len(output.split(" ")) == 5
61+
assert "humans" in output or "Humans" in output or "preserve" in output
62+
assert len(output) < 100
4163

4264
# Summarize input as context variable and print
4365
context_vars = sk.ContextVariables(text_to_summarize)
44-
summary = await kernel.run_async(tldr_function, input_vars=context_vars)
45-
66+
summary = await retry(
67+
lambda: kernel.run_async(tldr_function, input_vars=context_vars)
68+
)
4669
output = str(summary).strip()
4770
print(f"Summary using context variables: '{output}'")
48-
assert len(output.split(" ")) == 5
71+
assert "humans" in output or "Humans" in output or "preserve" in output
72+
assert len(output) < 100
4973

5074
# Summarize input context and print
5175
context = kernel.create_new_context()
5276
context["input"] = text_to_summarize
53-
summary = await kernel.run_async(tldr_function, input_context=context)
54-
77+
summary = await retry(
78+
lambda: kernel.run_async(tldr_function, input_context=context)
79+
)
5580
output = str(summary).strip()
5681
print(f"Summary using input context: '{output}'")
57-
assert len(output.split(" ")) == 5
82+
assert "humans" in output or "Humans" in output or "preserve" in output
83+
assert len(output) < 100
5884

5985
# Summarize input context with additional variables and print
6086
context = kernel.create_new_context()
6187
context["input"] = text_to_summarize
6288
context_vars = sk.ContextVariables("4) All birds are robots.")
63-
summary = await kernel.run_async(
64-
tldr_function, input_context=context, input_vars=context_vars
89+
summary = await retry(
90+
lambda: kernel.run_async(
91+
tldr_function, input_context=context, input_vars=context_vars
92+
)
6593
)
66-
6794
output = str(summary).strip()
6895
print(f"Summary using context and additional variables: '{output}'")
69-
assert len(output.split(" ")) == 5
96+
assert "humans" in output or "Humans" in output or "preserve" in output
97+
assert len(output) < 100
7098

7199
# Summarize input context with additional input string and print
72100
context = kernel.create_new_context()
73101
context["input"] = text_to_summarize
74-
summary = await kernel.run_async(
75-
tldr_function, input_context=context, input_str="4) All birds are robots."
102+
summary = await retry(
103+
lambda: kernel.run_async(
104+
tldr_function, input_context=context, input_str="4) All birds are robots."
105+
)
76106
)
77-
78107
output = str(summary).strip()
79108
print(f"Summary using context and additional string: '{output}'")
80-
assert len(output.split(" ")) == 5
109+
assert "humans" in output or "Humans" in output or "preserve" in output
110+
assert len(output) < 100
81111

82112
# Summarize input context with additional variables and string and print
83113
context = kernel.create_new_context()
84114
context["input"] = text_to_summarize
85115
context_vars = sk.ContextVariables(variables={"input2": "4) All birds are robots."})
86-
summary = await kernel.run_async(
87-
tldr_function,
88-
input_context=context,
89-
input_vars=context_vars,
90-
input_str="new text",
116+
summary = await retry(
117+
lambda: kernel.run_async(
118+
tldr_function,
119+
input_context=context,
120+
input_vars=context_vars,
121+
input_str="new text",
122+
)
91123
)
92-
93124
output = str(summary).strip()
94125
print(
95126
f"Summary using context, additional variables, and additional string: '{output}'"
96127
)
97-
assert len(output.split(" ")) == 5
128+
assert "humans" in output or "Humans" in output or "preserve" in output
129+
assert len(output) < 100
98130

99131

100132
async def simple_summarization(kernel: sk.Kernel):

Diff for: python/tests/integration/completions/test_azure_oai_chat_service.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@
1111

1212

1313
@pytest.mark.asyncio
14-
@pytest.mark.xfail(
15-
raises=AssertionError,
16-
reason="Azure OpenAI may throttle requests, preventing this test from passing",
17-
)
1814
async def test_azure_chat_completion_with_skills():
1915
kernel = sk.Kernel()
2016

@@ -27,6 +23,10 @@ async def test_azure_chat_completion_with_skills():
2723
deployment_name, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
2824
deployment_name = "gpt-4"
2925

26+
print("* Service: Azure OpenAI Chat Completion")
27+
print(f"* Endpoint: {endpoint}")
28+
print(f"* Deployment: {deployment_name}")
29+
3030
# Configure LLM service
3131
kernel.add_chat_service(
3232
"chat_completion",

Diff for: python/tests/integration/completions/test_azure_oai_text_service.py

+4
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,10 @@ async def test_azure_text_completion_with_skills():
2323
deployment_name, api_key, endpoint = sk.azure_openai_settings_from_dot_env()
2424
deployment_name = "text-davinci-003"
2525

26+
print("* Service: Azure OpenAI Text Completion")
27+
print(f"* Endpoint: {endpoint}")
28+
print(f"* Deployment: {deployment_name}")
29+
2630
# Configure LLM service
2731
kernel.add_text_completion_service(
2832
"text_completion",

Diff for: python/tests/integration/completions/test_oai_chat_service.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@
1111

1212

1313
@pytest.mark.asyncio
14-
@pytest.mark.xfail(
15-
raises=AssertionError,
16-
reason="OpenAI may throttle requests, preventing this test from passing",
17-
)
1814
async def test_oai_chat_service_with_skills():
1915
kernel = sk.Kernel()
2016

@@ -25,6 +21,10 @@ async def test_oai_chat_service_with_skills():
2521
# Load credentials from .env file
2622
api_key, org_id = sk.openai_settings_from_dot_env()
2723

24+
print("* Service: OpenAI Chat Completion")
25+
print("* Endpoint: OpenAI")
26+
print("* Model: gpt-3.5-turbo")
27+
2828
kernel.add_chat_service(
2929
"chat-gpt", sk_oai.OpenAIChatCompletion("gpt-3.5-turbo", api_key, org_id)
3030
)

Diff for: python/tests/integration/completions/test_oai_text_service.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,6 @@
1111

1212

1313
@pytest.mark.asyncio
14-
@pytest.mark.xfail(
15-
raises=AssertionError,
16-
reason="OpenAI may throttle requests, preventing this test from passing",
17-
)
1814
async def test_oai_text_completion_with_skills():
1915
kernel = sk.Kernel()
2016

@@ -25,6 +21,10 @@ async def test_oai_text_completion_with_skills():
2521
# Load credentials from .env file
2622
api_key, org_id = sk.openai_settings_from_dot_env()
2723

24+
print("* Service: OpenAI Text Completion")
25+
print("* Endpoint: OpenAI")
26+
print("* Model: text-davinci-003")
27+
2828
kernel.add_chat_service(
2929
"davinci-003", sk_oai.OpenAITextCompletion("text-davinci-003", api_key, org_id)
3030
)

Diff for: python/tests/integration/embeddings/test_oai_embedding_service.py

-1
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@
1111

1212

1313
@pytest.mark.asyncio
14-
# @pytest.mark.xfail(raises=AssertionError, reason="OpenAI may throttle requests, preventing this test from passing")
1514
async def test_oai_embedding_service_with_memories():
1615
kernel = sk.Kernel()
1716

0 commit comments

Comments
 (0)