|
| 1 | +"""Antropic Sample""" |
| 2 | +import os |
| 3 | +from typing import List |
| 4 | + |
| 5 | +from dotenv import load_dotenv |
| 6 | +from anthropic import Anthropic, MessageStopEvent, TextEvent |
| 7 | +from toolhouse import Toolhouse, Provider |
| 8 | + |
| 9 | +load_dotenv() |
| 10 | + |
| 11 | +TOKEN = os.getenv("ANTHROPIC_KEY") |
| 12 | +TH_TOKEN = os.getenv("TOOLHOUSE_BEARER_TOKEN") |
| 13 | + |
| 14 | +local_tools = [ |
| 15 | + { |
| 16 | + 'name': 'hello', |
| 17 | + 'description': 'The user receives a customized hello message from a city and returns it to the user.', |
| 18 | + 'input_schema': { |
| 19 | + 'type': 'object', |
| 20 | + 'properties': { |
| 21 | + 'city': {'type': 'string', 'description': 'The city where you are from'} |
| 22 | + }, |
| 23 | + 'required': ['city'] |
| 24 | + } |
| 25 | + } |
| 26 | + ] |
| 27 | + |
| 28 | +client = Anthropic(api_key=TOKEN) |
| 29 | + |
| 30 | +th = Toolhouse(access_token=TH_TOKEN, provider=Provider.ANTHROPIC) |
| 31 | +th.set_metadata("id", "fabio") |
| 32 | +th.set_metadata("timezone", 5) |
| 33 | + |
| 34 | + |
| 35 | +@th.register_local_tool("hello") |
| 36 | +def hello_tool(city: str): |
| 37 | + """Return a Hello message from a specific city.""" |
| 38 | + return f"Hello from {city}!!!" |
| 39 | + |
| 40 | + |
| 41 | +messages: List = [{ |
| 42 | + "role": "user", |
| 43 | + "content": |
| 44 | + "Can I get a hello from Rome?" |
| 45 | + }] |
| 46 | + |
| 47 | +with client.messages.stream( |
| 48 | + model="claude-3-5-sonnet-20240620", |
| 49 | + max_tokens=1024, |
| 50 | + tools=th.get_tools() + local_tools, |
| 51 | + messages=messages |
| 52 | +) as stream: |
| 53 | + for block in stream: |
| 54 | + if isinstance(block, MessageStopEvent): |
| 55 | + messages += th.run_tools(block.message, stream=True) |
| 56 | + elif isinstance(block, TextEvent): |
| 57 | + print(block.text, end="", flush=True) |
| 58 | + |
| 59 | + |
| 60 | +with client.messages.stream( |
| 61 | + model="claude-3-5-sonnet-20240620", |
| 62 | + max_tokens=1024, |
| 63 | + tools=th.get_tools() + local_tools, |
| 64 | + messages=messages |
| 65 | +) as stream: |
| 66 | + for text in stream.text_stream: |
| 67 | + print(text, end="", flush=True) |
0 commit comments