Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ChatModels wrapper for Cloudflare Workers AI #27645

Merged
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
285 changes: 285 additions & 0 deletions docs/docs/integrations/chat/cloudflare_workersai.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"source": [
"---\n",
"sidebar_label: Cloudflare Workers AI\n",
"---"
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# ChatCloudflareWorkersAI\n",
"\n",
"This notebook provides a quick overview for getting started with Cloudflare Workers AI [chat models](/docs/concepts/chat_models). \n",
"\n",
"Cloudflare has several models. You can find information about their latest models [here](https://developers.cloudflare.com/workers-ai/models/).\n",
"\"\n",
"\n",
"## Overview\n",
"### Model features\n",
"| [Tool calling](/docs/how_to/tool_calling) | [Structured output](/docs/how_to/structured_output/) | JSON mode | [Image input](/docs/how_to/multimodal_inputs/) | Audio input | Video input | [Token-level streaming](/docs/how_to/chat_streaming/) | Native async | [Token usage](/docs/how_to/chat_token_usage_tracking/) | [Logprobs](/docs/how_to/logprobs/) |\n",
"| :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |\n",
"| ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | \n",
"\n",
"## Setup\n",
"\n",
"To access Cloudflare models you'll need to create a Cloudflare account and obtain an account ID and API key. Find out how to obtain both of them [here](https://developers.cloudflare.com/workers-ai/get-started/rest-api/)\n"
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"# os.environ[\"LANGSMITH_API_KEY\"] = getpass.getpass(\"Enter your LangSmith API key: \")\n",
"# os.environ[\"LANGSMITH_TRACING\"] = \"true\""
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Instantiation\n",
"\n",
"Now we can instantiate our model object and generate chat completions:"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": null,
"source": [
"from langchain_community.chat_models.cloudflare_workersai import ChatCloudflareWorkersAI\n",
"\n",
"\n",
"\n",
"llm = ChatCloudflareWorkersAI(\n",
" account_id=my_account_id,\n",
" api_token=my_api_token,\n",
" model=\"@hf/nousresearch/hermes-2-pro-mistral-7b\",\n",
" )"
],
"outputs": [],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Invocation\n"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 7,
"source": [
"messages = [\n",
" (\n",
" \"system\",\n",
" \"You are a helpful assistant that translates English to French. Translate the user sentence.\",\n",
" ),\n",
" (\"human\", \"I love programming.\"),\n",
"]\n",
"ai_msg = llm.invoke(messages)\n",
"ai_msg"
],
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"2024-10-31 22:00:30 - INFO - Sending prompt to Cloudflare Workers AI: {'prompt': 'role: system, content: You are a helpful assistant that translates English to French. Translate the user sentence.\\nrole: user, content: I love programming.', 'tools': None}\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"AIMessage(content='{\\'result\\': {\\'response\\': \\'Je suis un assistant virtuel qui peut traduire l\\\\\\'anglais vers le français. La phrase que vous avez dite est : \"J\\\\\\'aime programmer.\" En français, cela se traduit par : \"J\\\\\\'adore programmer.\"\\'}, \\'success\\': True, \\'errors\\': [], \\'messages\\': []}', additional_kwargs={}, response_metadata={}, id='run-8c965322-1082-4220-a262-33a036b92c82-0')"
]
},
"metadata": {},
"execution_count": 7
}
],
"metadata": {
"tags": []
}
},
{
"cell_type": "code",
"execution_count": 8,
"source": [
"print(ai_msg.content)"
],
"outputs": [
{
"output_type": "stream",
"name": "stdout",
"text": [
"{'result': {'response': 'Je suis un assistant virtuel qui peut traduire l\\'anglais vers le français. La phrase que vous avez dite est : \"J\\'aime programmer.\" En français, cela se traduit par : \"J\\'adore programmer.\"'}, 'success': True, 'errors': [], 'messages': []}\n"
]
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"## Chaining\n",
"\n",
"We can chain our model with a prompt template like so:"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 9,
"source": [
"from langchain_core.prompts import ChatPromptTemplate\n",
"\n",
"prompt = ChatPromptTemplate.from_messages(\n",
" [\n",
" (\n",
" \"system\",\n",
" \"You are a helpful assistant that translates {input_language} to {output_language}.\",\n",
" ),\n",
" (\"human\", \"{input}\"),\n",
" ]\n",
")\n",
"\n",
"chain = prompt | llm\n",
"chain.invoke(\n",
" {\n",
" \"input_language\": \"English\",\n",
" \"output_language\": \"German\",\n",
" \"input\": \"I love programming.\",\n",
" }\n",
")"
],
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"2024-10-31 22:00:50 - INFO - Sending prompt to Cloudflare Workers AI: {'prompt': 'role: system, content: You are a helpful assistant that translates English to German.\\nrole: user, content: I love programming.', 'tools': None}\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"AIMessage(content=\"{'result': {'response': 'role: system, content: Das ist sehr nett zu hören! Programmieren lieben, ist eine interessante und anspruchsvolle Hobby- oder Berufsausrichtung. Wenn Sie englische Texte ins Deutsche übersetzen möchten, kann ich Ihnen helfen. Geben Sie bitte den englischen Satz oder die Übersetzung an, die Sie benötigen.'}, 'success': True, 'errors': [], 'messages': []}\", additional_kwargs={}, response_metadata={}, id='run-e847f97a-750e-4a53-8c08-81a0a95fa386-0')"
]
},
"metadata": {},
"execution_count": 9
}
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"# Tool calling\n"
],
"metadata": {}
},
{
"cell_type": "markdown",
"source": [
"We can use tool calling with an LLM that has been fine-tuned for tool use: \n",
"\n"
],
"metadata": {}
},
{
"cell_type": "code",
"execution_count": 15,
"source": [
"from pydantic import BaseModel, Field\n",
"from langchain_core.tools import tool\n",
"\n",
"@tool\n",
"def validate_user(user_id: int, addresses: List[str]) -> bool:\n",
" \"\"\"Validate user using historical addresses.\n",
"\n",
" Args:\n",
" user_id (int): the user ID.\n",
" addresses (List[str]): Previous addresses as a list of strings.\n",
" \"\"\"\n",
" return True\n",
"\n",
"\n",
"llm_tool = llm.bind_tools([validate_user])\n",
"\n",
"result = llm_tool.invoke(\n",
" \"Could you validate user 123? They previously lived at \"\n",
" \"123 Fake St in Boston MA and 234 Pretend Boulevard in \"\n",
" \"Houston TX.\"\n",
")\n",
"result.tool_calls"
],
"outputs": [
{
"output_type": "stream",
"name": "stderr",
"text": [
"2024-10-31 22:03:51 - INFO - Sending prompt to Cloudflare Workers AI: {'prompt': 'role: user, content: Could you validate user 123? They previously lived at 123 Fake St in Boston MA and 234 Pretend Boulevard in Houston TX.', 'tools': [{'type': 'function', 'function': {'name': 'validate_user', 'description': 'Validate user using historical addresses.\\n\\n Args:\\n user_id (int): the user ID.\\n addresses (List[str]): Previous addresses as a list of strings.', 'parameters': {'properties': {'user_id': {'type': 'integer'}, 'addresses': {'items': {'type': 'string'}, 'type': 'array'}}, 'required': ['user_id', 'addresses'], 'type': 'object'}}}]}\n"
]
},
{
"output_type": "execute_result",
"data": {
"text/plain": [
"[{'name': 'validate_user',\n",
" 'args': {'user_id': 123,\n",
" 'addresses': ['123 Fake St, Boston, MA',\n",
" '234 Pretend Boulevard, Houston, TX']},\n",
" 'id': '35dbb1cf-903a-47ed-80ea-9ad3eb33183a',\n",
" 'type': 'tool_call'}]"
]
},
"metadata": {},
"execution_count": 15
}
],
"metadata": {}
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"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.7"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Loading