Skip to content
Getting Started with the Claude 2 and the Claude 2 API
  • AI Chat
  • Code
  • Report
  • Spinner

    Setting Up

    %pip install anthropic -q
    from anthropic import Anthropic, HUMAN_PROMPT, AI_PROMPT
    import os
    
    anthropic_api_key = os.environ["ANTHROPIC_API_KEY"]
    
    anthropic = Anthropic(
        api_key= anthropic_api_key,
    )
    HUMAN_PROMPT , AI_PROMPT

    Simple Completions Function

    completion = anthropic.completions.create(
        model="claude-2.1",
        max_tokens_to_sample=350,
        prompt=f"{HUMAN_PROMPT} How do I learn Python in a week?{AI_PROMPT}",
    )
    print(completion.completion)

    Async Completions Function

    from anthropic import AsyncAnthropic
    
    anthropic = AsyncAnthropic()
    
    
    async def main():
        completion = await anthropic.completions.create(
            model="claude-2.1",
            max_tokens_to_sample=300,
            prompt=f"{HUMAN_PROMPT}How many moons does Jupiter have?{AI_PROMPT}",
        )
        print(completion.completion)
    
    
    await main()

    Simple LLM Streaming

    anthropic = Anthropic()
    
    stream = anthropic.completions.create(
        prompt=f"{HUMAN_PROMPT}Could you please write a Python code to train a simple classification model?{AI_PROMPT}",
        max_tokens_to_sample=350,
        model="claude-2.1",
        stream=True,
    )
    for completion in stream:
        print(completion.completion, end="", flush=True)

    Async LLM Streaming

    anthropic = AsyncAnthropic()
    
    stream = await anthropic.completions.create(
        prompt=f"{HUMAN_PROMPT}Please write a blog post on Neural Networks and use Markdown format. Kindly make sure that you proofread your work for any spelling, grammar, or punctuation errors.{AI_PROMPT}",
        max_tokens_to_sample=350,
        model="claude-2.1",
        stream=True,
    )
    async for completion in stream:
        print(completion.completion, end="", flush=True)