Claude Client使用
2024-09-08
安装依赖
bash
pip install anthropic
标准请求
python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="sk-ant-xxx",
)
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=[{"role": "user", "content": "Hello, Claude"}],
)
print(message.content)
流式请求
python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="sk-ant-xxx"
)
with client.messages.stream(
max_tokens=1024,
messages=[{"role": "user", "content": "Hello"}],
model="claude-3-5-sonnet-20240620",
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
多轮对话请求
Messages API是无状态的,这意味着始终需要将完整的会话历史发送给API。你可以用这个模式来构建更早的对话,对话历史不一定需要真实来自claude-你可以按需构造,可以是你合成的历史数据。
python
import anthropic
client = anthropic.Anthropic(
# defaults to os.environ.get("ANTHROPIC_API_KEY")
api_key="sk-ant-xxx"
)
message = client.messages.create(
model="claude-3-5-sonnet-20240620",
max_tokens=1024,
messages=[
{"role": "user", "content": "Hello, Claude"},
{"role": "assistant", "content": "Hello!"},
{"role": "user", "content": "Can you describe LLMs to me?"},
],
)
print(message)