-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
9 changed files
with
602 additions
and
124 deletions.
There are no files selected for viewing
119 changes: 119 additions & 0 deletions
119
...instrumentation/openinference-instrumentation-groq/examples/chat_completions_with_tool.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
import asyncio | ||
import os | ||
|
||
from groq import AsyncGroq, Groq | ||
from groq.types.chat import ChatCompletionToolParam | ||
from phoenix.otel import register | ||
|
||
from openinference.instrumentation.groq import GroqInstrumentor | ||
|
||
|
||
def test(): | ||
client = Groq( | ||
api_key=os.environ.get("GROQ_API_KEY"), | ||
) | ||
|
||
weather_function = { | ||
"type": "function", | ||
"function": { | ||
"name": "get_weather", | ||
"description": "finds the weather for a given city", | ||
"parameters": { | ||
"type": "object", | ||
"properties": { | ||
"city": { | ||
"type": "string", | ||
"description": "The city to find the weather for, e.g. 'London'", | ||
} | ||
}, | ||
"required": ["city"], | ||
}, | ||
}, | ||
} | ||
|
||
sys_prompt = "Respond to the user's query using the correct tool." | ||
user_msg = "What's the weather like in San Francisco?" | ||
|
||
messages = [{"role": "system", "content": sys_prompt}, {"role": "user", "content": user_msg}] | ||
response = client.chat.completions.create( | ||
model="mixtral-8x7b-32768", | ||
messages=messages, | ||
temperature=0.0, | ||
tools=[weather_function], | ||
tool_choice="required", | ||
) | ||
|
||
message = response.choices[0].message | ||
assert (tool_calls := message.tool_calls) | ||
tool_call_id = tool_calls[0].id | ||
messages.append(message) | ||
messages.append( | ||
ChatCompletionToolParam(content="sunny", role="tool", tool_call_id=tool_call_id), | ||
) | ||
final_response = client.chat.completions.create( | ||
model="mixtral-8x7b-32768", | ||
messages=messages, | ||
) | ||
return final_response | ||
|
||
|
||
async def async_test(): | ||
client = AsyncGroq( | ||
api_key=os.environ.get("GROQ_API_KEY"), | ||
) | ||
|
||
weather_function = { | ||
"type": "function", | ||
"function": { | ||
"name": "get_weather", | ||
"description": "finds the weather for a given city", | ||
"parameters": { | ||
"type": "object", | ||
"properties": { | ||
"city": { | ||
"type": "string", | ||
"description": "The city to find the weather for, e.g. 'London'", | ||
} | ||
}, | ||
"required": ["city"], | ||
}, | ||
}, | ||
} | ||
|
||
sys_prompt = "Respond to the user's query using the correct tool." | ||
user_msg = "What's the weather like in San Francisco?" | ||
|
||
messages = [{"role": "system", "content": sys_prompt}, {"role": "user", "content": user_msg}] | ||
response = await client.chat.completions.create( | ||
model="mixtral-8x7b-32768", | ||
messages=messages, | ||
temperature=0.0, | ||
tools=[weather_function], | ||
tool_choice="required", | ||
) | ||
|
||
message = response.choices[0].message | ||
assert (tool_calls := message.tool_calls) | ||
tool_call_id = tool_calls[0].id | ||
messages.append(message) | ||
messages.append( | ||
ChatCompletionToolParam(content="sunny", role="tool", tool_call_id=tool_call_id), | ||
) | ||
final_response = await client.chat.completions.create( | ||
model="mixtral-8x7b-32768", | ||
messages=messages, | ||
) | ||
return final_response | ||
|
||
|
||
if __name__ == "__main__": | ||
tracer_provider = register(project_name="groq_debug") | ||
GroqInstrumentor().instrument(tracer_provider=tracer_provider) | ||
|
||
response = test() | ||
print("Response\n--------") | ||
print(response) | ||
|
||
async_response = asyncio.run(async_test()) | ||
print("\nAsync Response\n--------") | ||
print(async_response) |
41 changes: 0 additions & 41 deletions
41
python/instrumentation/openinference-instrumentation-groq/examples/tool_call.py
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
98
...rumentation-groq/src/openinference/instrumentation/groq/_response_attributes_extractor.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
import logging | ||
from typing import Any, Iterable, Iterator, Mapping, Tuple | ||
|
||
from opentelemetry.util.types import AttributeValue | ||
|
||
from openinference.instrumentation.groq._utils import _as_output_attributes, _io_value_and_type | ||
from openinference.semconv.trace import MessageAttributes, SpanAttributes, ToolCallAttributes | ||
|
||
__all__ = ("_ResponseAttributesExtractor",) | ||
|
||
logger = logging.getLogger(__name__) | ||
logger.addHandler(logging.NullHandler()) | ||
|
||
|
||
class _ResponseAttributesExtractor: | ||
__slots__ = () | ||
|
||
def get_attributes(self, response: Any) -> Iterator[Tuple[str, AttributeValue]]: | ||
yield from _as_output_attributes( | ||
_io_value_and_type(response), | ||
) | ||
|
||
def get_extra_attributes( | ||
self, | ||
response: Any, | ||
request_parameters: Mapping[str, Any], | ||
) -> Iterator[Tuple[str, AttributeValue]]: | ||
yield from self._get_attributes_from_chat_completion( | ||
completion=response, | ||
request_parameters=request_parameters, | ||
) | ||
|
||
def _get_attributes_from_chat_completion( | ||
self, | ||
completion: Any, | ||
request_parameters: Mapping[str, Any], | ||
) -> Iterator[Tuple[str, AttributeValue]]: | ||
if model := getattr(completion, "model", None): | ||
yield SpanAttributes.LLM_MODEL_NAME, model | ||
if usage := getattr(completion, "usage", None): | ||
yield from self._get_attributes_from_completion_usage(usage) | ||
if (choices := getattr(completion, "choices", None)) and isinstance(choices, Iterable): | ||
for choice in choices: | ||
if (index := getattr(choice, "index", None)) is None: | ||
continue | ||
if message := getattr(choice, "message", None): | ||
for key, value in self._get_attributes_from_chat_completion_message(message): | ||
yield f"{SpanAttributes.LLM_OUTPUT_MESSAGES}.{index}.{key}", value | ||
|
||
def _get_attributes_from_chat_completion_message( | ||
self, | ||
message: object, | ||
) -> Iterator[Tuple[str, AttributeValue]]: | ||
if role := getattr(message, "role", None): | ||
yield MessageAttributes.MESSAGE_ROLE, role | ||
if content := getattr(message, "content", None): | ||
yield MessageAttributes.MESSAGE_CONTENT, content | ||
if function_call := getattr(message, "function_call", None): | ||
if name := getattr(function_call, "name", None): | ||
yield MessageAttributes.MESSAGE_FUNCTION_CALL_NAME, name | ||
if arguments := getattr(function_call, "arguments", None): | ||
yield MessageAttributes.MESSAGE_FUNCTION_CALL_ARGUMENTS_JSON, arguments | ||
if (tool_calls := getattr(message, "tool_calls", None)) and isinstance( | ||
tool_calls, Iterable | ||
): | ||
for index, tool_call in enumerate(tool_calls): | ||
if (tool_call_id := getattr(tool_call, "id", None)) is not None: | ||
yield ( | ||
f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{index}." | ||
f"{ToolCallAttributes.TOOL_CALL_ID}", | ||
tool_call_id, | ||
) | ||
if function := getattr(tool_call, "function", None): | ||
if name := getattr(function, "name", None): | ||
yield ( | ||
( | ||
f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{index}." | ||
f"{ToolCallAttributes.TOOL_CALL_FUNCTION_NAME}" | ||
), | ||
name, | ||
) | ||
if arguments := getattr(function, "arguments", None): | ||
yield ( | ||
f"{MessageAttributes.MESSAGE_TOOL_CALLS}.{index}." | ||
f"{ToolCallAttributes.TOOL_CALL_FUNCTION_ARGUMENTS_JSON}", | ||
arguments, | ||
) | ||
|
||
def _get_attributes_from_completion_usage( | ||
self, | ||
usage: object, | ||
) -> Iterator[Tuple[str, AttributeValue]]: | ||
if (total_tokens := getattr(usage, "total_tokens", None)) is not None: | ||
yield SpanAttributes.LLM_TOKEN_COUNT_TOTAL, total_tokens | ||
if (prompt_tokens := getattr(usage, "prompt_tokens", None)) is not None: | ||
yield SpanAttributes.LLM_TOKEN_COUNT_PROMPT, prompt_tokens | ||
if (completion_tokens := getattr(usage, "completion_tokens", None)) is not None: | ||
yield SpanAttributes.LLM_TOKEN_COUNT_COMPLETION, completion_tokens |
Oops, something went wrong.