Files
sglang/examples/frontend_language/quick_start/anthropic_example_complete.py

69 lines
1.5 KiB
Python
Raw Normal View History

2024-01-30 04:29:32 -08:00
"""
Usage:
export ANTHROPIC_API_KEY=sk-******
python3 anthropic_example_complete.py
"""
2024-01-30 04:29:32 -08:00
import sglang as sgl
2024-01-30 04:29:32 -08:00
@sgl.function
def few_shot_qa(s, question):
2024-07-18 04:55:39 +10:00
s += """
\n\nHuman: What is the capital of France?
\n\nAssistant: Paris
\n\nHuman: What is the capital of Germany?
\n\nAssistant: Berlin
\n\nHuman: What is the capital of Italy?
\n\nAssistant: Rome
2024-07-18 04:55:39 +10:00
"""
s += "\n\nHuman: " + question + "\n"
2024-03-22 13:42:22 -07:00
s += "\n\nAssistant:" + sgl.gen("answer", temperature=0)
2024-01-30 04:29:32 -08:00
def single():
state = few_shot_qa.run(question="What is the capital of the United States?")
answer = state["answer"].strip().lower()
assert "washington" in answer, f"answer: {state['answer']}"
print(state.text())
def stream():
state = few_shot_qa.run(
2024-07-18 04:55:39 +10:00
question="What is the capital of the United States?", stream=True
)
2024-01-30 04:29:32 -08:00
for out in state.text_iter("answer"):
print(out, end="", flush=True)
print()
def batch():
2024-07-18 04:55:39 +10:00
states = few_shot_qa.run_batch(
[
{"question": "What is the capital of the United States?"},
{"question": "What is the capital of China?"},
]
)
2024-01-30 04:29:32 -08:00
for s in states:
print(s["answer"])
2024-01-30 04:29:32 -08:00
if __name__ == "__main__":
2024-03-22 22:23:31 +02:00
sgl.set_default_backend(sgl.Anthropic("claude-3-haiku-20240307"))
2024-01-30 04:29:32 -08:00
# Run a single request
print("\n========== single ==========\n")
single()
2024-01-30 04:29:32 -08:00
# Stream output
print("\n========== stream ==========\n")
stream()
2024-01-30 04:29:32 -08:00
# Run a batch of requests
print("\n========== batch ==========\n")
batch()