• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

ticoAg

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

openai包基础用法

Note

包含同步&异步 完成&流式
闲言少叙, 看剑

Requirements

pip install openai -U

Code

import openai
import asyncio


def pp(obj: str):
    print(obj.center(50, "*"))


# sync
def _sync():
    ## w/o stream
    pp("Sync w/o stream")
    response = client.chat.completions.create(
        model=model, messages=messages, temperature=0
    )
    print(response.choices[0].message.content)

    ## w/ stream
    pp("Sync w/ stream")
    response = client.chat.completions.create(
        model=model, messages=messages, temperature=0, stream=True
    )
    for chunk in response:
        content = chunk.choices[0].delta.content
        if content:
            print(content, end="", flush=True)
        if chunk.choices[0].finish_reason == "stop":
            print()


# async
async def _async():
    # w/o stream
    pp("Async w/o stream")
    async_response = await aclient.chat.completions.create(
        model=model, messages=messages, temperature=0
    )
    print(async_response.choices[0].message.content)

    ## w/ stream
    pp("Async w/ stream")

    async_response_with_stream = await aclient.chat.completions.create(
        model=model, messages=messages, temperature=0, stream=True
    )
    async for chunk in async_response_with_stream:
        content = chunk.choices[0].delta.content
        if content:
            print(content, end="", flush=True)
        if chunk.choices[0].finish_reason == "stop":
            print()


async def main():
    _sync()
    await _async()


if __name__ == "__main__":
    client = openai.OpenAI()
    aclient = openai.AsyncOpenAI()

    model = "Qwen1.5-32B-Chat"
    messages = [{"role": "user", "content": "Who are you"}]
    asyncio.run(main())

posted on 2024-04-17 22:02  躺好摆烂  阅读(194)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3