### Installing MCP Server for Claude Desktop
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Command to install an MCP server, making it available for use with Claude Desktop by adding it to the application's configuration.
```bash
mcp install server.py
```
--------------------------------
### Install Instructor
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/04-structured-output/Instructor/README.md
Installs the Instructor library using pip. This is the primary method for setting up the library in a Python environment.
```bash
pip install -U instructor
```
--------------------------------
### Direct Execution of MCP Server
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Demonstrates two methods for running an MCP server directly: as a standard Python script or using the UV ASGI server for potentially better performance.
```bash
# Method 1: Running as a Python script
python server.py
# Method 2: Using UV (recommended)
uv run server.py
```
--------------------------------
### Install Dependencies
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/knowledge/docling/README.md
Installs the necessary Python packages for the project using pip. Ensure you have Python and pip installed.
```bash
pip install -r requirements.txt
```
--------------------------------
### Python MCP Server with a Tool
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Defines a simple MCP server named 'DemoServer' with a 'say_hello' tool that greets a given name. This code snippet is the core of the server-side implementation.
```python
from mcp.server.fastmcp import FastMCP
# Create an MCP server
mcp = FastMCP("DemoServer")
# Simple tool
@mcp.tool()
def say_hello(name: str) -> str:
"""Say hello to someone
Args:
name: The person's name to greet
"""
return f"Hello, {name}! Nice to meet you."
# Run the server
if __name__ == "__main__":
mcp.run()
```
--------------------------------
### New Project Setup and Git Integration
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Outlines a typical new project workflow including initializing the project with UV, adding dependencies (both regular and development), setting up environment variables, initializing Git, and creating a remote repository on GitHub.
```bash
uv init my-project
cd my-project
# Add dependencies
uv add openai python-dotenv fastapi
uv add --dev ipykernel
# Set up environment variables
echo "API_KEY=your-key" > .env
# Git initialization and commit
git init
git add .
git commit -m "Initial commit"
# Create remote GitHub repository
gh repo create my-project --private --source=. --remote=origin --push
```
--------------------------------
### Python MCP Client using Standard I/O
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
A Python client implementation that connects to an MCP server using the standard input/output (stdio) transport. It demonstrates initializing a session, listing tools, and calling a tool.
```python
import asyncio
import nest_asyncio
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def main():
# Define server parameters
server_params = StdioServerParameters(
command="python", # The command to run your server
args=["server.py"], # Arguments to the command
)
# Connect to the server
async with stdio_client(server_params) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Install MCP Dependencies
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/README.md
Installs the necessary dependencies for the MCP Python SDK using either uv or pip. Ensure you have a requirements.txt file in your project directory.
```bash
# Using uv (recommended)
uv pip install -r requirements.txt
# Or using pip
pip install -r requirements.txt
```
--------------------------------
### Running MCP Server with MCP Inspector
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Command to run an MCP server in development mode, connecting it to the MCP Inspector for interactive testing and debugging.
```bash
mcp dev server.py
```
--------------------------------
### Initialize and Run a New Python Project with UV
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Demonstrates the basic workflow for starting a new Python project using UV. This includes initializing the project, adding dependencies, and running a script within the project's environment.
```bash
uv init my-ai-app
cd my-ai-app
# Add dependencies
uv add openai fastapi
# Run a script
uv run hello.py
```
--------------------------------
### Project Dependencies
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/agents/building-blocks/requirements.txt
Lists the required Python packages and their versions for the AI Cookbook project. These are essential for interacting with AI models and making HTTP requests.
```python
openai==1.97.1
requests==2.32.4
```
--------------------------------
### Python Function Calling Example
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/04-structured-output/README.md
Demonstrates how to use function calling with OpenAI's chat models. It defines a function, sets up messages, and makes a call to the chat completions API to get a tool call response.
```python
query = "Hi there, I have a question about my bill. Can you help me?"
function_name = "chat"
tools = [
{
"type": "function",
"function": {
"name": function_name,
"description": f"Function to respond to a customer query.",
"parameters": {
"type": "object",
"properties": {
"content": {
"type": "string",
"description": "Your reply that we send to the customer.",
},
"category": {
"type": "string",
"enum": ["general", "order", "billing"],
"description": "Category of the ticket.",
},
},
"required": ["content", "category"],
},
},
}
]
messages = [
{
"role": "system",
"content": "You're a helpful customer care assistant that can classify incoming messages and create a response.",
},
{
"role": "user",
"content": query,
},
]
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
tools=tools,
tool_choice={"type": "function", "function": {"name": function_name}},
)
tool_call = response.choices[0].message.tool_calls[0]
type(tool_call) # ChatCompletionMessageToolCall
function_args = json.loads(tool_call.function.arguments)
type(function_args) # dict
```
--------------------------------
### Mem0 Configuration Example
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/knowledge/mem0/README.md
Demonstrates a complete configuration for Mem0, specifying providers and settings for vector stores, language models, embedders, and graph stores. It also shows how to initialize the Memory object from this configuration.
```python
config = {
"vector_store": {
"provider": "qdrant",
"config": {"host": "localhost", "port": 6333},
},
"llm": {
"provider": "openai",
"config": {"api_key": "your-api-key", "model": "gpt-4"},
},
"embedder": {
"provider": "openai",
"config": {"api_key": "your-api-key", "model": "text-embedding-3-small"},
},
"graph_store": {
"provider": "neo4j",
"config": {
"url": "neo4j+s://your-instance",
"username": "neo4j",
"password": "password",
},
},
"history_db_path": "/path/to/history.db",
"version": "v1.1",
"custom_fact_extraction_prompt": "Optional custom prompt for fact extraction for memory",
"custom_update_memory_prompt": "Optional custom prompt for update memory",
}
# Initialize Memory with configuration
# from mem0 import Memory
# m = Memory.from_config(config)
```
--------------------------------
### Essential UV Commands Overview
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Provides a quick reference for the most frequently used UV commands, covering project setup, dependency management, running code, Python version management, temporary tool execution, and direct pip replacements.
```bash
# Project setup
uv init myproject
uv add requests
uv remove requests
uv sync
# Running code
uv run script.py
uv run pytest
# Python management
uv python install 3.12
uv python pin 3.12
# Tool usage
uvx black .
uv tool install ruff
# Package management
uv pip install requests
uv pip install -r requirements.txt
```
--------------------------------
### Connect with Streamable HTTP
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Demonstrates how to connect to an MCP server using the Streamable HTTP transport in Python. This method is recommended for production deployments due to its performance and scalability benefits. It establishes a connection, initializes the session, lists available tools, and calls a tool.
```python
import asyncio
import nest_asyncio
from mcp import ClientSession
from mcp.client.streamable_http import streamablehttp_client
async def main():
# Connect to the server using Streamable HTTP
async with streamablehttp_client("http://localhost:8050/mcp") as (read_stream, write_stream, get_session_id):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### MCP CLI Development Tools
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/README.md
Provides commands for developing and testing MCP servers using the MCP CLI. These tools include a development server, installation utility, and direct server execution.
```bash
# Test a server with the MCP Inspector
mcp dev server.py
# Install a server in Claude Desktop
mcp install server.py
# Run a server directly
mcp run server.py
```
--------------------------------
### MCP Transport Comparison
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
A comparison table outlining the key differences between SSE (Server-Sent Events) transport and the newer Streamable HTTP transport for MCP communication. It highlights differences in endpoints, return values, stream handling, and recommended usage.
```apidoc
MCP Transport Comparison:
| SSE Transport | Streamable HTTP Transport |
|---------------------|---------------------------|
| `/sse` endpoint | `/mcp` endpoint |
| Returns 2 values: `(read, write)` | Returns 3 values: `(read, write, get_session_id)` |
| Separate HTTP + SSE streams | Unified HTTP streaming |
| Good for development| **Recommended for production** |
```
--------------------------------
### Basic Structured Output with Instructor
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/04-structured-output/Instructor/README.md
Demonstrates how to use Instructor to get structured data from an LLM. It defines a Pydantic model for the output and uses the patched OpenAI client to create a completion, extracting specific fields from the response.
```python
import instructor
from pydantic import BaseModel
from openai import OpenAI
# Define your desired output structure
class UserInfo(BaseModel):
name: str
age: int
# Patch the OpenAI client
client = instructor.from_openai(OpenAI())
# Extract structured data from natural language
user_info = client.chat.completions.create(
model="gpt-3.5-turbo",
response_model=UserInfo,
messages=[{"role": "user", "content": "John Doe is 30 years old."}]
)
print(user_info.name)
print(user_info.age)
```
--------------------------------
### Python MCP Client using Server-Sent Events (SSE)
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
A Python client implementation that connects to an MCP server using the Server-Sent Events (SSE) transport over HTTP. It shows how to establish a connection, manage the session, and interact with server tools.
```python
import asyncio
import nest_asyncio
from mcp import ClientSession
from mcp.client.sse import sse_client
async def main():
# Connect to the server using SSE
async with sse_client("http://localhost:8050/sse") as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the connection
await session.initialize()
# List available tools
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
# Call our calculator tool
result = await session.call_tool("add", arguments={"a": 2, "b": 3})
print(f"2 + 3 = {result.content[0].text}")
if __name__ == "__main__":
asyncio.run(main())
```
--------------------------------
### Python MCP Server with SSE Transport
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/3-simple-server-setup/README.md
Configures an MCP server to use Server-Sent Events (SSE) transport, specifying the host and port for HTTP-based communication. This is necessary for exposing the server over a traditional web port.
```python
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("MyServer", host="127.0.0.1", port=8050)
# Add your tools and resources here...
if __name__ == "__main__":
# Run with SSE transport on port 8000
mcp.run(transport="sse")
```
--------------------------------
### UV Python Version Management
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Details commands for managing Python versions with UV, which acts as a replacement for tools like pyenv. This includes installing specific Python versions, pinning a project to a version, and listing available versions.
```bash
# Install Python versions
uv python install 3.12
uv python install 3.11 3.12 3.13
# Pin project to a specific version
uv python pin 3.12
# List available versions
uv python list
```
--------------------------------
### MCP Lifespan Object Usage
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/7-lifecycle-management/README.md
Provides an example of creating and using an asynchronous context manager (lifespan object) to manage application resources like database connections within an MCP server.
```python
from contextlib import asynccontextmanager
from collections.abc import AsyncIterator
from dataclasses import dataclass
from mcp.server.fastmcp import Context, FastMCP
# Define a type-safe context class
@dataclass
class AppContext:
db: Database # Replace with your actual resource type
# Create the lifespan context manager
@asynccontextmanager
async def app_lifespan(server: FastMCP) -> AsyncIterator[AppContext]:
# Initialize resources on startup
db = await Database.connect()
try:
# Make resources available during operation
yield AppContext(db=db)
finally:
# Clean up resources on shutdown
await db.disconnect())
# Create the MCP server with the lifespan
mcp = FastMCP("My App", lifespan=app_lifespan)
# Use the lifespan context in tools
@mcp.tool()
def query_db(ctx: Context) -> str:
"""Tool that uses initialized resources"""
db = ctx.request_context.lifespan_context.db
return db.query()
```
--------------------------------
### MCP Client Initialization
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/7-lifecycle-management/README.md
Demonstrates the initialization of an MCP client connection using context managers for establishing and managing the session.
```python
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Initialize the connection
await session.initialize()
```
--------------------------------
### MCP Tool Discovery
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/7-lifecycle-management/README.md
Shows how an MCP client can discover available tools exposed by an MCP server and print their names and descriptions.
```python
# Tool discovery example
tools_result = await session.list_tools()
print("Available tools:")
for tool in tools_result.tools:
print(f" - {tool.name}: {tool.description}")
```
--------------------------------
### Working with Existing Projects using UV
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Explains how to use UV to manage dependencies for an existing project, including cloning a repository and synchronizing dependencies based on a lock file. It also shows how to exclude development dependencies for production.
```bash
git clone https://github.com/org/project.git
cd project
# Install exact versions from lockfile
uv sync
# Install for production (exclude dev dependencies)
uv sync --no-dev
```
--------------------------------
### LLM Request with Confidence Score Validation
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/04-structured-output/Instructor/README.md
Shows how to make a request to an LLM using Instructor, specifying a `response_model` that includes confidence score validation. The system message can also guide the LLM on the expected range, though Pydantic validation is the primary enforcement.
```python
from instructor import Instructor
client = Instructor()
query = "What is the status of my order?"
reply = client.chat.completions.create(
model="gpt-3.5-turbo",
response_model=Reply,
max_retries=3,
messages=[
{
"role": "system",
"content": "You're a helpful customer care assistant that can classify incoming messages and create a response. Set confidence between 1-100.",
},
{"role": "user", "content": query},
],
)
```
--------------------------------
### Set Environment Variables
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/knowledge/docling/README.md
Creates a .env file to store sensitive information like API keys. This is crucial for authenticating with services like OpenAI.
```bash
OPENAI_API_KEY=your_api_key_here
```
--------------------------------
### Transport Mechanism Comparison Diagram
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/2-understanding-mcp/README.md
A Mermaid diagram illustrating the comparison between Stdio, SSE, and Streamable HTTP transport mechanisms for MCP clients and servers, including local and remote deployment scenarios.
```mermaid
flowchart LR
subgraph Stdio["Stdio Transport"]
Client1["MCP Client"]
Server1["MCP Server"]
end
subgraph SSE["SSE Transport"]
Client2["MCP Client"]
Server2["MCP Server"]
end
subgraph StreamableHTTP["Streamable HTTP Transport"]
Client3["MCP Client"]
Server3["MCP Server"]
end
subgraph Local["Local Deployment"]
Stdio
end
subgraph Remote["Remote Deployment"]
SSE
StreamableHTTP
end
Client1 -- stdin/stdout
(bidirectional) --> Server1
Client2 -- HTTP POST
(client to server) --> Server2
Server2 -- SSE
(server to client) --> Client2
Client3 -- Unified HTTP
(bidirectional streaming) --> Server3
style Client1 fill:#BBDEFB
style Server1 fill:#BBDEFB
style Client2 fill:#BBDEFB
style Server2 fill:#E1BEE7
style Client3 fill:#C8E6C9
style Server3 fill:#C8E6C9
```
--------------------------------
### Using JSON Mode for Structured Output
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/04-structured-output/README.md
This Python code snippet demonstrates how to use OpenAI's JSON mode to ensure the model's response is a valid JSON string. It includes setting the system prompt to guide the model's output format and parsing the response.
```python
query = "Hi there, I have a question about my bill. Can you help me?"
messages = [
{
"role": "system",
"content": """
You're a helpful customer care assistant that can classify incoming messages and create a response.
Always response in the following JSON format: {\"content\": , \"category\": }
Available categories: 'general', 'order', 'billing'
""",
},
{
"role": "user",
"content": query,
},
]
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=messages,
response_format={"type": "json_object"},
)
message = response.choices[0].message.content
type(message) # str
message_json = json.loads(message)
type(message_json) # dict
```
--------------------------------
### OpenAI Responses API Overview
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/05-responses/README.md
Provides an overview of the OpenAI Responses API, its relationship to Chat Completions, and its key new features. It also details available tools and migration advice.
```APIDOC
OpenAI Responses API:
Overview:
- Superset of Chat Completions API.
- Native support for web search.
- New 'developer' role.
- Improved reasoning support.
- Built-in file/vector search.
- Simplified conversation state management.
Available Tools:
- Web search: Integrate Internet data into responses.
- File search: Search uploaded files for context.
- Computer use: Enable agentic workflows controlling computer interfaces.
- Function calling: Allow models to call custom code.
Migration:
- New applications: Start with Responses API.
- Existing applications: Plan migration, test in parallel.
- No immediate urgency for Chat Completions users.
Resources:
- Official Documentation: https://platform.openai.com/docs/api-reference/responses
- Agent SDK: https://platform.openai.com/docs/guides/agents (replaces Swarm)
```
--------------------------------
### Prompt Chaining: Calendar Assistant Workflow
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/patterns/workflows/README.md
Demonstrates a 3-step prompt chain for a calendar assistant. It includes extraction, validation, parsing, and confirmation generation, with a gate check for validation.
```Mermaid
graph LR
A[User Input] --> B[LLM 1: Extract]
B --> C{Gate Check}
C -->|Pass| D[LLM 2: Parse Details]
C -->|Fail| E[Exit]
D --> F[LLM 3: Generate Confirmation]
F --> G[Final Output]
```
--------------------------------
### Tool Integration for AI Agents
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/agents/building-blocks/README.md
Depicts the workflow for integrating external tools with an LLM. It shows how an LLM can analyze a request, select an appropriate tool, execute it, and then format the result into a response.
```mermaid
graph LR
A[User Input] --> B[LLM Analyzes Request] --> C{Tool Needed?}
C -->|Yes| D[Select Tool] --> F[Execute Tool] --> G[Tool Result] --> H[LLM Formats Response]
C -->|No| E[Direct Response]
H --> I[Final Response]
E --> I
```
--------------------------------
### Troubleshooting Docker Commands
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/6-run-with-docker/README.md
Provides essential Docker commands for troubleshooting server connectivity issues. These commands help verify the server's running status, port mappings, and logs.
```bash
docker ps
docker logs
```
--------------------------------
### Project Dependencies
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/requirements.txt
Lists the core Python dependencies for the AI Cookbook project, including the OpenAI client, httpx for HTTP requests, ipykernel for Jupyter integration, and python-dotenv for environment variable management. The mcp[cli] dependency is also noted.
```shell
mcp[cli]==1.10.1openai==1.75.0
python-dotenv
ipykernel
httpx
```
--------------------------------
### Managing Dependency Groups with UV Commands
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/tools/uv-guide/README.md
Shows the command-line usage for adding dependencies to specific groups (like 'dev') and synchronizing the project's environment, including options to exclude development dependencies.
```bash
# Add dependencies to the 'dev' group
uv add --dev pytest black
# Install all dependencies
uv sync
# Install only production dependencies
uv sync --no-dev
```
--------------------------------
### MCP Tool Execution
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/7-lifecycle-management/README.md
Illustrates how an MCP client can execute a tool on the server, passing function name and arguments, and receiving the result.
```python
# Tool execution example
result = await session.call_tool(
tool_call.function.name,
arguments=json.loads(tool_call.function.arguments),
)
```
--------------------------------
### Mem0 Memory Addition Process
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/knowledge/mem0/README.md
Illustrates the internal process when calling `memory.add()`, detailing the steps involved in adding memories to the Mem0 system.
```python
# When you call memory.add(), here's what happens:
# 1. Fact Extraction: The system extracts key facts from the input conversation.
# 2. Memory Update Logic: It determines whether to ADD, UPDATE, or DELETE memories based on the new facts and existing knowledge.
# 3. Storage: Relevant memories are stored in the configured vector store and potentially a graph store.
```
--------------------------------
### Build Docker Image
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/6-run-with-docker/README.md
Builds the Docker image for the MCP server. This command creates a Docker image tagged as 'mcp-server' from the current directory's Dockerfile.
```bash
docker build -t mcp-server .
```
--------------------------------
### Run Client
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/6-run-with-docker/README.md
Executes the Python client script to connect to the running MCP server. The client interacts with the server, lists tools, and performs a calculation.
```python
python client.py
```
--------------------------------
### Docling Pipeline Execution Order
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/knowledge/docling/README.md
Provides the sequence of Python scripts to run for building and querying a document database using Docling. Each script performs a specific step in the RAG pipeline.
```python
python 1-extraction.py
python 2-chunking.py
python 3-embedding.py
python 4-search.py
streamlit run 5-chat.py
```
--------------------------------
### Python Dependencies for AI Cookbook
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/models/openai/requirements.txt
Lists the core Python packages required for the AI Cookbook project, focusing on OpenAI integration, data validation, and structured output.
```python
openai==1.66.2
openai-agents
pydantic
instructor
```
--------------------------------
### OpenAI Function Calling with MCP
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/4-openai-integration/README.md
Illustrates the process of integrating OpenAI's function calling capabilities with the Model Context Protocol (MCP). This involves registering MCP tools in a format understandable by OpenAI, allowing the model to select and execute these tools based on user queries.
```APIDOC
OpenAI Function Calling Integration:
- MCP Tool Registration:
- Converts MCP tools into OpenAI's function definition format.
- Function definition includes 'name', 'description', and 'parameters'.
- Parameters are defined with 'type', 'description', and 'enum' (if applicable).
- Tool Selection:
- OpenAI analyzes user queries to determine the most relevant tool.
- Considers tool descriptions and parameter requirements.
- Tool Execution:
- Upon selecting a tool, OpenAI requests its execution with specific arguments.
- The MCP client receives this request and forwards it to the MCP server.
- Response Handling:
- The MCP server executes the tool and returns the result.
- The result is passed back to OpenAI via the MCP client.
- OpenAI uses the tool's output to formulate a final response to the user.
Example Function Definition (Conceptual):
{
"name": "get_knowledge_base",
"description": "Retrieves Q&A pairs from the knowledge base.",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The user's question to find an answer for."
}
},
"required": ["query"]
}
}
```
--------------------------------
### MCP Server Implementation (Conceptual)
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/mcp/crash-course/4-openai-integration/README.md
A conceptual outline of an MCP server implementation, focusing on exposing a knowledge base tool. This server would handle requests from an MCP client, execute the specified tool (e.g., querying a JSON knowledge base), and return the results.
```python
import json
from mcp.server import Server
class KnowledgeBaseServer(Server):
def __init__(self, kb_path="data/kb.json"):
super().__init__()
self.kb_path = kb_path
with open(self.kb_path, 'r') as f:
self.knowledge_base = json.load(f)
def get_knowledge_base(self, query: str) -> str:
"""Retrieves an answer from the knowledge base based on the query."""
for item in self.knowledge_base:
if item['question'].lower() == query.lower():
return item['answer']
return "I couldn't find an answer for that question."
if __name__ == "__main__":
server = KnowledgeBaseServer()
server.run()
```
--------------------------------
### Parallelization: Calendar Assistant Workflow
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/patterns/workflows/README.md
Shows the parallelization pattern for a calendar assistant, implementing concurrent validation guardrails for calendar and security checks.
```Mermaid
graph LR
A[User Input] --> B[Calendar Check]
A --> C[Security Check]
B --> D{Aggregate}
C --> D
D -->|Valid| E[Continue]
D -->|Invalid| F[Exit]
```
--------------------------------
### Blog Writing Orchestrator Diagram
Source: https://github.com/daveebbelaar/ai-cookbook/blob/main/patterns/workflows/README.md
A Mermaid diagram illustrating the workflow of the blog writing orchestrator. It shows the flow from topic input through the orchestrator to the planning, writing, and review phases.
```mermaid
graph LR
A[Topic Input] --> B[Orchestrator]
B --> C[Planning Phase]
C --> D[Writing Phase]
D --> E[Review Phase]
style D fill:#f9f,stroke:#333,stroke-width:2px
```