Use your model from your code
Your model is running. How does your own program talk to it? Most model servers offer an OpenAI compatible API. Your program sends messages to an address.
Chapters
- 0:00Introduction
- 0:05The shape: A simple conversation
- 0:17Try it: Your first call
- 0:25From Python: A few lines
- 0:35Messages: Who says what
- 0:46Know this: It doesn't remember
- 0:56Better feel: Stream the answer
- 1:05Grow: One front door
- 1:15Stay safe: Guard the door
- 1:26Wrap up
Read the transcript
Introduction
Your model is running. How does your own program talk to it?
The shape: A simple conversation
Most model servers offer an OpenAI compatible API. Your program sends messages to an address. The server runs the model and sends back the reply.
Try it: Your first call
You can try it from a terminal. Send a request to the chat completions address, naming the model and your message.
curl http://localhost:8000/v1/chat/completions \
-H 'Content-Type: application/json' \
-d '{"model":"my-model",
"messages":[{"role":"user","content":"Hi"}]}'From Python: A few lines
In Python, the OpenAI library works with your own server. Point its base address at your machine, then ask for a reply and print it.
from openai import OpenAI
client = OpenAI(
base_url="http://localhost:8000/v1",
api_key="not-needed-locally")
r = client.chat.completions.create(
model="my-model",
messages=[{"role": "user", "content": "Hi"}])
print(r.choices[0].message.content)Messages: Who says what
A conversation is a list of messages. The system message sets the behaviour. User messages ask. Assistant messages are the model's earlier replies.
Know this: It doesn't remember
The model doesn't remember your last request. Send the history each time. Longer history costs more time. So trim what no longer matters.
Better feel: Stream the answer
Turn on streaming to see words as they arrive. Set a limit on reply length. A lower temperature gives steadier answers.
Grow: One front door
With several models, put a gateway in front. Your programs use one address and one key, and the gateway sends each request to the right model.
Stay safe: Guard the door
Don't expose a model server to the open internet without protection. Keep keys out of your code. Use environment variables. And never trust a reply as a command.
Wrap up
One familiar API, and your own model answers.
Sources
- docs.vllm.ai/en/latest/serving/openai_compatible_server.html
- platform.openai.com/docs/api-reference/chat
- github.com/openai/openai-python
- docs.litellm.ai/docs/simple_proxy