langchain-meta 0.3.11__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 LangChain, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,248 @@
1
+ Metadata-Version: 2.3
2
+ Name: langchain-meta
3
+ Version: 0.3.11
4
+ Summary: An integration wrapper package connecting Meta's Llama API client and LangGraph. Implements ChatModel interface from LangChain.
5
+ License: MIT
6
+ Author: Matt Petters
7
+ Author-email: mcpetters@gmail.com
8
+ Requires-Python: >=3.9,<3.14
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Requires-Dist: langchain (>=0.3.25,<0.4.0)
17
+ Requires-Dist: langchain-core (>=0.1.33,<0.4.0)
18
+ Requires-Dist: langchain-tavily (>=0.1.6,<0.2.0)
19
+ Requires-Dist: langgraph (>=0.4.3,<0.5.0)
20
+ Requires-Dist: llama-api-client (>=0.1.0,<0.2.0)
21
+ Requires-Dist: pydantic (>=1.10,<3.0)
22
+ Requires-Dist: pytest (==7.4.4)
23
+ Requires-Dist: pytest-asyncio (==0.23.7)
24
+ Requires-Dist: python-dotenv (>=1.1.0,<2.0.0)
25
+ Requires-Dist: regex (>=2023.0.0)
26
+ Requires-Dist: twine (>=6.1.0,<7.0.0)
27
+ Requires-Dist: typing-extensions (>=4.8.0)
28
+ Project-URL: Repository, https://github.com/mattpetters/langchain-meta
29
+ Project-URL: Release Notes, https://github.com/mattpetters/langchain-meta/releases?q=tag%3A%22meta%3D%3D0%22&expanded=true
30
+ Project-URL: Source Code, https://github.com/mattpetters/langchain-meta
31
+ Description-Content-Type: text/markdown
32
+
33
+ # langchain-meta
34
+
35
+ Native integration between the [Meta Llama API](https://www.llama.com/products/llama-api/) 🦙 and the [LangChain/LangGraph ecosystem](https://www.langchain.com/), ⛓ providing fast hosted access to Meta's powerful Llama 4 models to power your Langgraph agents.
36
+ Fully implements [ChatModel interface](https://python.langchain.com/docs/concepts/chat_models/).
37
+
38
+ ## Installation
39
+
40
+ ```bash
41
+ pip install langchain-meta
42
+ ```
43
+
44
+ Set up your credentials with environment variables:
45
+
46
+ ```bash
47
+ export META_API_KEY="your-api-key"
48
+ export META_API_BASE_URL="https://api.llama.com/v1"
49
+ export META_MODEL_NAME="Llama-4-Maverick-17B-128E-Instruct-FP8"
50
+ # Optional, see list: https://llama.developer.meta.com/docs/api/models/
51
+ ```
52
+
53
+ ## Usage
54
+
55
+ ### ChatMetaLlama
56
+
57
+ ```python
58
+ from langchain_meta import ChatMetaLlama
59
+
60
+ # Initialize with API key and base URL
61
+ llm = ChatMetaLlama(
62
+ model="Llama-4-Maverick-17B-128E-Instruct-FP8",
63
+ api_key="your-meta-api-key",
64
+ base_url="https://api.llama.com/v1/"
65
+ )
66
+
67
+ # Basic invocation
68
+ from langchain_core.messages import HumanMessage
69
+ response = llm.invoke([HumanMessage(content="Hello Llama!")])
70
+ print(response.content)
71
+ ```
72
+
73
+ ### LangSmith Integration
74
+
75
+ ChatMetaLlama is fully compatible with [LangSmith](https://smith.langchain.com/), providing comprehensive tracing and observability for your Meta LLM applications.
76
+
77
+ Key features of LangSmith integration:
78
+
79
+ - **Token Usage Tracking**: Get accurate input/output token counts for cost estimation
80
+ - **Request/Response Logging**: View full context of all prompts and completions
81
+ - **Tool Execution Tracing**: Monitor tool calls and their execution
82
+ - **Runtime Metrics**: Track latency and other performance metrics
83
+
84
+ To enable LangSmith tracing, set these environment variables:
85
+
86
+ ```bash
87
+ export LANGSMITH_TRACING=true
88
+ export LANGSMITH_API_KEY="your-api-key"
89
+ export LANGSMITH_PROJECT="your-project-name"
90
+ ```
91
+
92
+ See the [examples/langsmith_integration.py](./examples/langsmith_integration.py) script for a complete example of LangSmith integration.
93
+
94
+ ### Utility Functions
95
+
96
+ #### meta_agent_factory
97
+
98
+ A utility to create LangChain runnables with Meta-specific configurations. Handles structured output and ensures streaming is disabled when needed for Meta API compatibility.
99
+
100
+ ```python
101
+ from langchain_meta import meta_agent_factory, ChatMetaLlama
102
+ from langchain_core.tools import Tool
103
+ from pydantic import BaseModel
104
+
105
+ # Create LLM
106
+ llm = ChatMetaLlama(api_key="your-meta-api-key")
107
+
108
+ # Example with tools
109
+ tools = [Tool.from_function(func=lambda x: x, name="example", description="Example tool")]
110
+ agent = meta_agent_factory(
111
+ llm=llm,
112
+ tools=tools,
113
+ system_prompt_text="You are a helpful assistant that uses tools.",
114
+ disable_streaming=True
115
+ )
116
+
117
+ # Example with structured output
118
+ class ResponseSchema(BaseModel):
119
+ answer: str
120
+ confidence: float
121
+
122
+ structured_agent = meta_agent_factory(
123
+ llm=llm,
124
+ output_schema=ResponseSchema,
125
+ system_prompt_text="Return structured answers with confidence scores."
126
+ )
127
+ ```
128
+
129
+ #### extract_json_response
130
+
131
+ A robust utility to extract JSON from various response formats, handling direct JSON objects, code blocks with backticks, or JSON-like patterns in text.
132
+
133
+ ```python
134
+ from langchain_meta import extract_json_response
135
+
136
+ # Parse various response formats
137
+ result = llm.invoke("Return a JSON with name and age")
138
+ parsed_json = extract_json_response(result.content)
139
+ ```
140
+
141
+ ## Key Features
142
+
143
+ - **Direct Native API Access**: Connect to Meta Llama models through their official API for full feature compatibility
144
+ - **Seamless Tool Calling**: Intelligent conversion between LangChain tool formats and Llama API requirements
145
+ - **Complete Message History Support**: Proper conversion of all LangChain message types
146
+ - **Multi-Agent System Compatibility**: Drop-in replacement for ChatOpenAI in LangGraph workflows
147
+ - **LangSmith Integration**: Full observability and tracing for debugging and monitoring
148
+
149
+ ## Chat Models
150
+
151
+ ```python
152
+ from langchain_meta import ChatMetaLlama
153
+
154
+ llm = ChatMetaLlama()
155
+ llm.invoke("Who directed the movie The Social Network?")
156
+ ```
157
+
158
+ ## LangGraph & Multi-Agent Integration
159
+
160
+ The `ChatMetaLlama` class works with LangGraph nodes and complex agent systems:
161
+
162
+ ```python
163
+ from langchain_meta import ChatMetaLlama
164
+ from langchain_core.tools import tool
165
+
166
+ # Works with @tool decorations
167
+ @tool
168
+ def get_weather(location: str) -> str:
169
+ """Get the current weather for a location."""
170
+ return f"The weather in {location} is sunny."
171
+
172
+ # Create LLM with tools
173
+ llm = ChatMetaLlama(model="Llama-4-Maverick-17B-128E-Instruct-FP8")
174
+ llm_with_tools = llm.bind_tools([get_weather])
175
+
176
+ # Works in agent nodes and graph topologies
177
+ response = llm_with_tools.invoke("What's the weather in Seattle?")
178
+ ```
179
+
180
+ ### LangGraph Serialization Support
181
+
182
+ To solve serialization issues with LangGraph, `ChatMetaLlama` provides a built-in message serializer:
183
+
184
+ ```python
185
+ from langchain_meta import ChatMetaLlama
186
+ from langgraph.serde import register_type_serializer
187
+ from langchain_core.messages import AIMessage
188
+
189
+ # Register the serializer with LangGraph
190
+ register_type_serializer(
191
+ AIMessage,
192
+ serialize_fn=ChatMetaLlama.get_message_serializer(),
193
+ deserialize_fn=lambda x: AIMessage(**x)
194
+ )
195
+
196
+ # Now your graph nodes can properly serialize AIMessage objects
197
+ # See examples/langgraph_serialization.py for a complete example
198
+ ```
199
+
200
+ ## Advanced Features
201
+
202
+ - **Streaming Support**: Streaming implementation for both content and tool calls
203
+ - **Context Preservation**: Correctly handles the full conversation context in agent graphs
204
+ - **Error Resilience**: Robust handling of tool call parsing errors and response validation
205
+ - **Format Compatibility**: Support for structured output Pydantic objects
206
+ - **Observability**: Complete LangSmith integration for tracing and debugging
207
+
208
+ ## Robust Tool Call Normalization
209
+
210
+ This module automatically normalizes all tool calls from Llama/Meta API:
211
+
212
+ - Ensures every tool call has a valid string `id` (generates one if missing/empty)
213
+ - Ensures `name` is a string (defaults to `"unknown_tool"` if missing)
214
+ - Ensures `args` is a dict (parses JSON if string, else wraps as `{"value": ...}`)
215
+ - Always sets `type` to `"function"`
216
+ - Logs a warning for any repair
217
+
218
+ **Best Practices:**
219
+
220
+ - Define your tool schemas as simply as possible (avoid advanced JSON Schema features).
221
+ - Provide clear prompt examples to the LLM for tool calling.
222
+ - Be aware of backend limitations (see [vLLM Issue #15236](https://github.com/vllm-project/vllm/issues/15236)).
223
+
224
+ Your code is robust to malformed tool calls, but clear schemas and prompts will maximize reliability.
225
+
226
+ ## Defensive Tool Call Handling
227
+
228
+ LangChain Meta includes robust defensive mechanisms for handling malformed tool calls:
229
+
230
+ - Always ensures `tool_call_id` is a non-empty string (generates UUID if missing/empty)
231
+ - Always ensures `name` is a string (fallback to 'unknown_tool')
232
+ - Always ensures `args` is a dict (tries to parse string as JSON, else wraps as {'value': ...})
233
+ - Always sets `type` to 'function'
234
+ - Logs warnings for any repairs made
235
+
236
+ This makes the integration more resilient when working with models that may sometimes produce malformed tool calls.
237
+
238
+ ## Contributing
239
+
240
+ We welcome contributions! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for details.
241
+
242
+ ## License
243
+
244
+ This project is licensed under the MIT License.
245
+
246
+ Llama 4, Llama AI API, etc trademarks belong to their respective owners (Meta)
247
+ I just made this to make my life easier and thought I'd share. 😊
248
+
@@ -0,0 +1,215 @@
1
+ # langchain-meta
2
+
3
+ Native integration between the [Meta Llama API](https://www.llama.com/products/llama-api/) 🦙 and the [LangChain/LangGraph ecosystem](https://www.langchain.com/), ⛓ providing fast hosted access to Meta's powerful Llama 4 models to power your Langgraph agents.
4
+ Fully implements [ChatModel interface](https://python.langchain.com/docs/concepts/chat_models/).
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ pip install langchain-meta
10
+ ```
11
+
12
+ Set up your credentials with environment variables:
13
+
14
+ ```bash
15
+ export META_API_KEY="your-api-key"
16
+ export META_API_BASE_URL="https://api.llama.com/v1"
17
+ export META_MODEL_NAME="Llama-4-Maverick-17B-128E-Instruct-FP8"
18
+ # Optional, see list: https://llama.developer.meta.com/docs/api/models/
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ### ChatMetaLlama
24
+
25
+ ```python
26
+ from langchain_meta import ChatMetaLlama
27
+
28
+ # Initialize with API key and base URL
29
+ llm = ChatMetaLlama(
30
+ model="Llama-4-Maverick-17B-128E-Instruct-FP8",
31
+ api_key="your-meta-api-key",
32
+ base_url="https://api.llama.com/v1/"
33
+ )
34
+
35
+ # Basic invocation
36
+ from langchain_core.messages import HumanMessage
37
+ response = llm.invoke([HumanMessage(content="Hello Llama!")])
38
+ print(response.content)
39
+ ```
40
+
41
+ ### LangSmith Integration
42
+
43
+ ChatMetaLlama is fully compatible with [LangSmith](https://smith.langchain.com/), providing comprehensive tracing and observability for your Meta LLM applications.
44
+
45
+ Key features of LangSmith integration:
46
+
47
+ - **Token Usage Tracking**: Get accurate input/output token counts for cost estimation
48
+ - **Request/Response Logging**: View full context of all prompts and completions
49
+ - **Tool Execution Tracing**: Monitor tool calls and their execution
50
+ - **Runtime Metrics**: Track latency and other performance metrics
51
+
52
+ To enable LangSmith tracing, set these environment variables:
53
+
54
+ ```bash
55
+ export LANGSMITH_TRACING=true
56
+ export LANGSMITH_API_KEY="your-api-key"
57
+ export LANGSMITH_PROJECT="your-project-name"
58
+ ```
59
+
60
+ See the [examples/langsmith_integration.py](./examples/langsmith_integration.py) script for a complete example of LangSmith integration.
61
+
62
+ ### Utility Functions
63
+
64
+ #### meta_agent_factory
65
+
66
+ A utility to create LangChain runnables with Meta-specific configurations. Handles structured output and ensures streaming is disabled when needed for Meta API compatibility.
67
+
68
+ ```python
69
+ from langchain_meta import meta_agent_factory, ChatMetaLlama
70
+ from langchain_core.tools import Tool
71
+ from pydantic import BaseModel
72
+
73
+ # Create LLM
74
+ llm = ChatMetaLlama(api_key="your-meta-api-key")
75
+
76
+ # Example with tools
77
+ tools = [Tool.from_function(func=lambda x: x, name="example", description="Example tool")]
78
+ agent = meta_agent_factory(
79
+ llm=llm,
80
+ tools=tools,
81
+ system_prompt_text="You are a helpful assistant that uses tools.",
82
+ disable_streaming=True
83
+ )
84
+
85
+ # Example with structured output
86
+ class ResponseSchema(BaseModel):
87
+ answer: str
88
+ confidence: float
89
+
90
+ structured_agent = meta_agent_factory(
91
+ llm=llm,
92
+ output_schema=ResponseSchema,
93
+ system_prompt_text="Return structured answers with confidence scores."
94
+ )
95
+ ```
96
+
97
+ #### extract_json_response
98
+
99
+ A robust utility to extract JSON from various response formats, handling direct JSON objects, code blocks with backticks, or JSON-like patterns in text.
100
+
101
+ ```python
102
+ from langchain_meta import extract_json_response
103
+
104
+ # Parse various response formats
105
+ result = llm.invoke("Return a JSON with name and age")
106
+ parsed_json = extract_json_response(result.content)
107
+ ```
108
+
109
+ ## Key Features
110
+
111
+ - **Direct Native API Access**: Connect to Meta Llama models through their official API for full feature compatibility
112
+ - **Seamless Tool Calling**: Intelligent conversion between LangChain tool formats and Llama API requirements
113
+ - **Complete Message History Support**: Proper conversion of all LangChain message types
114
+ - **Multi-Agent System Compatibility**: Drop-in replacement for ChatOpenAI in LangGraph workflows
115
+ - **LangSmith Integration**: Full observability and tracing for debugging and monitoring
116
+
117
+ ## Chat Models
118
+
119
+ ```python
120
+ from langchain_meta import ChatMetaLlama
121
+
122
+ llm = ChatMetaLlama()
123
+ llm.invoke("Who directed the movie The Social Network?")
124
+ ```
125
+
126
+ ## LangGraph & Multi-Agent Integration
127
+
128
+ The `ChatMetaLlama` class works with LangGraph nodes and complex agent systems:
129
+
130
+ ```python
131
+ from langchain_meta import ChatMetaLlama
132
+ from langchain_core.tools import tool
133
+
134
+ # Works with @tool decorations
135
+ @tool
136
+ def get_weather(location: str) -> str:
137
+ """Get the current weather for a location."""
138
+ return f"The weather in {location} is sunny."
139
+
140
+ # Create LLM with tools
141
+ llm = ChatMetaLlama(model="Llama-4-Maverick-17B-128E-Instruct-FP8")
142
+ llm_with_tools = llm.bind_tools([get_weather])
143
+
144
+ # Works in agent nodes and graph topologies
145
+ response = llm_with_tools.invoke("What's the weather in Seattle?")
146
+ ```
147
+
148
+ ### LangGraph Serialization Support
149
+
150
+ To solve serialization issues with LangGraph, `ChatMetaLlama` provides a built-in message serializer:
151
+
152
+ ```python
153
+ from langchain_meta import ChatMetaLlama
154
+ from langgraph.serde import register_type_serializer
155
+ from langchain_core.messages import AIMessage
156
+
157
+ # Register the serializer with LangGraph
158
+ register_type_serializer(
159
+ AIMessage,
160
+ serialize_fn=ChatMetaLlama.get_message_serializer(),
161
+ deserialize_fn=lambda x: AIMessage(**x)
162
+ )
163
+
164
+ # Now your graph nodes can properly serialize AIMessage objects
165
+ # See examples/langgraph_serialization.py for a complete example
166
+ ```
167
+
168
+ ## Advanced Features
169
+
170
+ - **Streaming Support**: Streaming implementation for both content and tool calls
171
+ - **Context Preservation**: Correctly handles the full conversation context in agent graphs
172
+ - **Error Resilience**: Robust handling of tool call parsing errors and response validation
173
+ - **Format Compatibility**: Support for structured output Pydantic objects
174
+ - **Observability**: Complete LangSmith integration for tracing and debugging
175
+
176
+ ## Robust Tool Call Normalization
177
+
178
+ This module automatically normalizes all tool calls from Llama/Meta API:
179
+
180
+ - Ensures every tool call has a valid string `id` (generates one if missing/empty)
181
+ - Ensures `name` is a string (defaults to `"unknown_tool"` if missing)
182
+ - Ensures `args` is a dict (parses JSON if string, else wraps as `{"value": ...}`)
183
+ - Always sets `type` to `"function"`
184
+ - Logs a warning for any repair
185
+
186
+ **Best Practices:**
187
+
188
+ - Define your tool schemas as simply as possible (avoid advanced JSON Schema features).
189
+ - Provide clear prompt examples to the LLM for tool calling.
190
+ - Be aware of backend limitations (see [vLLM Issue #15236](https://github.com/vllm-project/vllm/issues/15236)).
191
+
192
+ Your code is robust to malformed tool calls, but clear schemas and prompts will maximize reliability.
193
+
194
+ ## Defensive Tool Call Handling
195
+
196
+ LangChain Meta includes robust defensive mechanisms for handling malformed tool calls:
197
+
198
+ - Always ensures `tool_call_id` is a non-empty string (generates UUID if missing/empty)
199
+ - Always ensures `name` is a string (fallback to 'unknown_tool')
200
+ - Always ensures `args` is a dict (tries to parse string as JSON, else wraps as {'value': ...})
201
+ - Always sets `type` to 'function'
202
+ - Logs warnings for any repairs made
203
+
204
+ This makes the integration more resilient when working with models that may sometimes produce malformed tool calls.
205
+
206
+ ## Contributing
207
+
208
+ We welcome contributions! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) file for details.
209
+
210
+ ## License
211
+
212
+ This project is licensed under the MIT License.
213
+
214
+ Llama 4, Llama AI API, etc trademarks belong to their respective owners (Meta)
215
+ I just made this to make my life easier and thought I'd share. 😊
@@ -0,0 +1,18 @@
1
+ """LangChain <> Meta Llama API integration package."""
2
+
3
+ __version__ = "0.3.8"
4
+
5
+ from langchain_meta.chat_meta_llama.serialization import (
6
+ serialize_message,
7
+ )
8
+ from langchain_meta.chat_models import (
9
+ ChatMetaLlama,
10
+ )
11
+ from langchain_meta.utils import extract_json_response, meta_agent_factory
12
+
13
+ __all__ = [
14
+ "ChatMetaLlama",
15
+ "meta_agent_factory",
16
+ "extract_json_response",
17
+ "serialize_message",
18
+ ]