### FastMCP CLI Quick Start Source: https://context7_llms Provides commands to install dependencies and run the FastMCP development server, enabling local LLM tool availability. ```bash # Quick start with FastMCP pip install -r requirements.txt fastmcp dev main.py ``` ```bash fastmcp install main.py ``` -------------------------------- ### Sherlock Domains Python SDK Installation Source: https://context7_llms Instructions for installing the Sherlock Domains Python SDK from PyPI or directly from GitHub. This SDK facilitates programmatic interaction with the Sherlock Domains API. ```bash # Install from PyPI pip install sherlock-domains # Or install latest from GitHub pip install git+https://github.com/Fewsats/sherlock-python.git ``` -------------------------------- ### Install Claudette Library Source: https://claudette.answer.ai/ Installs the Claudette Python library using pip. This command also ensures the Anthropic Python SDK is installed if not already present. ```bash pip install claudette ``` -------------------------------- ### Claudette Text Editor Tool Usage Example Source: https://claudette.answer.ai/ Demonstrates how to initialize a chat with the Text Editor Tool and use it to interact with files, such as explaining a configuration file. ```Python from claudette.text_editor import text_editor_conf, str_replace_based_edit_tool from toolslm.funccall import mk_ns # Create a chat with the text editor tool chat = Chat(model, sp='Be concise in your responses.', tools=[text_editor_conf['sonnet']], ns=mk_ns(str_replace_based_edit_tool)) # Now Claude can explore files for o in chat.toolloop('Please explain concisely what my _quarto.yml does. Use your tools, and explain before each usage what you are doing.'): if not isinstance(o,dict): display(o) ``` -------------------------------- ### Sherlock Domains Python SDK Agent Integration Example with Claudette Source: https://context7_llms Provides an example of integrating the Sherlock Domains Python SDK with an AI assistant using Claudette, a wrapper for Claude, by passing the SDK tools to the Chat initializer. ```Python from claudette import Chat, models # Initialize Sherlock s = Sherlock() # Create chat with tools system_prompt = 'You are a helpful assistant that has access to a domain purchase API.' chat = Chat(models[1], sp=system_prompt, tools=s.as_tools()) ``` -------------------------------- ### Sherlock Domains TypeScript SDK - Installation Source: https://context7_llms Instructions for installing the Sherlock Domains TypeScript SDK using npm. This package provides programmatic access to domain and DNS management functionalities. ```bash npm install sherlock-domains ``` -------------------------------- ### Sherlock Domains TypeScript SDK - DNS Management Example Source: https://context7_llms Illustrates common DNS management tasks using the TypeScript SDK. This example shows how to list existing domains, retrieve a domain ID, and create a new DNS A record. ```typescript const sherlock = new Sherlock('your-token') const domains = await sherlock.domains() const domainId = domains[0].id // Create DNS record await sherlock.createDns(domainId, { type: "A", name: "www", value: "1.2.3.4", ttl: 3600 }) ``` -------------------------------- ### Claude Server-Side Web Search Tool Usage Source: https://claudette.answer.ai/ Demonstrates how to use Claude's server-side web search tool with the `search_conf()` helper function. This example shows initializing a chat with tools and making a query for current weather information. ```python chat = Chat(model, sp='Be concise in your responses.', tools=[search_conf()]) pr = 'What is the current weather in San Diego?' r = chat(pr) r ``` -------------------------------- ### Sherlock Domains TypeScript SDK - Domain Search & Purchase Example Source: https://context7_llms Demonstrates how to use the TypeScript SDK to search for an available domain and then purchase it. It includes initializing the client, performing a search, and executing a purchase with a specified payment method. ```typescript const sherlock = new Sherlock('your-token') const results = await sherlock.search("example.com") if (results.available) { const purchase = await sherlock.purchaseDomain( results.id, "example.com", 'credit_card' ) } ``` -------------------------------- ### Async Streaming with Prefill Source: https://claudette.answer.ai/ Illustrates how to stream responses asynchronously from the chat client, including the use of the `prefill` argument to guide the model's initial output. This is useful for receiving partial responses as they are generated. ```python async for o in await chat("Concisely, what is the meaning of life?", prefill='According to Douglas Adams,', stream=True): print(o, end='') ``` -------------------------------- ### Initialize AnthropicVertex Client with Google Cloud Source: https://claudette.answer.ai/ Demonstrates how to initialize the `AnthropicVertex` client for Google Cloud. It requires project ID and region, and is then passed to the main `Client` for model interaction. This setup allows using Vertex AI models through the Anthropic SDK. ```python from anthropic import AnthropicVertex import google.auth # project_id = google.auth.default()[1] # gv = AnthropicVertex(project_id=project_id, region="us-east5") # client = Client(models_goog[-1], gv) # chat = Chat(cli=client) # chat("I'm Jeremy") ``` -------------------------------- ### Sherlock Domains Python SDK Domain Search & Purchase Example Source: https://context7_llms Demonstrates a common pattern for using the Sherlock Domains Python SDK to search for an available domain and then purchase it using a credit card. ```Python s = Sherlock() results = s.search("example.com") if results['available']: purchase = s.purchase_domain( results['id'], "example.com", payment_method='credit_card' ) ``` -------------------------------- ### Python Sentence Generation Example Source: https://claudette.answer.ai/ Illustrates a thought process for generating a sentence about the Python programming language, considering potential ambiguities. The output is a descriptive sentence about Python's versatility. ```text Python is a versatile, high-level programming language known for its readable syntax and extensive libraries, making it popular for everything from web development to data science and machine learning. ``` -------------------------------- ### AI Chatbot Conversation Examples Source: https://claudette.answer.ai/ Demonstrates typical conversational exchanges with an AI model, showing user prompts and the model's responses. It highlights how context is maintained across turns and includes usage statistics. ```APIDOC chat('What direction is the puppy facing?') The puppy is facing toward the camera/viewer. You can see the puppy’s face straight-on, with both eyes visible and looking directly at the camera. The puppy appears to be lying down with its head up and oriented forward, giving us a clear frontal view of its sweet face. ``` ```APIDOC chat('What color is it?') The puppy has a chestnut (reddish-brown) and white coat. The ears and patches around the eyes are a rich chestnut or reddish-brown color, while the face has a white blaze down the center and the chest/front appears to be white as well. This is the classic “Blenheim” color pattern that’s common in Cavalier King Charles Spaniels - the combination of chestnut and white markings. ``` -------------------------------- ### Sherlock Domains Python SDK DNS Management Example Source: https://context7_llms Illustrates a common pattern for managing DNS records with the Sherlock Domains Python SDK, including fetching owned domains and creating a new A record. ```Python s = Sherlock() domains = s.domains() domain_id = domains[0]['id'] # Create DNS record s.create_dns( domain_id, type="A", name="www", value="1.2.3.4", ttl=3600 ) ``` -------------------------------- ### Structured Data Extraction with Classes Source: https://claudette.answer.ai/ Illustrates extracting structured data into Python objects using `Client.structured`. A class definition, including type hints and docstrings for parameters, guides the model to populate an instance of the class with the requested information. ```python from claudette.core import Client import re # Assume 'model' is a pre-configured model identifier # model = "claude-sonnet-4-20250514" cli = Client(model) class President: """Information about a president of the United States""" def __init__( self, first:str, # first name last:str, # last name spouse:str, # name of spouse years_in_office:str, # format: "{start_year}-{end_year}" birthplace:str, # name of city birth_year:int # year of birth, `0` if unknown ): assert re.match(r'\d{4}-\d{4}', years_in_office), "Invalid format: `years_in_office`" # store_attr() # Assuming this is a helper to store attributes self.first = first self.last = last self.spouse = spouse self.years_in_office = years_in_office self.birthplace = birthplace self.birth_year = birth_year __repr__ = lambda self: f"President(first='{self.first}', last='{self.last}', spouse='{self.spouse}', years_in_office='{self.years_in_office}', birthplace='{self.birthplace}', birth_year={self.birth_year})" # Example usage: # cli.structured("Provide key information about the 3rd President of the United States", President) # Expected output: # [President(first='Thomas', last='Jefferson', spouse='Martha Wayles Skelton Jefferson', years_in_office='1801-1809', birthplace='Shadwell, Virginia', birth_year=1743)] ``` -------------------------------- ### Send Message to Chat and Get Response Source: https://claudette.answer.ai/ Demonstrates sending a user message to the initialized chat interface and receiving a response from the Claude model. The response object contains message details. ```python chat("I'm Jeremy") # Expected output: # Hello Jeremy! Nice to meet you. How can I help you today? r = chat("What's my name?") # Expected output: # Your name is Jeremy. ``` -------------------------------- ### Sherlock CLI Domain Operations Source: https://context7_llms Provides examples of common Sherlock CLI commands for searching domains, setting contact information, and managing DNS records. ```bash # Search for domain ``` ```bash sherlock search --q example.com ``` ```bash # Set contact information ``` ```bash sherlock set_contact_information --first_name "Test" --last_name "User" ... ``` ```bash # Create DNS record ``` ```bash sherlock create_dns --domain_id "uuid" --type "A" --name "www" --value "1.2.3.4" ``` -------------------------------- ### JavaScript: Annotation Event Listener Setup Source: https://claudette.answer.ai/ Sets up click event listeners for annotation elements (dt tags with data-target-cell attributes). When an annotation is clicked, it triggers the selection and highlighting of corresponding code lines, manages active states for UI elements, and handles deselection when the same element is clicked again. ```javascript // Attach click handler to the DT const annoteDls = window.document.querySelectorAll('dt[data-target-cell]'); for (const annoteDlNode of annoteDls) { annoteDlNode.addEventListener('click', (event) => { const clickedEl = event.target; if (clickedEl !== selectedAnnoteEl) { unselectCodeLines(); const activeEl = window.document.querySelector('dt[data-target-cell].code-annotation-active'); if (activeEl) { activeEl.classList.remove('code-annotation-active'); } selectCodeLines(clickedEl); clickedEl.classList.add('code-annotation-active'); } else { // Unselect the line unselectCodeLines(); clickedEl.classList.remove('code-annotation-active'); } }); } ``` -------------------------------- ### Claudette Chat Initialization and Basic Usage Source: https://claudette.answer.ai/ Shows how to initialize the Claudette Chat object with a model, system prompt, and a list of tools. It also demonstrates making a query that requires tool use and handling the initial tool_use response. ```python sp = "Always use tools if math ops are needed." # Assuming 'model' is a pre-defined model object # chat = Chat(model, sp=sp, tools=[sums]) # pr = f"What is {{a}}+{{b}}?" # r = chat(pr, tool_choice='sums') # print(r) # This would print the tool_use object # Example of a tool_use response structure: # ToolUseBlock(id='toolu_01UUWNqtkMHQss345r1ir17q', input={'a': 604542, 'b': 6458932}, name='sums', type='tool_use') ``` -------------------------------- ### Initialize AnthropicBedrock with AWS Credentials Source: https://claudette.answer.ai/ Demonstrates how to initialize the `AnthropicBedrock` client using AWS access keys stored in environment variables. This client is then used to create a `Client` object for the claudette library. ```Python from anthropic import AnthropicBedrock ab = AnthropicBedrock( aws_access_key=os.environ['AWS_ACCESS_KEY'], aws_secret_key=os.environ['AWS_SECRET_KEY'] ) client = Client(models_aws[-1], ab) ``` -------------------------------- ### Initialize Chat with System Prompt Source: https://claudette.answer.ai/ Initializes a stateful chat interface with a specific Claude model and a system prompt to define the assistant's behavior. ```python chat = Chat(model, sp="""You are a helpful and concise assistant.""") ``` -------------------------------- ### Import Claudette and Set Debug Logging Source: https://claudette.answer.ai/ Demonstrates how to import the Claudette library and optionally enable debug logging for HTTP requests and responses by setting an environment variable. ```python import os # os.environ['ANTHROPIC_LOG'] = 'debug' from claudette import * # Alternatively: import claudette ``` -------------------------------- ### Create Chat Object with Custom Client Source: https://claudette.answer.ai/ Shows how to instantiate a `Chat` object by passing a custom `Client` instance, which is configured with a specific model and provider. ```Python chat = Chat(cli=client) chat("I'm Jeremy") ``` -------------------------------- ### List and Select Claude Models Source: https://claudette.answer.ai/ Shows how to access the list of available Claude models provided by the Claudette library and select a specific model for use. ```python models # Example output: # ['claude-opus-4-20250514', # 'claude-sonnet-4-20250514', # 'claude-3-opus-20240229', # 'claude-3-7-sonnet-20250219', # 'claude-3-5-sonnet-20241022'] model = models[1] # Selects 'claude-sonnet-4-20250514' model ``` -------------------------------- ### Claudette Client API Reference Source: https://claudette.answer.ai/ Provides an overview of the core `Client` and `Chat` objects within the Claudette library. It details initialization parameters and key methods for interacting with Claude models, including structured data extraction and conversational AI. ```APIDOC Client(model_name: str, **kwargs) Initializes the Claudette client. Parameters: model_name: The identifier for the Claude model to use (e.g., 'claude-sonnet-4-20250514'). **kwargs: Additional keyword arguments for model configuration. structured(prompt: str, tool: callable | type, **kwargs) -> list Extracts structured data from a prompt using a provided tool (function or class). Parameters: prompt: The natural language query. tool: A Python function or class definition that specifies the desired output structure. **kwargs: Additional keyword arguments for the structured call. Returns: A list containing the structured output (e.g., function return value or class instance). Chat(model_name: str, **kwargs) Initializes a chat session with the Claudette client. Parameters: model_name: The identifier for the Claude model to use. **kwargs: Additional keyword arguments for chat configuration. __call__(messages: list | str, **kwargs) -> str Sends a message or a list of messages (including images) to the chat session. Parameters: messages: A string or a list containing text strings and/or image byte data. **kwargs: Additional keyword arguments for the chat message. Returns: The model's response as a string. use Property to display token usage statistics for the current chat session. Example: In: 110; Out: 11; Cache create: 0; Cache read: 0; Total Tokens: 121; Search: 0 ``` -------------------------------- ### Python Function Definition with Docments Source: https://claudette.answer.ai/ Demonstrates defining Python functions with type hints and docments comments for clear parameter and return value descriptions, enhancing usability with AI tools. ```python def sums( a:int, # First thing to sum b:int=1 # Second thing to sum ) -> int: # The sum of the inputs """Adds a + b.""" print(f"Finding the sum of {a} and {b}") return a + b ``` ```python def mults( a:int, # First thing to multiply b:int=1 # Second thing to multiply ) -> int: # The product of the inputs """Multiplies a * b.""" print(f"Finding the product of {a} and {b}") return a * b ``` -------------------------------- ### OpenAI Integration for Domain Management Source: https://context7_llms Shows how to initialize Sherlock, OpenAI client, and Cosette chat client to manage domains using natural language prompts with GPT models. ```python from cosette import Chat, Client as CosetteClient from sherlock.core import Sherlock # Initialize clients sherlock = Sherlock() cli = openai.OpenAI(api_key=API_KEY) cosette_client = CosetteClient(MODEL, cli) # Create chat with tools sp = '''You are a helpful assistant that has access to a domain registrar and DNS management API.''' chat = Chat(cli=cosette_client, sp=sp, tools=sherlock.as_tools()) # Example interaction response = chat.toolloop("Is example.com available?") ``` -------------------------------- ### Async Chat Initialization and Usage Source: https://claudette.answer.ai/ Demonstrates initializing an `AsyncChat` client and making a simple asynchronous call to the model. This method is suitable for non-streaming interactions. Requires an initialized model object. ```python chat = AsyncChat(model) await chat("I'm Jeremy") ``` -------------------------------- ### Multi-stage Chat with Images Source: https://claudette.answer.ai/ Shows how to create a multi-stage conversation with the `Chat` object, where an image can be the initial prompt, followed by subsequent text-based questions. This allows for a more interactive dialogue where the model first comments on the image before answering specific queries. ```python from claudette.core import Chat from pathlib import Path # Assume 'model' is a pre-configured model identifier # model = "claude-sonnet-4-20250514" fn = Path('samples/puppy.jpg') chat = Chat(model) # Read image file as bytes img = fn.read_bytes() # Initial prompt with just the image # chat(img) # Expected output (example): # What an adorable puppy! This looks like a Cavalier King Charles Spaniel puppy with the classic Blenheim coloring (chestnut and white markings). The puppy has those characteristic sweet, gentle eyes and silky coat that the breed is known for. The setting with the purple flowers in the background makes for a lovely portrait - it really highlights the puppy’s beautiful coloring and sweet expression. Cavalier King Charles Spaniels are known for being friendly, affectionate companions. Is this your puppy? ``` -------------------------------- ### Claudette Chat Toolloop for Multi-Step Operations Source: https://claudette.answer.ai/ Demonstrates using `Chat.toolloop` to execute complex, multi-step operations involving multiple tools. It shows how to iterate through the responses and see each step of the AI's reasoning and tool calls. ```python # Initialize chat with multiple tools # chat = Chat(model, sp=sp, tools=[sums, mults]) # pr = 'Calculate (604542+6458932)*2' # for o in chat.toolloop(pr): # display(o) # display is assumed to be available for output rendering # Example of intermediate tool_use messages: # [{'content': "I'll help you calculate (604542+6458932)*2. I need to first add the two numbers, then multiply the result by 2.", 'type': 'text'}, # {'id': 'toolu_016NZ7MtE8oWHs5BSkxMcAN7', 'input': {'a': 604542, 'b': 6458932}, 'name': 'sums', 'type': 'tool_use'}] # Example of tool result: # {'content': [{'content': '7063474', 'tool_use_id': 'toolu_016NZ7MtE8oWHs5BSkxMcAN7', 'type': 'tool_result'}], # 'role': 'user'} # Example of next tool call: # [{'content': "Now I'll multiply that result by 2:", 'type': 'text'}, # {'id': 'toolu_019BQuhBzEkCWC1JMp6VtcfD', 'input': {'a': 7063474, 'b': 2}, 'name': 'mults', 'type': 'tool_use'}] ``` -------------------------------- ### JavaScript: Cross-Reference (XRef) Tooltips Source: https://claudette.answer.ai/ Implements tooltips for cross-references (`a.quarto-xref`) using `tippyHover`. It handles fetching content for cross-references, including special logic for section references to display only the initial part of the content. It also supports fetching content from external URLs if the target is not found locally. ```javascript const xrefs = window.document.querySelectorAll('a.quarto-xref'); const processXRef = (id, note) => { // Strip column container classes const stripColumnClz = (el) => { el.classList.remove("page-full", "page-columns"); if (el.children) { for (const child of el.children) { stripColumnClz(child); } } } stripColumnClz(note) if (id === null || id.startsWith('sec-')) { // Special case sections, only their first couple elements const container = document.createElement("div"); if (note.children && note.children.length > 2) { container.appendChild(note.children[0].cloneNode(true)); for (let i = 1; i < note.children.length; i++) { const child = note.children[i]; if (child.tagName === "P" && child.innerText === "") { continue; } else { container.appendChild(child.cloneNode(true)); break; } } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(container); } return container.innerHTML; } else { if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } return note.innerHTML; } } else { // Remove any anchor links if they are present const anchorLink = note.querySelector('a.anchorjs-link'); if (anchorLink) { anchorLink.remove(); } if (window.Quarto?.typesetMath) { window.Quarto.typesetMath(note); } if (note.classList.contains("callout")) { return note.outerHTML; } else { return note.innerHTML; } } } for (var i=0; i res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.getElementById(id); if (note !== null) { const html = processXRef(id, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } } else { // See if we can fetch a full url (with no hash to target) // This is a special case and we should probably do some content thinning / // targeting fetch(url) .then(res => res.text()) .then(html => { const parser = new DOMParser(); const htmlDoc = parser.parseFromString(html, "text/html"); const note = htmlDoc.querySelector('main.content'); if (note !== null) { // This should only happen for chapter cross references // (since there is no id in the URL) // remove the first header if (note.children.length > 0 && note.children[0].tagName === "HEADER") { note.children[0].remove(); } const html = processXRef(null, note); instance.setContent(html); } }).finally(() => { instance.enable(); instance.show(); }); } }); } ``` -------------------------------- ### Simplified Python Function Definition for Tools Source: https://claudette.answer.ai/ Illustrates how Claudette uses docstrings, type hints, and comments to make Python function definitions user-friendly for tool integration. This format simplifies defining functions that LLMs can easily understand and call. ```python def sums( a:int, # First thing to sum b:int=1 # Second thing to sum ) -> int: # The sum of the inputs "Adds a + b." return a + b ``` -------------------------------- ### Accessing LLM Usage Statistics Source: https://claudette.answer.ai/ Demonstrates how to access and print the usage statistics object returned by an LLM interaction. This object contains details about input tokens, output tokens, and cache usage. ```python print(r.usage) Usage(cache_creation_input_tokens=0, cache_read_input_tokens=9287, input_tokens=4, output_tokens=223, server_tool_use=None, service_tier='standard') ``` -------------------------------- ### Python Chatbot Initialization and Model Check Source: https://claudette.answer.ai/ Provides Python code snippets for initializing a chat interface with a specified model and checking for models that support extended thinking. This is crucial for leveraging advanced reasoning capabilities. ```python chat = Chat(model) ``` ```python has_extended_thinking_models {'claude-3-7-sonnet-20250219', 'claude-opus-4-20250514', 'claude-sonnet-4-20250514'} ``` -------------------------------- ### Configure Claudette Web Search Tool Source: https://claudette.answer.ai/ Defines the configuration for Claudette's web search tool, allowing customization of search behavior with parameters like maximum uses, allowed/blocked domains, and user location. ```Python search_conf( max_uses=None, # Maximum number of searches Claude can perform allowed_domains=None, # List of domains to search within (e.g., ['wikipedia.org']) blocked_domains=None, # List of domains to exclude (e.g., ['twitter.com']) user_location=None # Location context for search ) ``` -------------------------------- ### Sherlock Domains Python SDK Agent Integration Tools Source: https://context7_llms Shows how to expose the Sherlock Domains SDK methods as tools for AI agents using the `as_tools()` method. It lists the available agent tools. ```Python s = Sherlock() tools = s.as_tools() # Returns: ['me', '_set_contact_information', '_get_contact_information', '_search', # '_purchase_domain', '_domains', '_dns_records', '_create_dns_record', # '_update_dns_record', '_delete_dns_record'] ``` -------------------------------- ### Claudette Tool Use Features Overview Source: https://claudette.answer.ai/ An overview of Claudette's capabilities for making tool use more ergonomic. It covers simplified function definitions, automatic tool execution, multi-step workflows via `toolloop`, and easy integration methods. ```APIDOC Claudette Tool Use Features: 1. **Simplified Function Definitions**: - Uses docstrings, type hints, and comments for user-friendly Python function definitions. - Example: ```python def sums( a:int, # First thing to sum b:int=1 # Second thing to sum ) -> int: # The sum of the inputs "Adds a + b." return a + b ``` 2. **Automatic Tool Execution**: - Handles the tool calling process automatically when Claude returns a `tool_use` message. - Steps: - Call `chat()` again. - Claudette calls the tool with provided parameters. - Passes the result back to Claude. - Returns Claude’s final response. - No manual parameter extraction or result handling required. 3. **Multi-step Tool Workflows**: - The `toolloop` method supports sequential tool calls for complex problems. - Example: Calculating `(a+b)*2` automatically uses addition and multiplication tools in the correct order. 4. **Easy Tool Integration**: - Pass tools as a simple list to the `Chat` constructor. - Optionally force tool usage with the `tool_choice` parameter. - Get structured data directly with `Client.structured()`. 5. **Reduced Complexity**: - Abstracts away manual handling of tool use messages, parameter parsing, function calls, and result formatting required by base SDKs. - Provides a natural function calling experience instead of complex API orchestration. ``` -------------------------------- ### Basic LLM Interaction with Sherlock Source: https://context7_llms Demonstrates a fundamental interaction where a natural language prompt is used to trigger domain availability checks and purchase requests via the Sherlock tool loop. ```python prompt = "Search if domain 'example.com' is available? If it is request a purchase and process the payment using credit card method." response = chat.toolloop(prompt) ``` -------------------------------- ### JavaScript: Tippy.js Tooltip Initialization Source: https://claudette.answer.ai/ Defines a reusable `tippyHover` function to initialize tooltips using the Tippy.js library. It configures common options such as allowing HTML content, setting maximum width, delay, and placement, making it adaptable for various tooltip needs. ```javascript function tippyHover(el, contentFn, onTriggerFn, onUntriggerFn) { const config = { allowHTML: true, maxWidth: 500, delay: 100, arrow: false, appendTo: function(el) { return el.parentElement; }, interactive: true, interactiveBorder: 10, theme: 'quarto', placement: 'bottom-start', }; if (contentFn) { config.content = contentFn; } if (onTriggerFn) { config.onTrigger = onTriggerFn; } if (onUntriggerFn) { config.onUntrigger = onUntriggerFn; } window.tippy(el, config); } ``` -------------------------------- ### Claudette API: Chat Class Source: https://claudette.answer.ai/ Documentation for the Claudette Chat class, detailing its initialization parameters, methods, and how it facilitates interaction with AI models, particularly for tool usage. ```APIDOC Chat: __init__(model, sp: str = None, tools: list = None, **kwargs): Initializes the Chat interface for interacting with an AI model. Parameters: model: The AI model instance to use (e.g., from Claudette or other providers). sp (str, optional): System prompt to guide the AI's behavior. Defaults to None. tools (list, optional): A list of Python functions or objects that the AI can use as tools. Defaults to None. **kwargs: Additional keyword arguments passed to the underlying model or chat completion API. __call__(prompt: str, tool_choice: str = None, **kwargs): Sends a prompt to the AI and processes the response, including handling tool calls. Parameters: prompt (str): The user's input prompt. tool_choice (str, optional): If specified, forces the AI to use a particular tool. Defaults to None. **kwargs: Additional keyword arguments for the chat completion request. Returns: The AI's response, which could be text or a tool_use object. toolloop(prompt: str, show_trace: bool = False, **kwargs): An iterator that processes a prompt through a sequence of tool calls and responses, suitable for multi-step operations. Parameters: prompt (str): The initial user prompt. show_trace (bool, optional): If True, yields intermediate AI messages and tool calls. Defaults to False. **kwargs: Additional keyword arguments for the chat completion request. Yields: Intermediate or final responses from the AI, including text and tool_use/tool_result objects. use: Property that returns the current token usage statistics for the chat session. Returns: A dictionary or object containing token usage details (e.g., 'In', 'Out', 'Total Tokens'). Related Concepts: - Tool Use: AI models can be instructed to use external functions (tools) to perform tasks like calculations. - System Prompt (sp): A persistent instruction given to the AI to influence its behavior and decision-making. - Docments: A Python library for defining functions with rich metadata (type hints, descriptions) that can be leveraged by AI tools. ``` -------------------------------- ### Stream AI Chat Response in Python Source: https://claudette.answer.ai/ This Python snippet demonstrates how to interact with a chat function, asking a question and enabling streaming for gradual output. It uses a 'prefill' argument for context and prints the streamed response character by character. ```python for o in chat("Concisely, what book was that in?", prefill='It was in', stream=True): print(o, end='') ``` -------------------------------- ### Image Handling with Claudette Chat Source: https://claudette.answer.ai/ Demonstrates how to process images using the Claudette library. Images are read as bytes and can be passed directly to the `Chat` object along with text prompts. The library handles the image data as part of the input tokens. ```python from claudette.core import Chat from pathlib import Path # Assume 'model' is a pre-configured model identifier # model = "claude-sonnet-4-20250514" fn = Path('samples/puppy.jpg') chat = Chat(model) # Read image file as bytes img = fn.read_bytes() # Prompting with image and text # chat([img, "In brief, what color flowers are in this image?"]) # Expected output: # The flowers in this image are purple. # Example of checking token usage: # chat.use # In: 110; Out: 11; Cache create: 0; Cache read: 0; Total Tokens: 121; Search: 0 ``` -------------------------------- ### Claudette Text Editor Tool Commands Source: https://claudette.answer.ai/ Lists the operations supported by the Text Editor Tool, including viewing file/directory contents, creating new files, inserting text, and replacing text within files. ```APIDOC Text Editor Tool Commands: - view: View file or directory contents. - Usage Example: `{'command': 'view', 'path': '.'}` - create: Create new files. - insert: Insert text at specific line numbers. - replace: Replace text within files. ``` -------------------------------- ### Claudette Text Editor Tool Configuration Source: https://claudette.answer.ai/ Details the configuration for Claudette's Text Editor Tool, highlighting its schema-less nature, type identifiers, and the requirement for a dispatcher function. ```APIDOC Text Editor Tool: - Schema-less: Configuration provided, not a schema. - Type Identifier: Uses specific identifiers like "text_editor_20250124". - Dispatcher Function: Requires implementation (e.g., `str_replace_based_edit_tool` in Claudette). - Commands: Routes view, create, insert, and replace operations through a single dispatcher. ``` -------------------------------- ### Sherlock Domains Python SDK Core Concepts & Methods Source: https://context7_llms Details the core concepts and key methods of the Sherlock Domains Python SDK. It covers initialization, authentication, domain management, contact information handling, and DNS record management. ```Python # Sherlock Domains Python SDK ## Core Concepts - The SDK provides a `Sherlock` class that handles authentication and API interactions - Uses Ed25519 keypairs for authentication - Supports domain search, purchase, and DNS management - Handles contact information required by ICANN - Supports credit card and Lightning Network payments ## Key Methods ### Authentication & Setup - `Sherlock(priv='')` - Initialize client with optional private key - `me()` - Get authenticated user information ### Domain Management - `search(q)` - Search for available domains - `domains()` - List owned domains - `purchase_domain(sid, domain, payment_method='credit_card')` - Purchase a domain ### Contact Information - `set_contact_information(first_name, last_name, email, address, city, state, postal_code, country)` - Set ICANN contact info - `get_contact_information()` - Get current contact information ### DNS Management - `dns_records(domain_id)` - Get DNS records for a domain - `create_dns(domain_id, type, name, value, ttl)` - Create DNS record - `update_dns(domain_id, record_id, type, name, value, ttl)` - Update DNS record - `delete_dns(domain_id, record_id)` - Delete DNS record ``` -------------------------------- ### Amazon Bedrock Anthropic Models Source: https://claudette.answer.ai/ Lists available Anthropic models through Amazon Bedrock. These models can be accessed via the `AnthropicBedrock` provider. ```Python [ 'anthropic.claude-sonnet-4-20250514-v1:0', 'claude-3-5-haiku-20241022', 'claude-3-7-sonnet-20250219', 'anthropic.claude-3-opus-20240229-v1:0', 'anthropic.claude-3-5-sonnet-20241022-v2:0' ] ``` -------------------------------- ### JavaScript: Select and Highlight Code Lines Source: https://claudette.answer.ai/ Handles the selection and visual highlighting of specific code lines associated with annotations. It dynamically creates and positions highlight elements within the code container and its gutter based on the selected annotation's target cell and lines. Dependencies include DOM manipulation methods and CSS styling for positioning. ```javascript const selectorForAnnotation = ( cell, annotation) => { let cellAttr = 'data-code-cell="' + cell + '"'; let lineAttr = 'data-code-annotation="' + annotation + '"'; const selector = 'span\[' + cellAttr + '\]\[' + lineAttr + '\]'; return selector; } const selectCodeLines = (annoteEl) => { const doc = window.document; const targetCell = annoteEl.getAttribute("data-target-cell"); const targetAnnotation = annoteEl.getAttribute("data-target-annotation"); const annoteSpan = window.document.querySelector(selectorForAnnotation(targetCell, targetAnnotation)); const lines = annoteSpan.getAttribute("data-code-lines").split(","); const lineIds = lines.map((line) => { return targetCell + "-" + line; }); let top = null; let height = null; let parent = null; if (lineIds.length > 0) { //compute the position of the single el (top and bottom and make a div) const el = window.document.getElementById(lineIds[0]); top = el.offsetTop; height = el.offsetHeight; parent = el.parentElement.parentElement; if (lineIds.length > 1) { const lastEl = window.document.getElementById(lineIds[lineIds.length - 1]); const bottom = lastEl.offsetTop + lastEl.offsetHeight; height = bottom - top; } if (top !== null && height !== null && parent !== null) { // cook up a div (if necessary) and position it let div = window.document.getElementById("code-annotation-line-highlight"); if (div === null) { div = window.document.createElement("div"); div.setAttribute("id", "code-annotation-line-highlight"); div.style.position = 'absolute'; parent.appendChild(div); } div.style.top = top - 2 + "px"; div.style.height = height + 4 + "px"; div.style.left = 0; let gutterDiv = window.document.getElementById("code-annotation-line-highlight-gutter"); if (gutterDiv === null) { gutterDiv = window.document.createElement("div"); gutterDiv.setAttribute("id", "code-annotation-line-highlight-gutter"); gutterDiv.style.position = 'absolute'; const codeCell = window.document.getElementById(targetCell); const gutter = codeCell.querySelector('.code-annotation-gutter'); gutter.appendChild(gutterDiv); } gutterDiv.style.top = top - 2 + "px"; gutterDiv.style.height = height + 4 + "px"; } selectedAnnoteEl = annoteEl; } }; const unselectCodeLines = () => { const elementsIds = ["code-annotation-line-highlight", "code-annotation-line-highlight-gutter"]; elementsIds.forEach((elId) => { const div = window.document.getElementById(elId); if (div) { div.remove(); } }); selectedAnnoteEl = undefined; }; ``` -------------------------------- ### Sherlock Domains TypeScript SDK - Agent Integration Source: https://context7_llms Shows how to integrate the Sherlock Domains TypeScript SDK with AI agents by utilizing the `asTools()` method. This method exposes SDK functionalities as tools with Zod schemas for LLM function calling. ```typescript const sherlock = new Sherlock() const tools = sherlock.asTools() // Returns: me, setContactInformation, getContactInformation, searchDomains, // purchaseDomain, listDomains, getDnsRecords, createDnsRecord, // updateDnsRecord, deleteDnsRecord ``` -------------------------------- ### Ollama Integration for Local LLM Domain Management Source: https://context7_llms Illustrates setting up Sherlock with a local Ollama endpoint for LLM-powered domain management, using the OpenAI client configured for a local base URL. ```python import openai from cosette import Chat, Client as CosetteClient from sherlock.core import Sherlock # Initialize with local Ollama endpoint cli = openai.OpenAI(base_url="http://localhost:11434/v1", api_key='not-required') sherlock = Sherlock() # Create chat with tools chat = Chat(cli=cosette_client, sp=system_prompt, tools=sherlock.as_tools()) ``` -------------------------------- ### Cache Read Performance Source: https://claudette.answer.ai/ Demonstrates how context tokens are read from cache, significantly reducing input token count for subsequent interactions. This highlights efficient context management in LLM interactions. ```python print(r.usage) Usage(cache_creation_input_tokens=0, cache_read_input_tokens=9287, input_tokens=241, output_tokens=374, server_tool_use=None, service_tier='standard') ``` -------------------------------- ### Extended Thinking Feature Source: https://claudette.answer.ai/ Explains the 'extended thinking' feature for enhanced AI reasoning. It details how to enable it using `maxthinktok`, its automatic temperature setting, incompatibilities, and how thinking tokens contribute to usage. ```APIDOC Extended Thinking Claude >=3.7 Sonnet and Opus have enhanced reasoning capabilities through [extended thinking](https://docs.anthropic.com/en/docs/build-with-claude/extended-thinking). This feature allows Claude to think through complex problems step-by-step, making its reasoning process transparent and its final answers more reliable. To enable extended thinking, simply specify the number of thinking tokens using the `maxthinktok` parameter when making a call to Chat. The thinking process will appear in a collapsible section in the response. Some important notes about extended thinking: * Only available with select models * Automatically sets `temperature=1` when enabled (required for thinking to work) * Cannot be used with `prefill` (these features are incompatible) * Thinking is presented in a separate collapsible block in the response * The thinking tokens count toward your usage but help with complex reasoning ```