You need to enable JavaScript to run this app.
导航
ChatCompletions
最近更新时间:2024.11.29 11:22:29首次发布时间:2024.08.12 14:42:02

前提条件

接口参数

请参见请求参数

示例代码

说明

  • 示例代码中 <YOUR_ENDPOINT_ID> 需要替换为您在平台上创建的推理接入点 ID。
  • 示例代码中 ARK_API_KEY是模型调用凭证,建议您配置到环境变量中,具体方法请参见3. 获取并配置 API Key

单轮

import os
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

print("----- standard request -----")
completion = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages=[
        {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
        {"role": "user", "content": "常见的十字花科植物有哪些?"},
    ],
)
print(completion.choices[0].message.content)

多轮

import os
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

print("----- multiple rounds request -----")
completion = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages = [
        {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
        {"role": "user", "content": "花椰菜是什么?"},
        {"role": "assistant", "content": "花椰菜又称菜花、花菜,是一种常见的蔬菜。"},
        {"role": "user", "content": "再详细点"},
    ],
)
print(completion.choices[0].message.content)

流式

import os
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

print("----- streaming request -----")
stream = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages = [
        {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
        {"role": "user", "content": "常见的十字花科植物有哪些?"},
    ],
    stream=True
)
for chunk in stream:
    if not chunk.choices:
        continue
    print(chunk.choices[0].delta.content, end="")
print()

异步

import asyncio
import os
from volcenginesdkarkruntime import AsyncArk

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

async def main() -> None:
    stream = await client.chat.completions.create(
        model="<YOUR_ENDPOINT_ID>",
        messages=[
            {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
            {"role": "user", "content": "常见的十字花科植物有哪些?"},
        ],
        stream=True
    )
    async for completion in stream:
        print(completion.choices[0].delta.content, end="")
    print()


asyncio.run(main())

Function call

import os
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

print("----- function call request -----")
completion = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages = [
        {"role": "user", "content": "北京今天天气如何?"},
    ],
    tools=[
        {
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "获取给定地点的天气",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "地点的位置信息,比如北京"
                        },
                        "unit": {
                            "type": "string",
                            "enum": [
                                "摄氏度",
                                "华氏度"
                            ]
                        }
                    },
                    "required": [
                        "location"
                    ]
                }
            }
        }
    ]
)
print(completion.choices[0])

设置自定义 header

import os
from volcenginesdkarkruntime._constants import CLIENT_REQUEST_HEADER
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

print("----- standard request -----")
completion = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages = [
        {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
        {"role": "user", "content": "常见的十字花科植物有哪些?"},
    ],
    # 自定义request id
    extra_headers={CLIENT_REQUEST_HEADER: "202406251728190000B7EA7A9648AC08D9"}
)
print(completion.choices[0].message.content)

推理会话数据应用层加密

为了保证推理会话数据的传输安全,在默认的网络层加密方案基础上,方舟安全团队为在线推理的会话数据提供了端到端应用层加密方案,仅需增加一行代码,在自定义header中设置'x-is-encrypted': 'true',即可免费使用本功能,支持用户通过 SDK 在本地对推理会话的内容进行加密。更多能力介绍和原理信息请参考推理会话数据应用层加密方案

  • 版本要求:需要保证 SDK 版本 volcengine-python-sdk 1.0.104及以上。可以通过 pip install 'volcengine-python-sdk[ark]' -U 获得 SDK 的最新版本。
  • 能力支持:仅支持 AK/SK 初始化,仅支持豆包文生文对话模型,仅支持 Chat Completions 中的单轮/多轮会话,支持流式/非流式,同步/异步接口。
import os
from volcenginesdkarkruntime import Ark

ak = os.environ.get("VOLC_ACCESSKEY")
sk = os.environ.get("VOLC_SECRETKEY")
client = Ark(ak=ak, sk=sk)

print("----- standard request -----")
completion = client.chat.completions.create(
    model="<YOUR_ENDPOINT_ID>",
    messages = [
        {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
        {"role": "user", "content": "常见的十字花科植物有哪些?"},
    ],
    #按下述代码设置自定义header,免费开启推理会话应用层加密
    extra_headers={'x-is-encrypted': 'true'}
)
print(completion.choices[0].message.content)

异常处理

import os
from volcenginesdkarkruntime._exceptions import ArkAPIError
from volcenginesdkarkruntime import Ark

client = Ark(api_key=os.environ.get("ARK_API_KEY"))

# Streaming:
print("----- streaming request -----")
try:
    stream = client.chat.completions.create(
        model="<YOUR_ENDPOINT_ID>",
        messages=[
            {"role": "system", "content": "你是豆包,是由字节跳动开发的 AI 人工智能助手"},
            {"role": "user", "content": "常见的十字花科植物有哪些?"},
        ],
        stream=True
    )
    for chunk in stream:
        if not chunk.choices:
            continue

        print(chunk.choices[0].delta.content, end="")
    print()
except ArkAPIError as e:
    print(e)