openai_chat_completion_client.py 1.63 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
Reid's avatar
Reid committed
2
3
4
5
"""Example Python client for OpenAI Chat Completion using vLLM API server
NOTE: start a supported chat completion model server with `vllm serve`, e.g.
    vllm serve meta-llama/Llama-2-7b-chat-hf
"""
6
7
8

import argparse

9
from openai import OpenAI
10
11

# Modify OpenAI's API key and API base to use vLLM's API server.
12
13
openai_api_key = "EMPTY"
openai_api_base = "http://localhost:8000/v1"
14

Reid's avatar
Reid committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
messages = [{
    "role": "system",
    "content": "You are a helpful assistant."
}, {
    "role": "user",
    "content": "Who won the world series in 2020?"
}, {
    "role": "assistant",
    "content": "The Los Angeles Dodgers won the World Series in 2020."
}, {
    "role": "user",
    "content": "Where was it played?"
}]


30
31
32
33
34
35
36
37
38
def parse_args():
    parser = argparse.ArgumentParser(description="Client for vLLM API server")
    parser.add_argument("--stream",
                        action="store_true",
                        help="Enable streaming response")
    return parser.parse_args()


def main(args):
Reid's avatar
Reid committed
39
40
41
42
43
44
45
46
47
    client = OpenAI(
        # defaults to os.environ.get("OPENAI_API_KEY")
        api_key=openai_api_key,
        base_url=openai_api_base,
    )

    models = client.models.list()
    model = models.data[0].id

48
    # Chat Completion API
Reid's avatar
Reid committed
49
50
51
    chat_completion = client.chat.completions.create(
        messages=messages,
        model=model,
52
        stream=args.stream,
Reid's avatar
Reid committed
53
54
55
56
    )

    print("-" * 50)
    print("Chat completion results:")
57
58
59
60
61
    if args.stream:
        for c in chat_completion:
            print(c)
    else:
        print(chat_completion)
Reid's avatar
Reid committed
62
63
64
65
    print("-" * 50)


if __name__ == "__main__":
66
67
    args = parse_args()
    main(args)