### Install Dependencies with uv Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Installs project dependencies using the uv package manager. Ensure uv is installed and configured. ```bash uv sync ``` -------------------------------- ### Install langgraph-checkpoint-cloudflare-d1 Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langgraph-checkpoint-cloudflare-d1/README.md Install the package using pip. ```bash pip install -U langgraph-checkpoint-cloudflare-d1 ``` -------------------------------- ### Install Required Packages Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Installs necessary libraries for LangGraph, Cloudflare D1 checkpointer, and HTTP requests. Use this command in your environment. ```python %pip install -U requests httpx langgraph langgraph-checkpoint-cloudflare-d1 ``` -------------------------------- ### Install langgraph-checkpoint-cloudflare-d1 Package Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/README.md Install the langgraph-checkpoint-cloudflare-d1 package using pip. ```bash pip install langgraph-checkpoint-cloudflare-d1 ``` -------------------------------- ### Install langchain-cloudflare Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/README.md Install the package using pip. Ensure Cloudflare API credentials are set as environment variables. ```bash pip install -U langchain-cloudflare ``` -------------------------------- ### Install langmem-cloudflare-vectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langmem-cloudflare-vectorize/README.md Install the necessary packages for langmem, langgraph, and the Cloudflare integration. ```bash pip install -U langmem-cloudflare-vectorize langgraph langchain-cloudflare ``` -------------------------------- ### Install langchain-cloudflare Package Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/README.md Install the langchain-cloudflare package using pip. ```bash pip install langchain-cloudflare ``` -------------------------------- ### Install langmem-cloudflare-vectorize Package Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/README.md Install the langmem-cloudflare-vectorize package using pip. ```bash pip install langmem-cloudflare-vectorize ``` -------------------------------- ### Run Local Development Server Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Starts the local development server for the Cloudflare Worker using pywrangler. This command is used for testing and debugging the worker locally. ```bash uv run pywrangler dev ``` -------------------------------- ### Install Langchain Cloudflare Package Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Installs the `langchain-cloudflare` package for using Cloudflare WorkersAI models. This is optional if using other LLM providers. ```python %pip install -qU langchain-cloudflare ``` -------------------------------- ### Synchronous Cloudflare D1 Checkpointing Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langgraph-checkpoint-cloudflare-d1/README.md Initialize and use the synchronous CloudflareD1Saver for checkpoint operations. Ensure proper Cloudflare credentials and configuration are provided. The setup() method is idempotent. ```python from langgraph_checkpoint_cloudflare_d1 import CloudflareD1Saver # Cloudflare credentials account_id = "your-cloudflare-account-id" database_id = "your-d1-database-id" api_token = "your-cloudflare-api-token" # Configuration for checkpoint operations write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}} read_config = {"configurable": {"thread_id": "1"}} # Initialize the saver with proper credentials with CloudflareD1Saver( account_id=account_id, database_id=database_id, api_token=api_token ) as checkpointer: # Setup the database tables (idempotent operation) checkpointer.setup() # Sample checkpoint data checkpoint = { "v": 2, "ts": "2024-07-31T20:14:19.804150+00:00", "id": "1ef4f797-8335-6428-8001-8a1503f9b875", "channel_values": { "my_key": "meow", "node": "node" }, "channel_versions": { "__start__": 2, "my_key": 3, "start:node": 3, "node": 3 }, "versions_seen": { "__input__": {}, "__start__": { "__start__": 1 }, "node": { "start:node": 2 } }, "pending_sends": [], } # Store checkpoint checkpointer.put(write_config, checkpoint, {}, {}) # Load checkpoint loaded_checkpoint = checkpointer.get_tuple(read_config) # List checkpoints checkpoints = list(checkpointer.list(read_config)) ``` -------------------------------- ### Asynchronous Cloudflare D1 Checkpointing Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langgraph-checkpoint-cloudflare-d1/README.md Initialize and use the asynchronous AsyncCloudflareD1Saver for checkpoint operations. Ensure proper Cloudflare credentials and configuration are provided. Setup is automatic but can be called explicitly. ```python from langgraph_checkpoint_cloudflare_d1 import AsyncCloudflareD1Saver import asyncio async def main(): # Cloudflare credentials account_id = "your-cloudflare-account-id" database_id = "your-d1-database-id" api_token = "your-cloudflare-api-token" # Configuration for checkpoint operations write_config = {"configurable": {"thread_id": "1", "checkpoint_ns": ""}} read_config = {"configurable": {"thread_id": "1"}} # Initialize the async saver with proper credentials async with AsyncCloudflareD1Saver( account_id=account_id, database_id=database_id, api_token=api_token ) as checkpointer: # Sample checkpoint data checkpoint = { "v": 2, "ts": "2024-07-31T20:14:19.804150+00:00", "id": "1ef4f797-8335-6428-8001-8a1503f9b875", "channel_values": { "my_key": "meow", "node": "node" }, "channel_versions": { "__start__": 2, "my_key": 3, "start:node": 3, "node": 3 }, "versions_seen": { "__input__": {}, "__start__": { "__start__": 1 }, "node": { "start:node": 2 } }, "pending_sends": [], } # Setup happens automatically but can be called explicitly await checkpointer.setup() # Store checkpoint await checkpointer.put(write_config, checkpoint, {}, {}) # Load checkpoint loaded_checkpoint = await checkpointer.get_tuple(read_config) # List checkpoints checkpoints = [cp async for cp in checkpointer.list(read_config)] # For local execution if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Initialize CloudflareWorkersAIEmbeddings Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/README.md Instantiate CloudflareWorkersAIEmbeddings to generate embeddings. Specify the model name. Use the `embed_query` method to get embeddings for a given text. ```python from langchain_cloudflare.embeddings import CloudflareWorkersAIEmbeddings embeddings = CloudflareWorkersAIEmbeddings( model_name="@cf/baai/bge-base-en-v1.5" ) embeddings.embed_query("What is the meaning of life?") ``` -------------------------------- ### Define Model and Tools for the Graph Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Sets up a LangGraph agent with a specified LLM model and a tool for getting weather information. The `get_weather` tool is defined with literal types for cities. ```python from typing import Literal from langchain_core.tools import tool from langgraph.prebuilt import create_react_agent @tool def get_weather(city: Literal["nyc", "sf"]): """Use this to get weather information.""" if city == "nyc": return "It might be cloudy in nyc" elif city == "sf": return "It's always sunny in sf" else: raise AssertionError("Unknown city") tools = [get_weather] ``` -------------------------------- ### Initialize CloudflareVectorize with D1 Database ID and AI Token Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Initializes CloudflareVectorize when a D1 database ID is provided, but a global API token is not. It prioritizes service-specific tokens if available. This example shows providing the AI API token separately. ```python try: cfVect = CloudflareVectorize( embedding=embedder, account_id=cf_acct_id, # api_token=api_token, # (Optional if using service-specific token) ai_api_token=cf_ai_token, # (Optional if using global token) # d1_api_token=cf_d1_token, # (Optional if using global token) vectorize_api_token=cf_vectorize_token, # (Optional if using global token) d1_database_id=d1_database_id, # (Optional if not using D1) ) except Exception as e: print(str(e)) ``` -------------------------------- ### Get Vectorize Index Information Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Retrieves detailed information about a specific Vectorize index, including its dimensions and vector count. The `processedUpToMutation` field can track operation status. ```python r = cfVect.get_index_info(index_name=vectorize_index_name) print(r) ``` -------------------------------- ### Get Cloudflare D1 Database ID Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Retrieves the Cloudflare D1 Database ID from environment variables. This ID is necessary if you plan to store and retrieve raw values alongside embeddings using D1. ```python # provide the id of your D1 Database d1_database_id = os.getenv("CF_D1_DATABASE_ID") ``` -------------------------------- ### Define and Create Langgraph Agent with Memory Tools Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langmem-cloudflare-vectorize/README.md Create memory management and search tools, define a custom tool, and then construct a Langgraph agent using the initialized LLM, tools, and the Cloudflare Vectorize store for memory. ```python # Create memory tools manage_memory = create_manage_memory_tool( namespace=("memories",) ) search_memory = create_search_memory_tool( namespace=("memories",) ) @tool def get_weather(location: str): """Get the current weather for a location.""" if location.lower() in ["sf", "san francisco"]: return "It's 60 degrees and foggy in San Francisco." elif location.lower() in ["ny", "new york"]: return "It's 45 degrees and sunny in New York." else: return f"It's 75 degrees and partly cloudy in {location}." # Create the agent agent = create_react_agent( cloudflare_llm, tools=[ manage_memory, search_memory, ], store=agent_store, # This is how LangMem gets access to your store ) ``` -------------------------------- ### Chain Model with Prompt Template Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Chain a model with a prompt template for dynamic input and output languages. Ensure the 'llm' object is initialized before use. ```python from langchain_core.prompts import ChatPromptTemplate prompt = ChatPromptTemplate( [ ( "system", "You are a helpful assistant that translates {input_language} to {output_language}.", ), ("human", "{input}"), ] ) chain = prompt | llm chain.invoke( { "input_language": "English", "output_language": "German", "input": "I love programming.", } ) ``` -------------------------------- ### Initialize CloudflareVectorizeLangmemStore and LLM Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langmem-cloudflare-vectorize/README.md Set up the Cloudflare Vectorize store and a Cloudflare Workers AI language model for use with Langmem and Langgraph. Ensure your Cloudflare credentials and desired model are correctly configured. ```python from langmem_cloudflare_vectorize import CloudflareVectorizeLangmemStore from langchain_cloudflare.chat_models import ChatCloudflareWorkersAI from langmem import create_manage_memory_tool, create_search_memory_tool from langgraph.prebuilt import create_react_agent from langchain_core.tools import tool # Cloudflare credentials account_id = "your-cloudflare-account-id" vectorize_api_token = "your-vectorize-api-token" workers_ai_token = "your-workers-ai-api-token" # Create the langmem vectorize store agent_store = CloudflareVectorizeLangmemStore.with_cloudflare_embeddings( account_id=account_id, index_name="cool-vectorize-index-name", vectorize_api_token=vectorize_api_token, workers_ai_token=workers_ai_token, embedding_model="@cf/baai/bge-base-en-v1.5", dimensions=768 ) # Create the llm cloudflare_llm = ChatCloudflareWorkersAI( cloudflare_account_id=account_id, cloudflare_api_token=workers_ai_token, model="@cf/meta/llama-3.3-70b-instruct-fp8-fast" ) ``` -------------------------------- ### Asynchronously Create Metadata Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Asynchronously create metadata indexes for specified properties on multiple vectorstores. This allows for filtering and searching based on metadata fields. ```python async_requests = [ cfVect.acreate_metadata_index( property_name="section", index_type="string", index_name=vectorize_index_name1, wait=True, ), cfVect.acreate_metadata_index( property_name="section", index_type="string", index_name=vectorize_index_name2, wait=True, ), ] await asyncio.gather(*async_requests); ``` -------------------------------- ### Create Vectorstore from Documents Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Instantiate a Cloudflare Vectorize vectorstore directly from a list of documents using the `from_documents` method. Ensure all required parameters like account ID, index name, documents, and embedding model are provided. ```python cfVect = CloudflareVectorize.from_documents( account_id=cf_acct_id, index_name=vectorize_index_name, documents=texts, embedding=embedder, d1_database_id=d1_database_id, d1_api_token=cf_d1_token, vectorize_api_token=cf_vectorize_token, wait=True, ) ``` -------------------------------- ### Invoke Agent to Store and Retrieve Information Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langmem-cloudflare-vectorize/README.md Demonstrates invoking the agent to store user information using the 'manage_memory' tool and then recalling that information using the 'search_memory' tool. This showcases the memory persistence and retrieval capabilities. ```python config = {"configurable": {"thread_id": "test_session_1"}} response1 = agent.invoke( {"messages": [{"role": "user", "content": "Please remember this important information about me: My name is Sarah, I'm allergic to peanuts, and I love Italian food, especially pasta carbonara. Please use your manage_memory tool to store this."}]}, config ) print( "User: Please remember this important information about me: My name is Sarah, I'm allergic to peanuts, and I love Italian food, especially pasta carbonara. Please use your manage_memory tool to store this.") print(f"Agent: {response1['messages'][-1].content}") # Test 2: Try to recall the stored information print("\nCONVERSATION 2: THE MEMORY TEST") print("-" * 40) print("Testing if the agent remembers the stored information...") response2 = agent.invoke( {"messages": [{"role": "user", "content": "What do you remember about my dietary restrictions and food preferences? Please search your memory using search_memory tool."}]}, config ) print( "User: What do you remember about my dietary restrictions and food preferences? Please search your memory using search_memory tool.") print(f"Agent: {response2['messages'][-1].content}") # Test 3: Different topic, then back to memory print("\nšŸ“… CONVERSATION 3: Different topic") print("-" * 40) response3 = agent.invoke( {"messages": [{"role": "user", "content": "What's the weather like in San Francisco?"}]}, config ) print("User: What's the weather like in San Francisco?") print(f"Agent: {response3['messages'][-1].content}") response4 = agent.invoke( {"messages": [{"role": "user", "content": "What is my name and what am I allergic to?"}]}, config ) print( "User: What is my name and what am I allergic to?") print(f"Agent: {response4['messages'][-1].content}") ``` -------------------------------- ### Tool Calling Request Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Sends a POST request to the /tools endpoint to demonstrate tool calling. The request body should contain a JSON object with a 'message' field. ```bash curl -X POST http://localhost:8787/tools \ -H "Content-Type: application/json" \ -d '{"message": "What is the weather in San Francisco?"}' ``` -------------------------------- ### Initialize CloudflareVectorize with Embeddings and Credentials Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Creates an instance of the CloudflareVectorize class. This requires an embedding instance, account ID, and optionally, API tokens for Vectorize, D1, and WorkersAI. ```python cfVect = CloudflareVectorize( embedding=embedder, account_id=cf_acct_id, d1_api_token=cf_d1_token, # (Optional if using global token) vectorize_api_token=cf_vectorize_token, # (Optional if using global token) d1_database_id=d1_database_id, # (Optional if not using D1) ) ``` -------------------------------- ### Initialize ChatCloudflareWorkersAI Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/README.md Instantiate the ChatCloudflareWorkersAI class to use Cloudflare's chat models. Invoke the model with a prompt. ```python from langchain_cloudflare.chat_models import ChatCloudflareWorkersAI llm = ChatCloudflareWorkersAI() llm.invoke("Sing a ballad of LangChain.") ``` -------------------------------- ### Create D1 Database with Wrangler Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Creates a new D1 database named 'test-db'. This command is used to provision a new database instance for use with Cloudflare D1. ```bash npx wrangler d1 create test-db ``` -------------------------------- ### Initialize CloudflareVectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/README.md Instantiate CloudflareVectorize to use Cloudflare's Vectorize service. Pass an initialized embeddings object. Use `create_index` to set up a new vector store index. ```python from langchain_cloudflare.vectorstores import CloudflareVectorize vst = CloudflareVectorize( embedding=embeddings ) vst.create_index(index_name="my-cool-vectorstore") ``` -------------------------------- ### Asynchronously Create Multiple Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Asynchronously create multiple vectorstore indexes concurrently using `asyncio.gather`. This method is efficient for setting up multiple indexes simultaneously. ```python # depending on your notebook environment you might need to include these: # import nest_asyncio # nest_asyncio.apply() async_requests = [ cfVect.acreate_index(index_name=vectorize_index_name1), cfVect.acreate_index(index_name=vectorize_index_name2), ] res = await asyncio.gather(*async_requests); ``` -------------------------------- ### Configure Cloudflare Credentials Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Sets Cloudflare account ID and D1 API token from environment variables or prompts the user if not set. Ensure these are available before proceeding. ```python import getpass import os if not os.getenv("CF_ACCOUNT_ID"): os.environ["CF_ACCOUNT_ID"] = getpass.getpass("Enter your Cloudflare account ID: ") if not os.getenv("CF_D1_API_TOKEN"): os.environ["CF_D1_API_TOKEN"] = getpass.getpass( "Enter your Cloudflare D1 API token: " ) ``` -------------------------------- ### Initialize ChatOpenAI Model Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Initializes the ChatOpenAI model with a specific model name and temperature. This is an alternative to Cloudflare WorkersAI. ```python from langchain_openai import ChatOpenAI model = ChatOpenAI( model_name="gpt-4o-mini", temperature=0, ) ``` -------------------------------- ### Asynchronous Cloudflare D1 Checkpointer Usage Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Initializes the AsyncCloudflareD1Saver and creates a LangGraph agent with persistence. Asynchronously invokes the agent with a configuration specifying a thread ID. ```python from langgraph_checkpoint_cloudflare_d1 import AsyncCloudflareD1Saver checkpointer = AsyncCloudflareD1Saver() graph = create_react_agent(model, tools=tools, checkpointer=checkpointer) config = {"configurable": {"thread_id": "2"}} response = await graph.ainvoke( {"messages": [("human", "what's the weather in sf")]}, config ) ``` -------------------------------- ### Instantiate ChatCloudflareWorkersAI Model Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Instantiates the ChatCloudflareWorkersAI model with a specified model name, temperature, and max tokens. Other parameters can also be configured. ```python from langchain_cloudflare.chat_models import ChatCloudflareWorkersAI llm = ChatCloudflareWorkersAI( model="@cf/meta/llama-3.3-70b-instruct-fp8-fast", temperature=0, max_tokens=1024, # other params... ) ``` -------------------------------- ### List Vectorize Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Lists all Vectorize indexes in the account and filters them to show only those containing 'test-langchain' in their name. ```python indexes = cfVect.list_indexes() indexes = [x for x in indexes if "test-langchain" in x.get("name")] print(indexes) ``` -------------------------------- ### Load Documents with WikipediaLoader Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Loads documents about 'Cloudflare' using LangChain's WikipediaLoader, limiting to a maximum of 2 documents. ```python docs = WikipediaLoader(query="Cloudflare", load_max_docs=2).load() ``` -------------------------------- ### Load Environment Variables for Cloudflare Credentials Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/text_embedding.ipynb Loads Cloudflare Account ID and API token from a .env file. Ensure these credentials are set in your environment or .env file. ```python from dotenv import load_dotenv import os load_dotenv(".env") cf_acct_id = os.getenv("CF_ACCOUNT_ID") cf_ai_token = os.getenv("CF_AI_API_TOKEN") ``` -------------------------------- ### Synchronous Cloudflare D1 Checkpointer Usage Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Initializes the CloudflareD1Saver and creates a LangGraph agent with persistence. Invokes the agent synchronously with a configuration specifying a thread ID. ```python from langgraph_checkpoint_cloudflare_d1 import CloudflareD1Saver checkpointer = CloudflareD1Saver() graph = create_react_agent(model, tools=tools, checkpointer=checkpointer) config = {"configurable": {"thread_id": "1"}} response = graph.invoke({"messages": [("human", "what's the weather in sf")]}, config) ``` -------------------------------- ### List Metadata Indexes for Vectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Lists all metadata indexes associated with a specific Vectorize index. ```python r = cfVect.list_metadata_indexes(index_name=vectorize_index_name) print(r) ``` -------------------------------- ### Configure OpenAI API Key Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Sets the OpenAI API key from an environment variable or prompts the user if not set. This is an alternative if not using Cloudflare WorkersAI. ```python if not os.getenv("OPENAI_API_KEY"): os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter your OPENAI API Key: ") ``` -------------------------------- ### Prepare New Document for Upsert Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Creates a new `Document` object with a specified ID, page content, and metadata, intended for an upsert operation. ```python new_document_id = "12345678910" new_document = Document( id=new_document_id, page_content="This is a new document!", metadata={"section": "Introduction"}, ) ``` -------------------------------- ### Asynchronously Perform Similarity Searches Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Asynchronously perform similarity searches on multiple vectorstores with different queries. This allows for parallel retrieval of information. ```python async_requests = [ cfVect.asimilarity_search(index_name=vectorize_index_name1, query="Workers AI"), cfVect.asimilarity_search(index_name=vectorize_index_name2, query="Edge Computing"), ] async_results = await asyncio.gather(*async_requests); ``` -------------------------------- ### Tool Binding for Function Calling Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Bind a model to a list of tools, enabling it to call functions based on natural language input. The 'llm' object must be initialized, and the tool function should be decorated with '@tool'. ```python from typing import List from langchain_core.tools import tool @tool def validate_user(user_id: int, addresses: List[str]) -> bool: """Validate user using historical addresses. Args: user_id (int): the user ID. addresses (List[str]): Previous addresses as a list of strings. """ return True llm_with_tools = llm.bind_tools([validate_user]) result = llm_with_tools.invoke( "Could you validate user 123? They previously lived at " "123 Fake St in Boston MA and 234 Pretend Boulevard in " "Houston TX." ) result.tool_calls ``` -------------------------------- ### Import Necessary Libraries for Cloudflare Vector Store Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Imports essential libraries for interacting with Cloudflare Vectorize, including document loaders, embeddings, vector store, text splitters, and asyncio for asynchronous operations. ```python import asyncio import json import uuid import warnings from langchain_community.document_loaders import WikipediaLoader from langchain_cloudflare.embeddings import \ CloudflareWorkersAIEmbeddings from langchain_cloudflare.vectorstores import \ CloudflareVectorize from langchain_core.documents import Document from langchain_text_splitters import RecursiveCharacterTextSplitter warnings.filterwarnings("ignore") ``` -------------------------------- ### Create Vectorize Index with Wrangler Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Creates a new Vectorize index named 'langchain-test-persistent' with specified dimensions and cosine similarity metric. This is required before performing Vectorize operations. ```bash npx wrangler vectorize create langchain-test-persistent --dimensions 768 --metric cosine ``` -------------------------------- ### Structured Output with JSON Schema Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Bind a model to a JSON schema to enforce structured output. The schema defines the expected format, including types and required fields. The 'llm' object must be initialized. ```python json_schema = { "title": "joke", "description": "Joke to tell user.", "type": "object", "properties": { "setup": { "type": "string", "description": "The setup of the joke", }, "punchline": { "type": "string", "description": "The punchline to the joke", }, "rating": { "type": "integer", "description": "How funny the joke is, from 1 to 10", "default": None, }, }, "required": ["setup", "punchline"], } structured_llm = llm.with_structured_output(json_schema) structured_llm.invoke("Tell me a joke about cats") ``` -------------------------------- ### Integrate CloudflareD1Saver with LangGraph Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langgraph-checkpoint-cloudflare-d1/README.md Compile a LangGraph with the CloudflareD1Saver to enable checkpointing. Ensure the checkpointer is set up before compiling the graph. ```python from langgraph.graph import StateGraph from langgraph_checkpoint_cloudflare_d1 import CloudflareD1Saver # Create a simple graph builder = StateGraph(int) builder.add_node("add_one", lambda x: x + 1) builder.set_entry_point("add_one") builder.set_finish_point("add_one") # Create the checkpoint saver checkpointer = CloudflareD1Saver( account_id="your-account-id", database_id="your-database-id", api_token="your-api-token" ) checkpointer.setup() # Create necessary tables # Compile the graph with the checkpointer graph = builder.compile(checkpointer=checkpointer) # Use the graph with checkpointing config = {"configurable": {"thread_id": "my-thread-1"}} result = graph.invoke(3, config) ``` -------------------------------- ### Asynchronously Add Documents to Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Asynchronously add documents to multiple vectorstore indexes concurrently. This is an efficient way to populate multiple indexes with data. ```python async_requests = [ cfVect.aadd_documents(index_name=vectorize_index_name1, documents=texts, wait=True), cfVect.aadd_documents(index_name=vectorize_index_name2, documents=texts, wait=True), ] await asyncio.gather(*async_requests); ``` -------------------------------- ### Initialize ChatCloudflareWorkersAI Model Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Initializes the ChatCloudflareWorkersAI model with a specific model name, temperature, and max tokens. This model is suitable for Cloudflare WorkersAI. ```python from langchain_cloudflare import ChatCloudflareWorkersAI model = ChatCloudflareWorkersAI( model="@cf/meta/llama-3.3-70b-instruct-fp8-fast", temperature=0, max_tokens=1024 ) ``` -------------------------------- ### Print Chunk Information Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Prints the total number of text chunks created and the content and metadata of the first and last chunks. ```python print(len(texts)) print(texts[0], "\n\n", texts[-1]) ``` -------------------------------- ### Print Asynchronous Similarity Search Results Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Print the number of results and a preview of the first result from asynchronous similarity searches. ```python print(f"{len(async_results[0])} results:\n{str(async_results[0][0])[:300]}") print(f"{len(async_results[1])} results:\n{str(async_results[1][0])[:300]}") ``` -------------------------------- ### List and Filter Vectorize Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Retrieves a list of all Vectorize indexes and filters them to find those containing 'test-langchain' in their name. This is a preparatory step before deleting indexes. ```python arr_indexes = cfVect.list_indexes() arr_indexes = [x for x in arr_indexes if "test-langchain" in x.get("name")] ``` -------------------------------- ### Set CloudflareWorkersAI Credentials Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Sets the CF_AI_API_KEY and CF_ACCOUNT_ID environment variables. Prompts the user for input if they are not already set. ```python import getpass import os if not os.getenv("CF_AI_API_KEY"): os.environ["CF_AI_API_KEY"] = getpass.getpass( "Enter your CloudflareWorkersAI API key: " ) if not os.getenv("CF_ACCOUNT_ID"): os.environ["CF_ACCOUNT_ID"] = getpass.getpass( "Enter your CloudflareWorkersAI account ID: " ) ``` -------------------------------- ### Print Similarity Search Results Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Prints the number of results and a truncated preview of the last/first result from the asynchronous similarity searches. This helps in verifying the search output. ```python print(f"{len(async_results[0])} results:\n{str(async_results[0][-1])[:300]}") print(f"{len(async_results[1])} results:\n{str(async_results[1][0])[:300]}") ``` -------------------------------- ### Similarity Search for Documents Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Perform a similarity search on the vectorstore to find documents relevant to a given query. The output shows the number of results and a preview of the first result. ```python # query for documents query_documents = cfVect.similarity_search( index_name=vectorize_index_name, query="Edge Computing", ) print(f"{len(query_documents)} results:\n{str(query_documents[0])[:300]}") ``` -------------------------------- ### Asynchronously Search with Return Values and Metadata Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Perform asynchronous similarity searches, requesting specific return values and all metadata. This allows for detailed retrieval of document content and associated metadata. ```python async_requests = [ cfVect.asimilarity_search( index_name=vectorize_index_name1, query="California", return_values=True, return_metadata="all", ), cfVect.asimilarity_search( index_name=vectorize_index_name2, query="California", return_values=True, return_metadata="all", ), ] async_results = await asyncio.gather(*async_requests); ``` -------------------------------- ### Create Metadata Index for Vectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Creates a metadata index on the 'section' field for a Vectorize index, enabling metadata filtering in queries. The index type is specified as 'string'. ```python r = cfVect.create_metadata_index( property_name="section", index_type="string", index_name=vectorize_index_name, wait=True, ) print(r) ``` -------------------------------- ### Structured Output Extraction Request Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Sends a POST request to the /structured endpoint for structured output extraction. The request body should contain a JSON object with a 'text' field. ```bash curl -X POST http://localhost:8787/structured \ -H "Content-Type: application/json" \ -d '{"text": "Acme Corp announced a partnership with TechGiant."}' ``` -------------------------------- ### Add Documents to Vectorize Index with Namespaces Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Adds documents to a Vectorize index, specifying a namespace for each document. Ensure the `vectorize_index_name` is defined. ```python namespace_name = f"test-namespace-{uuid.uuid4().hex[:8]}" new_documents = [ Document( page_content="This is a new namespace specific document!", metadata={"section": "Namespace Test1"}, ), Document( page_content="This is another namespace specific document!", metadata={"section": "Namespace Test2"}, ), ] r = cfVect.add_documents( index_name=vectorize_index_name, documents=new_documents, namespaces=[namespace_name] * len(new_documents), wait=True, ) ``` -------------------------------- ### Initialize CloudflareWorkersAIEmbeddings Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Initializes the CloudflareWorkersAIEmbeddings class, which is used to generate embeddings for text data. Requires account ID, API token, and the desired model name. ```python cf_ai_token = os.getenv( "CF_AI_API_TOKEN" ) # needed if you want to use workersAI for embeddings embedder = CloudflareWorkersAIEmbeddings( account_id=cf_acct_id, api_token=cf_ai_token, model_name=MODEL_WORKERSAI ) ``` -------------------------------- ### Load Environment Variables for Cloudflare Credentials Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Loads environment variables from a .env file for Cloudflare API credentials. These variables are used to authenticate with Cloudflare services like Vectorize, D1, and WorkersAI. ```python from dotenv import load_dotenv import os load_dotenv(".env") # Declare as variables for example's sake (you'll see why below) cf_acct_id = os.getenv("CF_ACCOUNT_ID") # single "globally scoped" token with WorkersAI, Vectorize & D1 api_token = os.getenv("CF_API_TOKEN") # OR, separate tokens with access to each service cf_vectorize_token = os.getenv("CF_VECTORIZE_API_TOKEN") cf_d1_token = os.getenv("CF_D1_API_TOKEN") ``` -------------------------------- ### Configure Cloudflare WorkersAI API Key Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/checkpointer.ipynb Sets the Cloudflare WorkersAI API key from an environment variable or prompts the user if not set. Required for using Cloudflare WorkersAI models. ```python if not os.getenv("CF_AI_API_KEY"): os.environ["CF_AI_API_KEY"] = getpass.getpass( "Enter your CloudflareWorkersAI API key: " ) ``` -------------------------------- ### Perform Async Similarity Search with Metadata Filter Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Initiates asynchronous similarity searches on specified Vectorize indexes with metadata filtering. Ensure `vectorize_index_name1` and `vectorize_index_name2` are defined and accessible. ```python async_requests = [ cfVect.asimilarity_search( index_name=vectorize_index_name1, query="Cloudflare services", k=2, md_filter={"section": "Products"}, return_metadata="all", # return_values=True ), cfVect.asimilarity_search( index_name=vectorize_index_name2, query="Cloudflare services", k=2, md_filter={"section": "Products"}, return_metadata="all", # return_values=True ), ] async_results = await asyncio.gather(*async_requests); ``` -------------------------------- ### Optional: Set LangSmith Tracing Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Sets the LANGSMITH_TRACING and LANGSMITH_API_KEY environment variables for automated tracing of model calls. This is optional. ```python # os.environ["LANGSMITH_TRACING"] = "true" # os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ") ``` -------------------------------- ### Initiate Asynchronous Deletion of Vectorize Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Creates a list of asynchronous requests to delete the identified Vectorize indexes and then executes them concurrently using `asyncio.gather`. Ensure `arr_indexes` is populated with the correct index names. ```python arr_async_requests = [ cfVect.adelete_index(index_name=x.get("name")) for x in arr_indexes ] await asyncio.gather(*arr_async_requests); ``` -------------------------------- ### Perform Similarity Search Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Use `similarity_search` to find documents similar to a query. Specify the index name and the number of results (`k`). ```python query_documents = cfVect.similarity_search( index_name=vectorize_index_name, query="Workers AI", k=100, return_metadata="none" ) print(f"{len(query_documents)} results:\n{query_documents[:3]}") ``` -------------------------------- ### Basic Chat Completion Request Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/libs/langchain-cloudflare/examples/workers/README.md Sends a POST request to the /chat endpoint for basic chat completion. The request body should contain a JSON object with a 'message' field. ```bash curl -X POST http://localhost:8787/chat \ -H "Content-Type: application/json" \ -d '{"message": "Hello!"}' ``` -------------------------------- ### Print Partial Add Documents Response Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Prints the first 300 characters of the response from adding documents to the Vectorize index, which typically includes a list of document IDs. ```python print(json.dumps(r)[:300]) ``` -------------------------------- ### Similarity Search with Metadata and Values Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Retrieve documents along with their metadata and embedding values. Note that results are limited to the top 20 when metadata or values are returned. ```python query_documents = cfVect.similarity_search( index_name=vectorize_index_name, query="Workers AI", return_values=True, return_metadata="all", k=100, ) print(f"{len(query_documents)} results:\n{str(query_documents[0])[:500]}") ``` -------------------------------- ### Convert Vector Store to Retriever Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Transform the vector store into a retriever object for use in LangChain chains. Configure search type and keyword arguments like `k` and `index_name`. ```python retriever = cfVect.as_retriever( search_type="similarity", search_kwargs={"k": 1, "index_name": vectorize_index_name}, ) r = retriever.invoke("california") ``` -------------------------------- ### Add Documents to Vectorize Index Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Adds a list of text documents, including their metadata, to a specified Vectorize index. The `wait=True` parameter ensures the operation completes before returning. ```python r = cfVect.add_documents(index_name=vectorize_index_name, documents=texts, wait=True) ``` -------------------------------- ### Define Vectorstore Index Name Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Define the name for the vectorstore index. This is a prerequisite for creating or interacting with a vectorstore. ```python vectorize_index_name = "test-langchain-from-docs" ``` -------------------------------- ### Delete and Create Vectorize Index Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Deletes an existing Vectorize index if it exists, then creates a new one. Handles potential errors during deletion. ```python %%capture try: cfVect.delete_index(index_name=vectorize_index_name, wait=True) except Exception as e: print(e) ``` ```python r = cfVect.create_index( index_name=vectorize_index_name, description="A Test Vectorize Index", wait=True ) print(r) ``` -------------------------------- ### Generate Embeddings for a Batch of Strings Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/text_embedding.ipynb Generates embeddings for multiple input strings in a batch using the initialized CloudflareWorkersAIEmbeddings model. The result is a list of embedding vectors, where each vector corresponds to an input string. ```python # string embeddings in batches batch_query_result = embeddings.embed_documents(["test1", "test2", "test3"]) len(batch_query_result), len(batch_query_result[0]) ``` -------------------------------- ### Define Multiple Vectorstore Index Names Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Define unique names for multiple vectorstore indexes using UUIDs. This is useful when managing several independent vectorstores. ```python vectorize_index_name1 = f"test-langchain-{uuid.uuid4().hex}" vectorize_index_name2 = f"test-langchain-{uuid.uuid4().hex}" ``` -------------------------------- ### Invoke Chat Model for Translation Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Invokes the instantiated chat model with a system message and a human message to perform a translation task. The result includes the AI's response and metadata. ```python messages = [ ( "system", "You are a helpful assistant that translates English to French. Translate the user sentence.", ), ("human", "I love programming."), ] ai_msg = llm.invoke(messages) ai_msg ``` -------------------------------- ### Print Translated Content Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/chat.ipynb Prints the content of the AI's message, which in this case is the French translation. ```python print(ai_msg.content) ``` -------------------------------- ### Retrieve Updated Documents After Upsert Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Fetches documents from the Vectorize index after an upsert operation to verify the changes. Requires the IDs of the documents involved in the upsert. ```python query_documents_updated = cfVect.get_by_ids([new_document_id, query_documents[0].id]) ``` ```python print(str(query_documents_updated[0])[:500]) print(query_documents_updated[0].page_content) print(query_documents_updated[1].page_content) ``` -------------------------------- ### Similarity Search with Scores Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Use `similarity_search_with_score` to retrieve documents along with their similarity scores. This method also respects the `return_metadata` parameter. ```python query_documents = cfVect.similarity_search_with_score( index_name=vectorize_index_name, query="Workers AI", k=100, return_metadata="all", ) print(f"{len(query_documents)} results:\n{str(query_documents[0])[:500]}") ``` -------------------------------- ### Import Cloudflare Workers AI Embeddings Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/text_embedding.ipynb Imports the necessary CloudflareWorkersAIEmbeddings class from the langchain_cloudflare library. ```python from langchain_cloudflare.embeddings import ( CloudflareWorkersAIEmbeddings, ) ``` -------------------------------- ### Create Text Chunks with Metadata Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Splits document content into smaller chunks using RecursiveCharacterTextSplitter and assigns metadata, specifically the 'section' field, based on content. ```python text_splitter = RecursiveCharacterTextSplitter( # Set a really small chunk size, just to show. chunk_size=100, chunk_overlap=20, length_function=len, is_separator_regex=False, ) texts = text_splitter.create_documents([docs[0].page_content]) running_section = "" for idx, text in enumerate(texts): if text.page_content.startswith("="): running_section = text.page_content running_section = running_section.replace("=", "").strip() else: if running_section == "": text.metadata = {"section": "Introduction"} else: text.metadata = {"section": running_section} ``` -------------------------------- ### Search Documents by Namespace in Vectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Performs a similarity search within a specified namespace in a Vectorize index. Requires `vectorize_index_name` and `namespace_name` to be defined. ```python query_documents = cfVect.similarity_search( index_name=vectorize_index_name, query="California", namespace=namespace_name, ) print(f"{len(query_documents)} results:\n - {str(query_documents)}") ``` -------------------------------- ### Verify Deletion of Records Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Confirms that records have been deleted from the Vectorize index by attempting to retrieve them using their IDs. An empty result set indicates successful deletion. ```python query_documents = cfVect.get_by_ids(sample_ids) assert len(query_documents) == 0 ``` -------------------------------- ### Search with Exact Metadata Filter Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Use this to find documents matching a specific value in a metadata field. Ensure the 'section' metadata field is indexed. ```python query_documents = cfVect.similarity_search_with_score( index_name=vectorize_index_name, query="California", k=100, md_filter={"section": "Introduction"}, return_metadata="all", ) print(f"{len(query_documents)} results:\n - {str(query_documents[:3])}") ``` -------------------------------- ### Initialize Cloudflare Workers AI Embeddings Model Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/text_embedding.ipynb Initializes the CloudflareWorkersAIEmbeddings with account ID, API token, and a specified model name. This model is used for generating text embeddings. ```python embeddings = CloudflareWorkersAIEmbeddings( account_id=cf_acct_id, api_token=cf_ai_token, model_name="@cf/baai/bge-small-en-v1.5", ) ``` -------------------------------- ### Similarity Search Excluding D1 Data Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Perform a similarity search while excluding raw D1 data by setting `include_d1=False`. This results in documents with an empty `page_content` field. ```python query_documents = cfVect.similarity_search_with_score( index_name=vectorize_index_name, query="california", k=100, return_metadata="all", include_d1=False, ) print(f"{len(query_documents)} results:\n{str(query_documents[0])[:500]}") ``` -------------------------------- ### Search with Multiple Metadata Values Filter Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Use this to find documents that match any of the specified values within a metadata field. This allows for searching across multiple relevant sections. ```python query_documents = cfVect.similarity_search_with_score( index_name=vectorize_index_name, query="DNS", k=100, md_filter={"section": {"$in": ["Products", "History"]}}, return_metadata="all", ) print(f"{len(query_documents)} results:\n - {str(query_documents)}") ``` -------------------------------- ### Define Cloudflare Vectorize Index Name Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Generates a unique name for the Cloudflare Vectorize index using a UUID. This is useful for creating temporary or test indexes. ```python # name your vectorize index vectorize_index_name = f"test-langchain-{uuid.uuid4().hex}" ``` -------------------------------- ### Retrieve Documents by IDs from Vectorize Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Retrieves specific documents from a Vectorize index using their IDs. The `index_name` must be set on the `cfVect` object. ```python sample_ids = [x.id for x in query_documents] ``` ```python cfVect.index_name = vectorize_index_name ``` ```python query_documents = cfVect.get_by_ids( sample_ids, ) print(str(query_documents[:3])[:500]) ``` -------------------------------- ### Delete Test Cloudflare Vectorize Indexes Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Asynchronously deletes all Cloudflare Vectorize indexes that match the 'test-langchain*' pattern. This is useful for cleaning up before running tests or demonstrations. ```python # depending on your notebook environment you might need to include: # import nest_asyncio # nest_asyncio.apply() arr_indexes = cfVect.list_indexes() arr_indexes = [x for x in arr_indexes if "test-langchain" in x.get("name")] arr_async_requests = [ cfVect.adelete_index(index_name=x.get("name")) for x in arr_indexes ] await asyncio.gather(*arr_async_requests); ``` -------------------------------- ### Generate Embeddings for a Single String Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/text_embedding.ipynb Generates embeddings for a single input string using the initialized CloudflareWorkersAIEmbeddings model. The result is a list of floats representing the embedding vector. ```python # single string embeddings query_result = embeddings.embed_query("test") len(query_result), query_result[:3] ``` -------------------------------- ### Search with Not-Equal Metadata Filter Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Use this to exclude documents that match a specific value in a metadata field. This is useful for broad searches where certain sections should be omitted. ```python query_documents = cfVect.similarity_search_with_score( index_name=vectorize_index_name, query="California", k=100, md_filter={"section": {"$ne": "Introduction"}}, return_metadata="all", ) print(f"{len(query_documents)} results:\n - {str(query_documents[:3])}") ``` -------------------------------- ### Specify WorkersAI Embedding Model Source: https://github.com/cloudflare/langchain-cloudflare/blob/main/docs/vectorstores.ipynb Defines the model name to be used for generating embeddings via Cloudflare WorkersAI. Ensure the specified model is available on WorkersAI. ```python MODEL_WORKERSAI = "@cf/baai/bge-large-en-v1.5" ```