mirror of
https://github.com/anthropics/claude-cookbooks.git
synced 2025-10-06 01:00:28 +03:00
322 lines
12 KiB
Plaintext
322 lines
12 KiB
Plaintext
{
|
|
"cells": [
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 1,
|
|
"id": "94449849",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"data": {
|
|
"text/plain": [
|
|
"True"
|
|
]
|
|
},
|
|
"execution_count": 1,
|
|
"metadata": {},
|
|
"output_type": "execute_result"
|
|
}
|
|
],
|
|
"source": [
|
|
"from dotenv import load_dotenv\n",
|
|
"from utils.agent_visualizer import print_activity\n",
|
|
"\n",
|
|
"from claude_code_sdk import ClaudeCodeOptions, ClaudeSDKClient, query\n",
|
|
"\n",
|
|
"load_dotenv()"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "0d4a77a4",
|
|
"metadata": {},
|
|
"source": [
|
|
"# 00 - The One-Liner Research Agent\n",
|
|
"\n",
|
|
"PREFACE: We highly recommend reading [Building effective agents](https://www.anthropic.com/engineering/building-effective-agents) or [How we built our multi-agent research system](https://www.anthropic.com/engineering/built-multi-agent-research-system) in case you haven't. They are great reads and we will assume some basic understanding of agents! \n",
|
|
"\n",
|
|
"In this notebook we build our own (re)search agent, which is inherently a great use-case because of a few reasons:\n",
|
|
"- The input to our system is not sufficient to produce an output, meaning there needs to be interaction with external systems (e.g., the internet)\n",
|
|
"- There is no predefined workflow we can use since it is unclear what the agent will discover during its research\n",
|
|
"\n",
|
|
"Instead, a research agent requires the flexibility to explore unexpected leads and change direction based on what it finds. In its simplest form, a research agent can be an agent that simply searches the internet and summarizes it for you. \n",
|
|
"\n",
|
|
"Below, we'll implement a basic research agent with just a few lines of code. We provide Claude with exactly one tool which the Claude Code SDK contains straight out of the box: [web search tool](https://docs.claude.com/en/docs/agents-and-tools/tool-use/web-search-tool). \n",
|
|
"\n",
|
|
"> Check [here](https://docs.claude.com/en/docs/claude-code/settings#tools-available-to-claude) for a list of Claude Code's readily available tools"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 2,
|
|
"id": "b00890fb",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: WebSearch()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"messages = []\n",
|
|
"async for msg in query(\n",
|
|
" prompt=\"Research the latest trends in AI agents and give me a brief summary\",\n",
|
|
" options=ClaudeCodeOptions(model=\"claude-sonnet-4-20250514\", allowed_tools=[\"WebSearch\"]),\n",
|
|
"):\n",
|
|
" print_activity(msg)\n",
|
|
" messages.append(msg)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "293437f4",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"print(\n",
|
|
" f\"\\nResult:\\n{messages[-1].result if hasattr(messages[-1], 'result') and messages[-1].result else messages[-2].content[0].text}\"\n",
|
|
")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "6b888772",
|
|
"metadata": {},
|
|
"source": [
|
|
"And that's all it takes! Just like that we have a research agent that can go and browse the web to answer (to the best of its ability, at least) any question you throw at it.\n",
|
|
"\n",
|
|
"Note that in our query we provided the argument `options`. Here we define the configuration, the capabilities and limitations of our agent. For example, we provide our agent with the ability to search the web by passing ```allowed_tool=[\"WebSearch\"]```.\n",
|
|
"\n",
|
|
"More specifically, `allowed_tools` is a list of tools that Claude will be able to use without any approvals. The rest of the tools are still available, but Claude will ask for approval to use them. That said, certain tools like `Read` and other base read-only tools are always allowed. If you want any tool to be removed from Claude's context, add it to `disallowed_tools` instead.\n",
|
|
"\n",
|
|
"Now, to more closely inspect the actions our agent took, we have provided the ```visualize_conversation``` function."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "1d7c6d90",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from utils.agent_visualizer import visualize_conversation\n",
|
|
"\n",
|
|
"visualize_conversation(messages)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "22426729",
|
|
"metadata": {},
|
|
"source": [
|
|
"### Supercharging our agent\n",
|
|
"\n",
|
|
"So far, we have laid out a very simple (maybe naive) implementation to illustrate how you can start leveraging the SDK to build a research agent. However, there are various ways we can improve our agent to turn it production ready. Let's cover a few of them:\n",
|
|
"\n",
|
|
"1. Notice how before we only sent one query? In many systems, a human will look at the output of the system, potentially assigning a follow up task. Just like text completions, if we want to send multiple queries to the agent (e.g., 1. analyze abc, 2. make xyz based on your analysis) we would have to copy over the entire analysis context in our second query. Instead, we can **[use the ClaudeSDKClient](https://docs.claude.com/en/docs/claude-code/sdk/sdk-python#1-the-claudesdkclient-class-recommended)** to maintain the conversation context for us.\n",
|
|
"\n",
|
|
"2. Another great way of steering the system is **providing a system prompt**, akin to a system prompt used for text completions. To learn how to write a good system prompt for a research agent, we recommend looking [here](https://github.com/anthropics/anthropic-cookbook/tree/main/patterns/agents/prompts).\n",
|
|
"\n",
|
|
"3. **Leveraging the `Read` tool** to enable multimodal input. This tool allows Claude to analyze charts, infographics, and complex system diagrams."
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 5,
|
|
"id": "fa4c4d8f",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: Read()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: Bash()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: Read()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n",
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: WebSearch()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"messages = []\n",
|
|
"async with ClaudeSDKClient(\n",
|
|
" options=ClaudeCodeOptions(\n",
|
|
" model=\"claude-sonnet-4-20250514\",\n",
|
|
" cwd=\"research_agent\",\n",
|
|
" system_prompt=\"You are a research agent specialized in AI\",\n",
|
|
" allowed_tools=[\"WebSearch\", \"Read\"],\n",
|
|
" )\n",
|
|
") as research_agent:\n",
|
|
" await research_agent.query(\"Analyze the chart in research_agent/projects_claude.png\")\n",
|
|
" async for msg in research_agent.receive_response():\n",
|
|
" print_activity(msg)\n",
|
|
" messages.append(msg)\n",
|
|
"\n",
|
|
" await research_agent.query(\"Use a single websearch to investigate the insights from the chart.\")\n",
|
|
" async for msg in research_agent.receive_response():\n",
|
|
" print_activity(msg)\n",
|
|
" messages.append(msg)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "7971eae4-3ff1-48d8-99ef-fecca7332163",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"visualize_conversation(messages)"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "38256581",
|
|
"metadata": {},
|
|
"source": [
|
|
"### The Research Agent leaves Jupyter\n",
|
|
"\n",
|
|
"Finally, to be able to use the agent outside our notebook, we must put it in a Python script. A lightweight implementation of our research agent can be found in `research_agent/agent.py`. We define three functions:\n",
|
|
"- `print_activity()` - Shows what the agent is doing in real-time\n",
|
|
"- `get_activity_text()` - Extracts activity text for custom handlers\n",
|
|
"- `send_query()` - Main function for sending and handlingqueries with built-in activity display\n",
|
|
"\n",
|
|
"This agent can now be used in any Python script!"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "e220b5c7-463b-4171-b687-b1ec974958de",
|
|
"metadata": {},
|
|
"source": [
|
|
"First an example to test a one-off query to the agent:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "3c2ca449-7a36-4b67-af47-fdb68fb3e36b",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"from research_agent.agent import send_query\n",
|
|
"\n",
|
|
"result = await send_query(\"What is the Claude Code SDK? Only do one websearch and be concise\")\n",
|
|
"print(f\"\\nResult: {result}\\n\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "466155ec-9f54-49d4-83cb-00032b077147",
|
|
"metadata": {},
|
|
"source": [
|
|
"Now we test out a multi-turn conversation that reuses the same conversation:"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": 8,
|
|
"id": "38ba1eda",
|
|
"metadata": {},
|
|
"outputs": [
|
|
{
|
|
"name": "stdout",
|
|
"output_type": "stream",
|
|
"text": [
|
|
"🤖 Thinking...\n",
|
|
"🤖 Using: WebSearch()\n",
|
|
"✓ Tool completed\n",
|
|
"🤖 Thinking...\n",
|
|
"\n",
|
|
"-----\n",
|
|
"\n",
|
|
"Initial research: Anthropic is an AI safety and research company founded in 2021 by former OpenAI researchers, including siblings Dario and Daniela Amodei. The company develops Claude, a family of large language models (LLMs) designed to be helpful, harmless, and honest.\n",
|
|
"\n",
|
|
"**Key points:**\n",
|
|
"- **Mission**: Build reliable, interpretable, and steerable AI systems with a focus on AI safety\n",
|
|
"- **Main product**: Claude AI assistant (which you're currently using!)\n",
|
|
"- **Structure**: Public benefit corporation balancing profit with humanity's long-term benefit\n",
|
|
"- **Funding**: Backed by major investments from Amazon ($8B total) and Google ($2B)\n",
|
|
"- **Focus areas**: AI safety, natural language processing, human feedback, and responsible AI development\n",
|
|
"\n",
|
|
"Anthropic positions itself as a \"safety-first\" AI lab, emphasizing the responsible development of AI systems to serve humanity's long-term well-being.\n",
|
|
"\n"
|
|
]
|
|
}
|
|
],
|
|
"source": [
|
|
"result1 = await send_query(\"What is Anthropic? Only do one websearch and be concise\")\n",
|
|
"print(f\"\\n-----\\n\\nInitial research: {result1}\\n\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "code",
|
|
"execution_count": null,
|
|
"id": "36931a9e",
|
|
"metadata": {},
|
|
"outputs": [],
|
|
"source": [
|
|
"# Continue the conversation to dig deeper by setting continue_conversation=True\n",
|
|
"result2 = await send_query(\n",
|
|
" \"What are some of their products?\",\n",
|
|
" continue_conversation=True,\n",
|
|
")\n",
|
|
"print(f\"\\n-----\\n\\nFollow-up: {result2}\\n\")"
|
|
]
|
|
},
|
|
{
|
|
"cell_type": "markdown",
|
|
"id": "5344587c",
|
|
"metadata": {},
|
|
"source": [
|
|
"## Conclusion\n",
|
|
"\n",
|
|
"We've demonstrated how the Claude Code SDK enables you to build a functional research agent in just a few lines of code. By leveraging the built-in WebSearch tool, we created an agent capable of autonomous information gathering and synthesis. We also explored how the\n",
|
|
"ClaudeSDKClient maintains conversation context across multiple queries and how to incorporate multimodal capabilities through the Read tool.\n",
|
|
"\n",
|
|
"This foundation in basic agentic workflows prepares you for more sophisticated implementations. In the next notebook, we'll advance to building a Chief of Staff agent that coordinates multiple specialized subagents, implements custom output styles for different\n",
|
|
"stakeholders, and uses hooks for governance and compliance tracking.\n",
|
|
"\n",
|
|
"Next: [01_The_chief_of_staff_agent.ipynb](01_The_chief_of_staff_agent.ipynb) - Learn how to orchestrate complex multi-agent systems with enterprise-grade features.\n"
|
|
]
|
|
}
|
|
],
|
|
"metadata": {
|
|
"kernelspec": {
|
|
"display_name": "Python (cc-sdk-tutorial)",
|
|
"language": "python",
|
|
"name": "cc-sdk-tutorial"
|
|
},
|
|
"language_info": {
|
|
"codemirror_mode": {
|
|
"name": "ipython",
|
|
"version": 3
|
|
},
|
|
"file_extension": ".py",
|
|
"mimetype": "text/x-python",
|
|
"name": "python",
|
|
"nbconvert_exporter": "python",
|
|
"pygments_lexer": "ipython3",
|
|
"version": "3.11.13"
|
|
}
|
|
},
|
|
"nbformat": 4,
|
|
"nbformat_minor": 5
|
|
}
|