在 semantic-kernel 中使用

## 创建 .env

OPENAI_API_KEY=sk-xxxx
OPENAI_BASE_URL=https://api.fe8.cn/v1
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import OpenAIChatCompletion
import os
import asyncio

# 加载 .env 到环境变量
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

# 创建 semantic kernel
kernel = sk.Kernel()

# 配置 OpenAI 服务
api_key = os.getenv('OPENAI_API_KEY')
endpoint = os.getenv('OPENAI_BASE_URL')

model = OpenAIChatCompletion(
    "gpt-3.5-turbo", api_key)
service = OpenAIChatCompletion(ai_model_id="gpt-3.5-turbo", api_key=api_key)
service.client.base_url = endpoint
kernel.add_service(service)


# 运行 function 看结果
async def run_function():
    # 定义 semantic function

    joke_function = kernel.add_function(
        function_name="joke",  # function 名字,必填
        plugin_name="MyDemoPlugin",  # function 所属的 plugin,必填
        prompt="讲个笑话"  # prompt,必填
    )

    # 运行 function 看结果
    result = await kernel.invoke(joke_function)
    print(result)


asyncio.run(run_function())

Was this page helpful?