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

update cohere to use tool call attribute on AIMessage #7

Merged
merged 5 commits into from
Apr 10, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
80 changes: 72 additions & 8 deletions libs/cohere/langchain_cohere/chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@
HumanMessage,
SystemMessage,
)
from langchain_core.messages import (
ToolCall as LC_ToolCall,
)
from langchain_core.output_parsers.base import OutputParserLike
from langchain_core.output_parsers.openai_tools import (
JsonOutputKeyToolsParser,
Expand Down Expand Up @@ -250,10 +253,27 @@ def _stream(
yield chunk
elif data.event_type == "stream-end":
generation_info = self._get_generation_info(data.response)
tool_call_chunks = []
if tool_calls := generation_info.get("tool_calls"):
try:
tool_call_chunks = [
{
"name": tool_call["function"].get("name"),
"args": tool_call["function"].get("arguments"),
"id": tool_call.get("id"),
"index": tool_call.get("index"),
}
for tool_call in tool_calls
]
except KeyError:
pass
message = AIMessageChunk(
content="",
additional_kwargs=generation_info,
tool_call_chunks=tool_call_chunks,
)
yield ChatGenerationChunk(
message=AIMessageChunk(
content="", additional_kwargs=generation_info
),
message=message,
generation_info=generation_info,
)

Expand Down Expand Up @@ -282,10 +302,27 @@ async def _astream(
yield chunk
elif data.event_type == "stream-end":
generation_info = self._get_generation_info(data.response)
tool_call_chunks = []
if tool_calls := generation_info.get("tool_calls"):
try:
tool_call_chunks = [
{
"name": tool_call["function"].get("name"),
"args": tool_call["function"].get("arguments"),
"id": tool_call.get("id"),
"index": tool_call.get("index"),
}
for tool_call in tool_calls
]
except KeyError:
pass
message = AIMessageChunk(
content="",
additional_kwargs=generation_info,
tool_call_chunks=tool_call_chunks,
)
yield ChatGenerationChunk(
message=AIMessageChunk(
content="", additional_kwargs=generation_info
),
message=message,
generation_info=generation_info,
)

Expand Down Expand Up @@ -328,7 +365,18 @@ def _generate(
response = self.client.chat(**request)

generation_info = self._get_generation_info(response)
message = AIMessage(content=response.text, additional_kwargs=generation_info)
if "tool_calls" in generation_info:
tool_calls = [
_convert_cohere_tool_call_to_langchain(tool_call)
for tool_call in response.tool_calls
]
else:
tool_calls = []
message = AIMessage(
content=response.text,
additional_kwargs=generation_info,
tool_calls=tool_calls,
)
return ChatResult(
generations=[
ChatGeneration(message=message, generation_info=generation_info)
Expand All @@ -354,7 +402,18 @@ async def _agenerate(
response = self.client.chat(**request)

generation_info = self._get_generation_info(response)
message = AIMessage(content=response.text, additional_kwargs=generation_info)
if "tool_calls" in generation_info:
tool_calls = [
_convert_cohere_tool_call_to_langchain(tool_call)
for tool_call in response.tool_calls
]
else:
tool_calls = []
message = AIMessage(
content=response.text,
additional_kwargs=generation_info,
tool_calls=tool_calls,
)
return ChatResult(
generations=[
ChatGeneration(message=message, generation_info=generation_info)
Expand Down Expand Up @@ -388,3 +447,8 @@ def _format_cohere_tool_calls(
}
)
return formatted_tool_calls


def _convert_cohere_tool_call_to_langchain(tool_call: ToolCall) -> LC_ToolCall:
"""Convert a Cohere tool call into langchain_core.messages.ToolCall"""
return LC_ToolCall(name=tool_call.name, args=tool_call.parameters, id=None)
10 changes: 5 additions & 5 deletions libs/cohere/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions libs/cohere/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "langchain-cohere"
version = "0.1.1"
version = "0.1.2-rc1"
description = "An integration package connecting Cohere and LangChain"
authors = []
readme = "README.md"
Expand All @@ -12,7 +12,7 @@ license = "MIT"

[tool.poetry.dependencies]
python = ">=3.8.1,<4.0"
langchain-core = "^0.1.32"
langchain-core = {version ="^0.1.42-rc.1", allow-prereleases=true}
cohere = ">=5.1.8,<5.2"

[tool.poetry.group.test]
Expand Down
16 changes: 15 additions & 1 deletion libs/cohere/tests/integration_tests/test_chat_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@
from typing import Any

import pytest
from langchain_core.messages import AIMessage, AIMessageChunk
from langchain_core.messages import (
AIMessage,
AIMessageChunk,
ToolCall,
)
from langchain_core.pydantic_v1 import BaseModel, Field

from langchain_cohere import ChatCohere
Expand Down Expand Up @@ -92,6 +96,9 @@ class Person(BaseModel):
"name": "Erick",
"age": 27,
}
assert result.tool_calls == [
ToolCall(name="Person", args={"age": 27, "name": "Erick"}, id=None)
]


def test_streaming_tool_call() -> None:
Expand Down Expand Up @@ -120,6 +127,13 @@ class Person(BaseModel):
"name": "Erick",
"age": 27,
}
assert isinstance(chunk, AIMessageChunk)
assert isinstance(chunk.tool_call_chunks, list)
assert len(chunk.tool_call_chunks) == 1
tool_call_chunk = chunk.tool_call_chunks[0]
assert tool_call_chunk["name"] == "Person"
assert tool_call_chunk["args"] is not None
assert json.loads(tool_call_chunk["args"]) == {"name": "Erick", "age": 27}


@pytest.mark.xfail(
Expand Down
Loading