文档

Llama 系列大语言模型 API 详情

更新时间:

Llama模型

Llama2 /Llama3大语言模型是Meta开发并公开发布的系列大型语言模型(LLMs)。

模型概览

模型名称

上下文长度(Token数)

输入输出成本

免费额度

llama3.1-405b-instruct

128k

目前仅供免费体验。

免费额度用完后不可调用,敬请关注后续动态。

100万Token(需申请)

有效期:百炼开通后30天内

llama3.1-70b-instruct

llama3.1-8b-instruct

llama3-70b-instruct

8k

100万Token(需申请)

有效期:百炼开通后180天内

llama3-8b-instruct

llama2-13b-chat-v2

4k

100万Token(需申请)

有效期:申请通过后180天内

llama2-7b-chat-v2

SDK使用

您可以通过SDK实现单轮对话、多轮对话、流式输出、function call等多种功能。

前提条件

  • DashScope SDK提供了Python和Java两个版本,请确保您已安装最新版SDK安装SDK

  • 已开通服务并获得API-KEY:获取API-KEY

  • 我们推荐您将API-KEY配置到环境变量中以降低API-KEY的泄漏风险,详情可参考通过环境变量配置API-KEY。您也可以在代码中配置API-KEY,但是泄漏风险会增加。

    说明

    当您使用DashScope Java SDK时,为了效率您应该尽可能复用Generation以及其他请求对象,但对象(如Generation)不是线程安全的,您应该采取一定的措施,比如及时关闭进程、管理同步机制等,来确保对象安全。

文本生成

以下示例展示了调用Llama系列模型对一个用户指令进行响应的代码。

# For prerequisites running the following sample, visit https://help.aliyun.com/document_detail/611472.html
from http import HTTPStatus
import dashscope


def call_with_messages():
    messages = [{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你是谁'}]
    response = dashscope.Generation.call(
        model='llama3-8b-instruct',
        messages=messages,
        result_format='message',  # set the result to be "message" format.
    )
    if response.status_code == HTTPStatus.OK:
        print(response)
    else:
        print('Request id: %s, Status code: %s, error code: %s, error message: %s' % (
            response.request_id, response.status_code,
            response.code, response.message
        ))


if __name__ == '__main__':
    call_with_messages()
// Copyright (c) Alibaba, Inc. and its affiliates.

import java.util.ArrayList;
import java.util.List;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;

public class Main {
    public static void usage()
            throws NoApiKeyException, ApiException, InputRequiredException {
        List<Message> messages = new ArrayList<>();
        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue()).content("You are a helpful assistant.").build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是谁").build();
        messages.add(systemMsg);
        messages.add(userMsg);

        GenerationParam param = GenerationParam.builder()
                .model("llama3-8b-instruct")
                .messages(messages)
                .build();
        Generation gen = new Generation();
        GenerationResult result = gen.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            usage();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

参数配置

参数

类型

默认值

说明

model

string

-

模型名,可配置为已申请的 Llama 系列的模型

messages

list[dict]

-

用户输入的内容,dict内主要包含2个key:role和content,其中role支持user、assistant、system,content为对应role的text输入。

result_format

string

-

用户返回的内容类型,默认为text,当输入格式为messages时可配置为message。

返回结果

  • 返回结果示例

{
  "status_code": 200,
  "request_id": "7a98d596-1a56-9f4d-82ef-91cdcaefd389",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": " I am LLaMA, a helpful assistant developed by Meta AI that can understand and respond to human input in a conversational manner. I'm here to assist you with any questions, tasks, or topics you'd like to discuss. I can provide information on a wide range of subjects, from science and history to entertainment and culture. I can also help with language-related tasks such as language translation, text summarization, and more. So, feel free to ask me anything, and I'll do my best to help! "
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 24,
    "output_tokens": 109,
    "total_tokens": 133
  }
}
  • 返回参数说明

返回参数

类型

说明

status_code

int

200(HTTPStatus.OK)表示请求成功,否则表示请求失败,可以通过code获取错误码,通过message字段获取错误详细信息。

request_Id

string

系统生成的标志本次调用的id。

code

string

表示请求失败,表示错误码,成功忽略。

message

string

失败,表示失败详细信息,成功忽略。

output

dict

调用结果信息,对于Llama2模型,包含输出text。

output.text

string

模型生成回复。

usage.input_tokens

int

用户输入文本转换成Token后的长度。

usage.output_tokens

int

模型生成回复转换为Token后的长度。

HTTP调用接口

功能描述

Llama系列模型也同时提供了HTTP接口,您可以根据自己的需求选择。

前提条件

  • 已开通服务并获得API-KEY:获取API-KEY

  • 我们推荐您将API-KEY配置到环境变量中以降低API-KEY的泄漏风险,详情可参考通过环境变量配置API-KEY。您也可以在代码中配置API-KEY,但是泄漏风险会增加。

提交接口调用

POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

入参描述

传参方式

字段

类型

必选

描述

示例值

Header

Content-Type

string

请求类型:application/json

application/json

Authorization

string

API-Key,例如:Bearer d1**2a

Bearer d1**2a

X-DashScope-WorkSpace

string

指明本次调用需要使用的workspace;需要注意的是,对于子账号Apikey调用,此参数为必选项,子账号必须归属于某个workspace才能调用;对于主账号Apikey此项为可选项,添加则使用对应的workspace身份,不添加则使用主账号身份。

ws_QTggmeAxxxxx

Body

model

string

指明需要调用的模型,目前可选

Llama2-7b-chat-v2,

Llama2-13b-chat-v2;

Llama2-7b-chat-v2

input.prompt

string

用户当前输入的期望模型执行指令,7b模型最长不超过2048 tokens,13b模型最长不超过4096 tokens

hello, who are you?

出参描述

字段

类型

描述

示例值

output.text

string

本次请求的算法输出内容。

hello, who are you?\n\nI am an artificial intelligence designed to assist and communicate ... ...

usage.output_tokens

int

本次请求算法输出内容的 token 数目。

104

usage.input_tokens

int

本次请求用户输入内容的 token 数目。

41

request_id

string

本次请求的系统唯一码

fbd7e41a-363c-938a-81be-8ae0f9fbdb3d

请求示例

以下示例展示通过CURL命令来调用Llama系列模型的脚本。

curl --location 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "llama3-8b-instruct",
    "input":{
        "messages":[
            {"content":"你是谁","role":"user"}
        ]
    }
}'

响应示例

{
  "output": {
    "finish_reason": "stop",
    "text": "\n\nI am LLaMA, an AI assistant developed by Meta AI that can understand and respond to human input in a conversational manner. I'm a large language model trained on a massive dataset of text from the internet, which enables me to generate human-like responses to a wide range of topics and questions.\n\nI'm not a human, but I'm designed to be friendly, helpful, and engaging. I can assist with tasks such as answering questions, providing information, generating text, and even creating conversations. I'm constantly learning and improving, so please bear with me if I make any mistakes or don't quite understand what you're saying. "
  },
  "usage": {
    "total_tokens": 146,
    "output_tokens": 133,
    "input_tokens": 13
  },
  "request_id": "95a7f352-1140-9965-a977-11c3f9eaf767"
}

异常响应示例

在访问请求出错的情况下,输出的结果中会通过 code 和 message 指明出错原因。

{
    "code":"InvalidApiKey",
    "message":"Invalid API-key provided.",
    "request_id":"fb53c4ec-1c12-4fc4-a580-cdb7c3261fc1"
}

状态码说明

大模型服务平台通用状态码请查阅:状态码说明