Back to Mistral Rs

embedding

docs/src/content/docs/examples/server/embedding.md

0.9.21.7 KB
Original Source
<!-- generated by docs/scripts/render_examples.py; edit the source example instead -->

Runnable HTTP server example embedding.

<!-- needs-header -->
python
from openai import OpenAI
import httpx
import textwrap
import json


def log_response(response: httpx.Response):
    request = response.request
    print(f"Request: {request.method} {request.url}")
    print("  Headers:")
    for key, value in request.headers.items():
        if key.lower() == "authorization":
            value = "[...]"
        if key.lower() == "cookie":
            value = value.split("=")[0] + "=..."
        print(f"    {key}: {value}")
    print("  Body:")
    try:
        request_body = json.loads(request.content)
        print(textwrap.indent(json.dumps(request_body, indent=2), "    "))
    except json.JSONDecodeError:
        print(textwrap.indent(request.content.decode(), "    "))
    print(f"Response: status_code={response.status_code}")
    print("  Headers:")
    for key, value in response.headers.items():
        if key.lower() == "set-cookie":
            value = value.split("=")[0] + "=..."
        print(f"    {key}: {value}")


client = OpenAI(api_key="foobar", base_url="http://localhost:1234/v1/")

# Enable this to log requests and responses
# client._client = httpx.Client(
#     event_hooks={"request": [print], "response": [log_response]}
# )

res = client.embeddings.create(
    model="default",
    input=[
        "task: search result | query: What is graphene?",
        "task: search result | query: What is an apple?",
    ],
)

print(res.data[0].embedding[:10])
print(res.data[1].embedding[:10])
print(res.usage)

Source: examples/server/embedding.py