style: .. code-block:: admonition translations (#33400)

biiiiiiiiiiiiiiiigggggggg pass
This commit is contained in:
Mason Daugherty
2025-10-09 16:52:58 -04:00
committed by GitHub
parent 50445d4a27
commit 6fc21afbc9
199 changed files with 10133 additions and 10940 deletions

View File

@@ -7,56 +7,56 @@ Supported values are `None`, `'v0'`, and `'responses/v1'`.
`'v0'` corresponds to the format as of `ChatOpenAI` v0.3. For the Responses API, it
stores reasoning and tool outputs in `AIMessage.additional_kwargs`:
.. code-block:: python
AIMessage(
content=[
{"type": "text", "text": "Hello, world!", "annotations": [{"type": "foo"}]}
],
additional_kwargs={
"reasoning": {
"type": "reasoning",
"id": "rs_123",
"summary": [{"type": "summary_text", "text": "Reasoning summary"}],
},
"tool_outputs": [
{
"type": "web_search_call",
"id": "websearch_123",
"status": "completed",
}
],
"refusal": "I cannot assist with that.",
```python
AIMessage(
content=[
{"type": "text", "text": "Hello, world!", "annotations": [{"type": "foo"}]}
],
additional_kwargs={
"reasoning": {
"type": "reasoning",
"id": "rs_123",
"summary": [{"type": "summary_text", "text": "Reasoning summary"}],
},
response_metadata={"id": "resp_123"},
id="msg_123",
)
"tool_outputs": [
{
"type": "web_search_call",
"id": "websearch_123",
"status": "completed",
}
],
"refusal": "I cannot assist with that.",
},
response_metadata={"id": "resp_123"},
id="msg_123",
)
```
`'responses/v1'` is only applicable to the Responses API. It retains information
about response item sequencing and accommodates multiple reasoning items by
representing these items in the content sequence:
.. code-block:: python
AIMessage(
content=[
{
"type": "reasoning",
"summary": [{"type": "summary_text", "text": "Reasoning summary"}],
"id": "rs_123",
},
{
"type": "text",
"text": "Hello, world!",
"annotations": [{"type": "foo"}],
"id": "msg_123",
},
{"type": "refusal", "refusal": "I cannot assist with that."},
{"type": "web_search_call", "id": "websearch_123", "status": "completed"},
],
response_metadata={"id": "resp_123"},
id="resp_123",
)
```python
AIMessage(
content=[
{
"type": "reasoning",
"summary": [{"type": "summary_text", "text": "Reasoning summary"}],
"id": "rs_123",
},
{
"type": "text",
"text": "Hello, world!",
"annotations": [{"type": "foo"}],
"id": "msg_123",
},
{"type": "refusal", "refusal": "I cannot assist with that."},
{"type": "web_search_call", "id": "websearch_123", "status": "completed"},
],
response_metadata={"id": "resp_123"},
id="resp_123",
)
```
There are other, small improvements as well-- e.g., we store message IDs on text
content blocks, rather than on the AIMessage.id, which now stores the response ID.

File diff suppressed because it is too large Load Diff

View File

@@ -28,14 +28,14 @@ class AzureOpenAIEmbeddings(OpenAIEmbeddings): # type: ignore[override]
instance and key. You can find the key in the Azure Portal,
under the “Keys and Endpoint” section of your instance.
.. code-block:: bash
```bash
pip install -U langchain_openai
pip install -U langchain_openai
# Set up your environment variables (or pass them directly to the model)
export AZURE_OPENAI_API_KEY="your-api-key"
export AZURE_OPENAI_ENDPOINT="https://<your-endpoint>.openai.azure.com/"
export AZURE_OPENAI_API_VERSION="2024-02-01"
# Set up your environment variables (or pass them directly to the model)
export AZURE_OPENAI_API_KEY="your-api-key"
export AZURE_OPENAI_ENDPOINT="https://<your-endpoint>.openai.azure.com/"
export AZURE_OPENAI_API_VERSION="2024-02-01"
```
Key init args — completion params:
model: str
@@ -45,61 +45,58 @@ class AzureOpenAIEmbeddings(OpenAIEmbeddings): # type: ignore[override]
if the underlying model supports it.
Key init args — client params:
api_key: SecretStr | None
api_key: SecretStr | None
See full list of supported init args and their descriptions in the params section.
Instantiate:
.. code-block:: python
```python
from langchain_openai import AzureOpenAIEmbeddings
from langchain_openai import AzureOpenAIEmbeddings
embeddings = AzureOpenAIEmbeddings(
model="text-embedding-3-large"
# dimensions: int | None = None, # Can specify dimensions with new text-embedding-3 models
# azure_endpoint="https://<your-endpoint>.openai.azure.com/", If not provided, will read env variable AZURE_OPENAI_ENDPOINT
# api_key=... # Can provide an API key directly. If missing read env variable AZURE_OPENAI_API_KEY
# openai_api_version=..., # If not provided, will read env variable AZURE_OPENAI_API_VERSION
)
embeddings = AzureOpenAIEmbeddings(
model="text-embedding-3-large"
# dimensions: int | None = None, # Can specify dimensions with new text-embedding-3 models
# azure_endpoint="https://<your-endpoint>.openai.azure.com/", If not provided, will read env variable AZURE_OPENAI_ENDPOINT
# api_key=... # Can provide an API key directly. If missing read env variable AZURE_OPENAI_API_KEY
# openai_api_version=..., # If not provided, will read env variable AZURE_OPENAI_API_VERSION
)
```
Embed single text:
.. code-block:: python
input_text = "The meaning of life is 42"
vector = embed.embed_query(input_text)
print(vector[:3])
.. code-block:: python
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```python
input_text = "The meaning of life is 42"
vector = embed.embed_query(input_text)
print(vector[:3])
```
```python
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```
Embed multiple texts:
.. code-block:: python
input_texts = ["Document 1...", "Document 2..."]
```python
input_texts = ["Document 1...", "Document 2..."]
```
vectors = embed.embed_documents(input_texts)
print(len(vectors))
# The first 3 coordinates for the first vector
print(vectors[0][:3])
.. code-block:: python
2
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```python
2
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```
Async:
.. code-block:: python
vector = await embed.aembed_query(input_text)
print(vector[:3])
# multiple:
# await embed.aembed_documents(input_texts)
.. code-block:: python
[-0.009100092574954033, 0.005071679595857859, -0.0029193938244134188]
```python
vector = await embed.aembed_query(input_text)
print(vector[:3])
# multiple:
# await embed.aembed_documents(input_texts)
```
```python
[-0.009100092574954033, 0.005071679595857859, -0.0029193938244134188]
```
""" # noqa: E501
azure_endpoint: str | None = Field(

View File

@@ -84,10 +84,10 @@ class OpenAIEmbeddings(BaseModel, Embeddings):
Setup:
Install `langchain_openai` and set environment variable `OPENAI_API_KEY`.
.. code-block:: bash
pip install -U langchain_openai
export OPENAI_API_KEY="your-api-key"
```bash
pip install -U langchain_openai
export OPENAI_API_KEY="your-api-key"
```
Key init args — embedding params:
model: str
@@ -110,55 +110,51 @@ class OpenAIEmbeddings(BaseModel, Embeddings):
See full list of supported init args and their descriptions in the params section.
Instantiate:
.. code-block:: python
```python
from langchain_openai import OpenAIEmbeddings
from langchain_openai import OpenAIEmbeddings
embed = OpenAIEmbeddings(
model="text-embedding-3-large"
# With the `text-embedding-3` class
# of models, you can specify the size
# of the embeddings you want returned.
# dimensions=1024
)
embed = OpenAIEmbeddings(
model="text-embedding-3-large"
# With the `text-embedding-3` class
# of models, you can specify the size
# of the embeddings you want returned.
# dimensions=1024
)
```
Embed single text:
.. code-block:: python
input_text = "The meaning of life is 42"
vector = embeddings.embed_query("hello")
print(vector[:3])
.. code-block:: python
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```python
input_text = "The meaning of life is 42"
vector = embeddings.embed_query("hello")
print(vector[:3])
```
```python
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```
Embed multiple texts:
.. code-block:: python
vectors = embeddings.embed_documents(["hello", "goodbye"])
# Showing only the first 3 coordinates
print(len(vectors))
print(vectors[0][:3])
.. code-block:: python
2
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```python
vectors = embeddings.embed_documents(["hello", "goodbye"])
# Showing only the first 3 coordinates
print(len(vectors))
print(vectors[0][:3])
```
```python
2
[-0.024603435769677162, -0.007543657906353474, 0.0039630369283258915]
```
Async:
.. code-block:: python
await embed.aembed_query(input_text)
print(vector[:3])
# multiple:
# await embed.aembed_documents(input_texts)
.. code-block:: python
[-0.009100092574954033, 0.005071679595857859, -0.0029193938244134188]
```python
await embed.aembed_query(input_text)
print(vector[:3])
# multiple:
# await embed.aembed_documents(input_texts)
```
```python
[-0.009100092574954033, 0.005071679595857859, -0.0029193938244134188]
```
"""
client: Any = Field(default=None, exclude=True) #: :meta private:

View File

@@ -27,12 +27,11 @@ class AzureOpenAI(BaseOpenAI):
in, even if not explicitly saved on this class.
Example:
.. code-block:: python
from langchain_openai import AzureOpenAI
openai = AzureOpenAI(model_name="gpt-3.5-turbo-instruct")
```python
from langchain_openai import AzureOpenAI
openai = AzureOpenAI(model_name="gpt-3.5-turbo-instruct")
```
"""
azure_endpoint: str | None = Field(

View File

@@ -56,10 +56,10 @@ class BaseOpenAI(BaseLLM):
Setup:
Install `langchain-openai` and set environment variable `OPENAI_API_KEY`.
.. code-block:: bash
pip install -U langchain-openai
export OPENAI_API_KEY="your-api-key"
```bash
pip install -U langchain-openai
export OPENAI_API_KEY="your-api-key"
```
Key init args — completion params:
model_name: str
@@ -107,62 +107,60 @@ class BaseOpenAI(BaseLLM):
See full list of supported init args and their descriptions in the params section.
Instantiate:
.. code-block:: python
```python
from langchain_openai.llms.base import BaseOpenAI
from langchain_openai.llms.base import BaseOpenAI
llm = BaseOpenAI(
model_name="gpt-3.5-turbo-instruct",
temperature=0.7,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
# openai_api_key="...",
# openai_api_base="...",
# openai_organization="...",
# other params...
)
llm = BaseOpenAI(
model_name="gpt-3.5-turbo-instruct",
temperature=0.7,
max_tokens=256,
top_p=1,
frequency_penalty=0,
presence_penalty=0,
# openai_api_key="...",
# openai_api_base="...",
# openai_organization="...",
# other params...
)
```
Invoke:
.. code-block:: python
```python
input_text = "The meaning of life is "
response = llm.invoke(input_text)
print(response)
```
input_text = "The meaning of life is "
response = llm.invoke(input_text)
print(response)
.. code-block::
"a philosophical question that has been debated by thinkers and
scholars for centuries."
```txt
"a philosophical question that has been debated by thinkers and
scholars for centuries."
```
Stream:
.. code-block:: python
for chunk in llm.stream(input_text):
print(chunk, end="")
.. code-block::
a philosophical question that has been debated by thinkers and
scholars for centuries.
```python
for chunk in llm.stream(input_text):
print(chunk, end="")
```
```txt
a philosophical question that has been debated by thinkers and
scholars for centuries.
```
Async:
.. code-block:: python
```python
response = await llm.ainvoke(input_text)
response = await llm.ainvoke(input_text)
# stream:
# async for chunk in llm.astream(input_text):
# print(chunk, end="")
# stream:
# async for chunk in llm.astream(input_text):
# print(chunk, end="")
# batch:
# await llm.abatch([input_text])
.. code-block::
"a philosophical question that has been debated by thinkers and
scholars for centuries."
# batch:
# await llm.abatch([input_text])
```
```
"a philosophical question that has been debated by thinkers and
scholars for centuries."
```
"""
@@ -404,10 +402,9 @@ class BaseOpenAI(BaseLLM):
The full LLM output.
Example:
.. code-block:: python
response = openai.generate(["Tell me a joke."])
```python
response = openai.generate(["Tell me a joke."])
```
"""
# TODO: write a unit test for this
params = self._invocation_params
@@ -626,10 +623,9 @@ class BaseOpenAI(BaseLLM):
The maximum context size
Example:
.. code-block:: python
max_tokens = openai.modelname_to_contextsize("gpt-3.5-turbo-instruct")
```python
max_tokens = openai.modelname_to_contextsize("gpt-3.5-turbo-instruct")
```
"""
model_token_mapping = {
"gpt-4o-mini": 128_000,
@@ -691,10 +687,9 @@ class BaseOpenAI(BaseLLM):
The maximum number of tokens to generate for a prompt.
Example:
.. code-block:: python
max_tokens = openai.max_tokens_for_prompt("Tell me a joke.")
```python
max_tokens = openai.max_tokens_for_prompt("Tell me a joke.")
```
"""
num_tokens = self.get_num_tokens(prompt)
return self.max_context_size - num_tokens
@@ -706,10 +701,10 @@ class OpenAI(BaseOpenAI):
Setup:
Install `langchain-openai` and set environment variable `OPENAI_API_KEY`.
.. code-block:: bash
pip install -U langchain-openai
export OPENAI_API_KEY="your-api-key"
```bash
pip install -U langchain-openai
export OPENAI_API_KEY="your-api-key"
```
Key init args — completion params:
model: str
@@ -741,64 +736,59 @@ class OpenAI(BaseOpenAI):
See full list of supported init args and their descriptions in the params section.
Instantiate:
.. code-block:: python
```python
from langchain_openai import OpenAI
from langchain_openai import OpenAI
llm = OpenAI(
model="gpt-3.5-turbo-instruct",
temperature=0,
max_retries=2,
# api_key="...",
# base_url="...",
# organization="...",
# other params...
)
llm = OpenAI(
model="gpt-3.5-turbo-instruct",
temperature=0,
max_retries=2,
# api_key="...",
# base_url="...",
# organization="...",
# other params...
)
```
Invoke:
.. code-block:: python
input_text = "The meaning of life is "
llm.invoke(input_text)
.. code-block::
"a philosophical question that has been debated by thinkers and scholars for centuries."
```python
input_text = "The meaning of life is "
llm.invoke(input_text)
```
```txt
"a philosophical question that has been debated by thinkers and scholars for centuries."
```
Stream:
.. code-block:: python
```python
for chunk in llm.stream(input_text):
print(chunk, end="|")
```
```txt
a| philosophical| question| that| has| been| debated| by| thinkers| and| scholars| for| centuries|.
```
for chunk in llm.stream(input_text):
print(chunk, end="|")
.. code-block::
a| philosophical| question| that| has| been| debated| by| thinkers| and| scholars| for| centuries|.
.. code-block:: python
"".join(llm.stream(input_text))
.. code-block::
"a philosophical question that has been debated by thinkers and scholars for centuries."
```python
"".join(llm.stream(input_text))
```
```txt
"a philosophical question that has been debated by thinkers and scholars for centuries."
```
Async:
.. code-block:: python
```python
await llm.ainvoke(input_text)
await llm.ainvoke(input_text)
# stream:
# async for chunk in (await llm.astream(input_text)):
# print(chunk)
# batch:
# await llm.abatch([input_text])
.. code-block::
"a philosophical question that has been debated by thinkers and scholars for centuries."
# stream:
# async for chunk in (await llm.astream(input_text)):
# print(chunk)
# batch:
# await llm.abatch([input_text])
```
```txt
"a philosophical question that has been debated by thinkers and scholars for centuries."
```
""" # noqa: E501
@classmethod

View File

@@ -31,65 +31,65 @@ def custom_tool(*args: Any, **kwargs: Any) -> Any:
See below for an example using LangGraph:
.. code-block:: python
@custom_tool
def execute_code(code: str) -> str:
\"\"\"Execute python code.\"\"\"
return "27"
```python
@custom_tool
def execute_code(code: str) -> str:
\"\"\"Execute python code.\"\"\"
return "27"
llm = ChatOpenAI(model="gpt-5", output_version="responses/v1")
llm = ChatOpenAI(model="gpt-5", output_version="responses/v1")
agent = create_react_agent(llm, [execute_code])
agent = create_react_agent(llm, [execute_code])
input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
for step in agent.stream(
{"messages": [input_message]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
for step in agent.stream(
{"messages": [input_message]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
```
You can also specify a format for a corresponding context-free grammar using the
`format` kwarg:
.. code-block:: python
```python
from langchain_openai import ChatOpenAI, custom_tool
from langgraph.prebuilt import create_react_agent
from langchain_openai import ChatOpenAI, custom_tool
from langgraph.prebuilt import create_react_agent
grammar = \"\"\"
start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT
\"\"\"
grammar = \"\"\"
start: expr
expr: term (SP ADD SP term)* -> add
| term
term: factor (SP MUL SP factor)* -> mul
| factor
factor: INT
SP: " "
ADD: "+"
MUL: "*"
%import common.INT
\"\"\"
format = {"type": "grammar", "syntax": "lark", "definition": grammar}
format = {"type": "grammar", "syntax": "lark", "definition": grammar}
# highlight-next-line
@custom_tool(format=format)
def do_math(input_string: str) -> str:
\"\"\"Do a mathematical operation.\"\"\"
return "27"
# highlight-next-line
@custom_tool(format=format)
def do_math(input_string: str) -> str:
\"\"\"Do a mathematical operation.\"\"\"
return "27"
llm = ChatOpenAI(model="gpt-5", output_version="responses/v1")
llm = ChatOpenAI(model="gpt-5", output_version="responses/v1")
agent = create_react_agent(llm, [do_math])
agent = create_react_agent(llm, [do_math])
input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
for step in agent.stream(
{"messages": [input_message]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
input_message = {"role": "user", "content": "Use the tool to calculate 3^3."}
for step in agent.stream(
{"messages": [input_message]},
stream_mode="values",
):
step["messages"][-1].pretty_print()
```
"""
def decorator(func: Callable[..., Any]) -> Any: